text stringlengths 10 2.72M |
|---|
class Solution {
public boolean detectCapitalUse(String word) {
if(Character.isLowerCase(word.charAt(0))){
return checkAllSmall(word);
} else {
return checkAllCapital(word) || checkFirstCapital(word);
}
}
public boolean checkAllCapital(String word){
for(char c: word.toCharArray()){
if(!Character.isUpperCase(c)) return false;
}
return true;
}
public boolean checkAllSmall(String word){
for(char c: word.toCharArray()){
if(!Character.isLowerCase(c)) return false;
}
return true;
}
public boolean checkFirstCapital(String word){
for(int i=1; i<word.length();i++){
if(!Character.isLowerCase(word.charAt(i))) return false;
}
return true;
}
}
|
package com.tencent.mm.model;
import android.database.Cursor;
import com.tencent.mm.l.a;
import com.tencent.mm.sdk.e.e;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.az;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public final class bn {
private az dDh;
private e diF;
public bn(e eVar, az azVar) {
this.diF = eVar;
this.dDh = azVar;
}
public final Cursor a(String str, List<String> list, String str2) {
String str3 = " ";
String str4 = " ";
if (str2 != null && str2.length() > 0) {
str4 = " and rconversation.username = rcontact.username ";
}
String str5 = "select 1,unReadCount, status, isSend, conversationTime, rconversation.username, content, rconversation.msgType, rconversation.flag, rcontact.nickname from rconversation," + "rcontact" + str3 + " where rconversation.username = rcontact.username" + str4 + bi.oV(str);
str4 = "";
if (list != null && list.size() > 0) {
Iterator it = list.iterator();
while (true) {
str3 = str4;
if (!it.hasNext()) {
break;
}
str4 = str3 + " and rconversation.username != '" + ((String) it.next()) + "'";
}
str4 = str3;
}
str4 = str5 + str4;
if (str2 != null && str2.length() > 0) {
str4 = str4 + iJ(str2);
}
x.v("Micro.SimpleSearchConversationModel", "convsql %s", new Object[]{((str4 + " order by ") + "rconversation.username like '%@chatroom' asc, ") + "flag desc, conversationTime desc"});
return this.diF.rawQuery(((str4 + " order by ") + "rconversation.username like '%@chatroom' asc, ") + "flag desc, conversationTime desc", null);
}
private String iJ(String str) {
String string;
String str2;
String str3 = "";
ArrayList arrayList = new ArrayList();
Cursor b = this.diF.b("select username from rcontact where (username like '%" + str + "%' or nickname like '%" + str + "%' or alias like '%" + str + "%' or pyInitial like '%" + str + "%' or quanPin like '%" + str + "%' or conRemark like '%" + str + "%' )and username not like '%@%' and type & " + a.Bw() + "=0 ", null, 2);
x.v("Micro.SimpleSearchConversationModel", "contactsql %s", new Object[]{string});
while (b.moveToNext()) {
string = b.getString(b.getColumnIndex("username"));
if (!string.endsWith("@chatroom")) {
arrayList.add(string);
}
}
b.close();
if (arrayList.size() != 0) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(" ( rconversation.username in ( select chatroomname from chatroom where ");
stringBuffer.append("memberlist like '%" + str + "%'");
Iterator it = arrayList.iterator();
while (it.hasNext()) {
stringBuffer.append(" or memberlist like '%" + ((String) it.next()) + "%'");
}
stringBuffer.append("))");
str2 = str3 + stringBuffer.toString() + " or ";
} else {
str2 = str3;
}
return " and ( rconversation.username like '%" + str + "%' or " + str2 + "rconversation.content like '%" + str + "%' or rcontact.nickname like '%" + str + "%' or rcontact.alias like '%" + str + "%' or rcontact.pyInitial like '%" + str + "%' or rcontact.quanPin like '%" + str + "%' or rcontact.conRemark like '%" + str + "%' ) ";
}
}
|
package com.newer.domain;
public class hzx {
private String name;
public hzx() {
}
public hzx(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void tsb (){
System.out.println("haha ");
}
}
|
package encapsulation;
public class ClassE {
public static void someMethod(){
ClassA instanceOne = new ClassA();
//instanceOne.setVariable(1000.12341234);
}
}
|
package sample;
import java.awt.*;
import java.util.InputMismatchException;
import java.util.Scanner;
import javafx.scene.control.Button;
public class HumanPlayer extends Player {
PlayerTimer playertimer;
public HumanPlayer(){
}
@Override
public playerMove getplayermove(Grid grid) {
try {
playertimer = new PlayerTimer();
playertimer.start();
playerMove p = new playerMove(this);
p.setPlayer(this);
Scanner scan = new Scanner(System.in);
System.out.print("enter the Row: ");
int r = scan.nextInt();
System.out.print("enter the Column: ");
char c = scan.next().charAt(0);
int c1 = Character.toUpperCase(c);
if (c1 < 65 || c1 > 91) {
System.out.println("you're not entering a character ! try again");
return getplayermove(grid);
}
if (!playertimer.isPossibleToPlay) {
System.out.println("you're out of time. ");
p.setPossibleToMove(false);
return p;
}
p.setSquare(grid.getIndex(r, c1 - 65));
System.out.println("Open = O , Flag = F :");
String stat = scan.next();
if (stat.equals("F") || stat.equals("f"))
p.setMoveType(moveType.Mark);
else if (stat.equals("!F") || stat.equals("!f"))
p.setMoveType(moveType.Unmark);
else {
p.setMoveType(moveType.Reveal);
}
if (!playertimer.isPossibleToPlay) {
System.out.println("you're out of time. ");
p.setPossibleToMove(false);
return p;
}
if (playertimer.getTimer() != 0)
playertimer.interrupt();
return p;
} catch (IndexOutOfBoundsException | NullPointerException | InputMismatchException e ) {
System.out.println("You're out of the array !!! ");
return getplayermove(grid);
}
}
}
|
package com.example.demo.controller;
import com.example.demo.error.BusinessException;
import com.example.demo.model.AyUser;
import com.example.demo.service.AyUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
/**
* 描述:用户控制层
* @author Ay
* @date 2017/10/28.
*/
@Controller
@RequestMapping("/ayUser")
public class AyUserController {
@Resource
private AyUserService ayUserService;
@RequestMapping("/test")
public String test(Model model) {
List<AyUser> ayUser = ayUserService.findAll();
model.addAttribute("users",ayUser);
return "ayUser";
}
@RequestMapping("/findAll")
public String findAll(Model model) {
List<AyUser> ayUser = ayUserService.findAll();
model.addAttribute("users",ayUser);
throw new BusinessException("业务异常");
}
@RequestMapping("/update")
public String update(Model model) {
AyUser ayUser = new AyUser();
ayUser.setId("1");
ayUser.setName("阿毅");
boolean isSuccess = ayUserService.update(ayUser);
return "success";
}
}
|
public class Kadai06 {
/**
* 課題06
* 引数として渡された配列の中で、降順で2番目の値を返す
* @param d 数値が入っている配列
* @return 配列の中の降順で2番目の値
*/
int get2ndMax(int[] d) {
return -1;
}
}
|
import org.junit.Test;
/**
* @Author: lty
* @Date: 2021/1/22 09:37
*/
public class MainTest {
@Test
public void test(){
DebugHandler debugHandler = new DebugHandler(new InfoHandler(new MyMessageHandler()));
debugHandler.execute();
}
}
|
package org.es.api.factory;
import org.es.api.WeatherApi;
import org.es.api.impl.WundergroundWeatherApi;
/**
* Created by Cyril Leroux on 18/06/13.
*/
public class WeatherApiFactory {
public static synchronized WeatherApi getWeatherAPI() {
return new WundergroundWeatherApi();
}
}
|
package com.appdear.client.update;
import java.io.File;
/**
* 处理下载通知接口
* @author jindan
*
*/
public interface FileDownloadHandlerI {
/**
*
* @param count 下载字节数
* @param total 总字节数
*/
public abstract void HandlerNocatifycation(long count,long total);
/**
* 下载失败处理
*/
public abstract void HandlerNocatifycationFail();
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/life.qbic.xml.properties/jaxb">http://java.sun.com/life.qbic.xml.properties/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.11.26 at 03:39:24 PM CET
//
package life.qbic.xml.persons;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="firstname" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="lastname" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="title" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="position" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="email" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="phone" type="{http://www.w3.org/2001/XMLSchema}int" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "qperson")
public class Qperson {
@XmlAttribute(name = "firstname", required = true)
protected String firstname;
@XmlAttribute(name = "lastname", required = true)
protected String lastname;
@XmlAttribute(name = "title")
protected String title;
@XmlAttribute(name = "position")
protected String position;
@XmlAttribute(name = "email")
protected String email;
@XmlAttribute(name = "phone")
protected Integer phone;
/**
* Gets the value of the firstname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstname() {
return firstname;
}
/**
* Sets the value of the firstname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstname(String value) {
this.firstname = value;
}
/**
* Gets the value of the lastname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastname() {
return lastname;
}
/**
* Sets the value of the lastname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastname(String value) {
this.lastname = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the position property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPosition() {
return position;
}
/**
* Sets the value of the position property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPosition(String value) {
this.position = value;
}
/**
* Gets the value of the email property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
/**
* Gets the value of the phone property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getPhone() {
return phone;
}
/**
* Sets the value of the phone property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setPhone(Integer value) {
this.phone = value;
}
}
|
package com.tyss.cg.DatatypesAndVariables;
public class VariablesEx {
static byte sGByte;
static short sGShort;
static int sGInt;
static long sGLong;
static float sGFloat;
static double sGDouble;
static char sGChar;
static boolean sGIsTrue;
static String sGString;
@SuppressWarnings("unused") //this will suppress warnings (annotation)
public static void main(String[] args) { // if we want to use global var in 'static' main method we need to make
// them static as static context will search static pool mem loc.
//for local variable initialization is mandatory while for global it is not
//local variables
byte lByte;
short lShort;
int lInt;
long lLong;
float lFloat;
double lDouble;
char lChar;
boolean lIsTrue;
String lString;
System.out.println(sGByte);
System.out.println(sGShort);
System.out.println(sGInt);
System.out.println(sGLong);
System.out.println(sGFloat);
System.out.println(sGDouble);
System.out.println(sGChar);
System.out.println(sGIsTrue);
System.out.println(sGString);
/*
* We need to initialize the local variables or error will show
*
* System.out.println(lByte); System.out.println(lShort);
* System.out.println(lInt); System.out.println(lLong);
* System.out.println(lFloat); System.out.println(lDouble);
* System.out.println(lChar); System.out.println(lIsTrue);
* System.out.println(lString);
*/
}
}
|
package com.vilio.mps.receivepush.service.impl;
import com.vilio.mps.common.pojo.MpsReceiveMessageInfo;
import com.vilio.mps.glob.ConfigInfo;
import com.vilio.mps.glob.Constants;
import com.vilio.mps.glob.Fields;
import com.vilio.mps.receivepush.pojo.NlbsMessageResp;
import com.vilio.mps.receivepush.service.PushMessage;
import com.vilio.mps.util.HttpRequestUtils;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dell on 2017/5/31.
*/
@Service
public class PushMessageImpl implements PushMessage {
public static Logger logger = Logger.getLogger(PushMessageImpl.class);
public Map pushMessageToNlbs(Map paramMap) throws Exception {
Map<String, Object> headMap = new HashMap<String, Object>();
Map<String, Object> bodyMap = new HashMap<String, Object>();
headMap.put(Fields.PARAM_FUNCTION_NO, "HH000020");
List<MpsReceiveMessageInfo> messageList = (List<MpsReceiveMessageInfo>) paramMap.get(Fields.PARAM_MPS_MESSAGELIST);
List<NlbsMessageResp> listMessageResp = new ArrayList<NlbsMessageResp>();
for(MpsReceiveMessageInfo messageReceiveInfo:messageList){
NlbsMessageResp nlbsMessageResp = new NlbsMessageResp();
nlbsMessageResp.setSerialNo(messageReceiveInfo.getSerialNo());
nlbsMessageResp.setTitle(messageReceiveInfo.getTitle());
nlbsMessageResp.setContent(messageReceiveInfo.getContent());
nlbsMessageResp.setSenderCompanyCode(messageReceiveInfo.getSenderCompanyCode());
nlbsMessageResp.setSenderCompanyName(messageReceiveInfo.getSenderCompanyName());
nlbsMessageResp.setSenderDepartmentCode(messageReceiveInfo.getSenderDepartmentCode());
nlbsMessageResp.setSenderDepartmentName(messageReceiveInfo.getSenderDepartmentName());
nlbsMessageResp.setSenderIdentityId(messageReceiveInfo.getSenderIdentityId());
nlbsMessageResp.setSenderName(messageReceiveInfo.getSenderName());
nlbsMessageResp.setReceiverName(messageReceiveInfo.getReceiverName());
nlbsMessageResp.setReceiverUserId(messageReceiveInfo.getReceiverIdentityId());
nlbsMessageResp.setInternalParam(messageReceiveInfo.getInternalParam());
nlbsMessageResp.setCode(messageReceiveInfo.getRequestNo());
listMessageResp.add(nlbsMessageResp);
}
Map requestMap = new HashMap();
requestMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap);
requestMap.put(Fields.PARAM_MESSAGE_HEAD, headMap);
bodyMap.put(Fields.PARAM_MPS_MESSAGELIST, listMessageResp);
//发送消息
JSONObject jsonParam = JSONObject.fromObject(requestMap);
JSONObject resultJson = HttpRequestUtils.httpPost(ConfigInfo.nlbsUrl ,jsonParam);
List receiverList = new ArrayList();
for(NlbsMessageResp message:listMessageResp){
Map receiverMap = new HashMap();
receiverMap.put(Fields.PARAM_MPS_RECEIVERIDENTITYID, message.getReceiverUserId());
receiverMap.put(Fields.PARAM_MPS_RECEIVER_SERIAL_NO, message.getSerialNo());
receiverMap.put(Fields.PARAM_MPS_RECEIVERNAME, message.getReceiverName());
receiverMap.put(Fields.PARAM_MPS_RECEIVER_CODE, message.getCode());
receiverMap.put(Fields.PARAM_MPS_RECEIVERSYSTEM, Constants.RECEIVER_SYSTEM_NLBS);
receiverList.add(receiverMap);
}
bodyMap.put(Fields.PARAM_MPS_RECEIVEUSERLIST, receiverList);
return bodyMap;
}
}
|
package main3x3;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class PicButton extends JButton {
private boolean correctAnswer;
public PicButton(boolean correctAnswer){
super();
this.correctAnswer=correctAnswer;
if (correctAnswer){
setActionCommand("TRUE");
}else{
setActionCommand("FALSE");
}
}
public boolean getCorrectAnswer(){
return correctAnswer;
}
}
|
package com.tencent.mm.plugin.webview.model;
import android.os.Bundle;
import com.tencent.mm.sdk.platformtools.x;
public class ak$a {
public Bundle jfZ = null;
final /* synthetic */ ak pSn;
public ak$a(ak akVar, Bundle bundle) {
this.pSn = akVar;
this.jfZ = bundle;
}
public final void putValue(String str, Object obj) {
if (this.jfZ == null) {
return;
}
if (obj instanceof String) {
this.jfZ.putString(str, (String) obj);
} else if (obj instanceof Boolean) {
this.jfZ.putBoolean(str, ((Boolean) obj).booleanValue());
} else if (obj instanceof Integer) {
this.jfZ.putInt(str, ((Integer) obj).intValue());
} else {
x.w("MicroMsg.WebviewReporter", "put unknow type value.");
}
}
}
|
package com.shangcai.service.material;
import com.irille.core.controller.PageView;
import com.shangcai.entity.common.Member;
import com.shangcai.view.material.CompanyView;
public interface ICompanyService {
public CompanyView signup(String name, String code, String iv, String encryptedData);
/**
* 将用户转换为 CompanyView
*
* @param member
* @return
*/
public CompanyView get(Member member);
public CompanyView get(Integer memberId);
public void upd(Integer memberId, String name, String contact_number, Integer established_time, String address, String profile);
public PageView<CompanyView> list(String name, Integer start, Integer limit);
}
|
package com.tencent.b.a.a;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Build.VERSION;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import java.util.Locale;
import java.util.TimeZone;
final class b {
static a bvh;
Integer bvi = null;
String bvj = null;
static class a {
String aem;
String bvk;
String bvl;
DisplayMetrics bvm;
int bvn;
String bvo;
String bvp;
String bvq;
String bvr;
int bvs;
String bvt;
String bvu;
Context ctx;
String imsi;
String model;
String packageName;
String timezone;
private a(Context context) {
this.bvl = "2.21";
this.bvn = VERSION.SDK_INT;
this.model = Build.MODEL;
this.bvo = Build.MANUFACTURER;
this.aem = Locale.getDefault().getLanguage();
this.bvp = "WX";
this.bvs = 0;
this.packageName = null;
this.ctx = null;
this.bvt = null;
this.bvu = null;
this.ctx = context.getApplicationContext();
try {
this.bvk = this.ctx.getPackageManager().getPackageInfo(this.ctx.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
}
this.bvm = new DisplayMetrics();
((WindowManager) this.ctx.getApplicationContext().getSystemService("window")).getDefaultDisplay().getMetrics(this.bvm);
if (s.o(context, "android.permission.READ_PHONE_STATE")) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager != null) {
this.bvq = telephonyManager.getSimOperator();
this.imsi = telephonyManager.getSubscriberId();
}
}
this.timezone = TimeZone.getDefault().getID();
this.bvr = s.aO(this.ctx);
this.packageName = this.ctx.getPackageName();
this.bvu = s.tV();
}
/* synthetic */ a(Context context, byte b) {
this(context);
}
}
private static synchronized a aE(Context context) {
a aVar;
synchronized (b.class) {
if (bvh == null) {
bvh = new a(context.getApplicationContext(), (byte) 0);
}
aVar = bvh;
}
return aVar;
}
public b(Context context) {
try {
aE(context);
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager != null) {
this.bvi = Integer.valueOf(telephonyManager.getNetworkType());
}
this.bvj = s.aP(context);
} catch (Throwable th) {
}
}
}
|
package main.java.org.intringsoft.prDoublyLinkedList;
import org.junit.*;
import static org.junit.Assert.*;
public class DoublyLinkedListTest {
@Test
public void nuevaDLLEstaVacia() {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
assertTrue(DLL.isEmpty());
}
@Test(expected = DoublyLinkedListException.class)
public void primerDatoDeNuevaLista() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.first();
}
@Test(expected = DoublyLinkedListException.class)
public void ultimoDatoDeNuevaLista() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.last();
}
@Test(expected = DoublyLinkedListException.class)
public void primerNodoDeNuevaLista() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.firstNode();
}
@Test(expected = DoublyLinkedListException.class)
public void ultimoNodoDeNuevaLista() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.lastNode();
}
@Test
public void insertaNodoAlPrincipio() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
assertEquals(node, DLL.first());
}
@Test
public void insertaNodoAlFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertEnd(node);
assertEquals(node, DLL.last());
}
@Test
public void insertaMismoNodoAlPrincipioYFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
DLL.insertEnd(node);
assertEquals(node, DLL.first());
assertEquals(node, DLL.last());
}
@Test
public void listaConElementosAlPrincipioNoEstaVacia() {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
assertFalse(DLL.isEmpty());
}
@Test
public void listaConElementosAlFinalNoEstaVacia() {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertEnd(node);
assertFalse(DLL.isEmpty());
}
@Test
public void listaConElementosAlPrincipioYFinalNoEstaVacia() {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
DLL.insertEnd(node);
assertFalse(DLL.isEmpty());
}
@Test
public void insertaDistintoNodoAlPrincipioYFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
Object node_ = new Object();
DLL.insertBeginning(node);
DLL.insertEnd(node_);
assertEquals(node, DLL.first());
assertEquals(node_, DLL.last());
}
@Test
public void insertaMismoNodo3VecesAlPrincipio() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
DLL.insertBeginning(node);
DLL.insertBeginning(node);
assertEquals(node, DLL.first());
assertEquals(node, DLL.last());
}
@Test
public void insertaMismoNodo3VecesAlFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertEnd(node);
DLL.insertEnd(node);
DLL.insertEnd(node);
assertEquals(node, DLL.first());
assertEquals(node, DLL.last());
}
@Test
public void insertaMismoNodo3VecesAlPrincipioYFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node = new Object();
DLL.insertBeginning(node);
DLL.insertEnd(node);
DLL.insertBeginning(node);
assertEquals(node, DLL.first());
assertEquals(node, DLL.last());
}
@Test
public void insertaDistintosNodos3VecesAlPrincipio() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
Object node_2 = new Object();
Object node_3 = new Object();
DLL.insertBeginning(node_1);
DLL.insertBeginning(node_2);
DLL.insertBeginning(node_3);
assertEquals(node_3, DLL.first());
assertEquals(node_1, DLL.last());
}
@Test
public void insertaDistintosNodos3VecesAlFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
Object node_2 = new Object();
Object node_3 = new Object();
DLL.insertEnd(node_1);
DLL.insertEnd(node_2);
DLL.insertEnd(node_3);
assertEquals(node_1, DLL.first());
assertEquals(node_3, DLL.last());
}
@Test
public void insertaDistintosNodos3VecesAlPrincipioYFinal() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
Object node_2 = new Object();
Object node_3 = new Object();
DLL.insertBeginning(node_1);
DLL.insertEnd(node_2);
DLL.insertBeginning(node_3);
assertEquals(node_3, DLL.first());
assertEquals(node_2, DLL.last());
}
@Test
public void insertaNodoDespuesDeOtro() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.insertBeginning(new Object());
Object node_1 = DLL.first();
DoublyLinkedList.Node<Object> linkedNode_1 = DLL.firstNode();
Object node_2 = new Object();
DoublyLinkedList.Node<Object> linkedNode_2 = new DoublyLinkedList.Node<Object>(node_2, null, null);
DLL.insertAfter(linkedNode_1, linkedNode_2);
assertEquals(node_1, DLL.first());
assertEquals(node_2, DLL.last());
}
@Test
public void insertaNodoAntesDeOtro() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.insertBeginning(new Object());
Object node_1 = DLL.first();
DoublyLinkedList.Node<Object> linkedNode_1 = DLL.firstNode();
Object node_2 = new Object();
DoublyLinkedList.Node<Object> linkedNode_2 = new DoublyLinkedList.Node<Object>(node_2, null, null);
DLL.insertBefore(linkedNode_1, linkedNode_2);
assertEquals(node_2, DLL.first());
assertEquals(node_1, DLL.last());
}
@Test
public void insertaNodoDespuesDeVarios() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.insertBeginning(new Object());
DLL.insertEnd(new Object());
Object node_1 = DLL.first();
DoublyLinkedList.Node<Object> linkedNode_2 = DLL.lastNode();
Object node_3 = new Object();
DoublyLinkedList.Node<Object> linkedNode_3 = new DoublyLinkedList.Node<Object>(node_3, null, null);
DLL.insertAfter(linkedNode_2, linkedNode_3);
assertEquals(node_1, DLL.first());
assertEquals(node_3, DLL.last());
}
@Test
public void insertaNodoAntesDeVarios() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
DLL.insertBeginning(new Object());
DLL.insertEnd(new Object());
Object node_2 = DLL.last();
DoublyLinkedList.Node<Object> linkedNode_1 = DLL.firstNode();
Object node_3 = new Object();
DoublyLinkedList.Node<Object> linkedNode_3 = new DoublyLinkedList.Node<Object>(node_3, null, null);
DLL.insertBefore(linkedNode_1, linkedNode_3);
assertEquals(node_3, DLL.first());
assertEquals(node_2, DLL.last());
}
@Test
public void insertaNodoEnMitadDeVariosConAfter() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
DLL.insertBeginning(node_1);
Object node_2 = new Object();
DLL.insertEnd(node_2);
DoublyLinkedList.Node<Object> linkedNode_1 = DLL.firstNode();
DoublyLinkedList.Node<Object> linkedNode_3 = new DoublyLinkedList.Node<Object>(new Object(), null, null);
DLL.insertAfter(linkedNode_1, linkedNode_3);
assertEquals(node_1, DLL.first());
assertEquals(node_2, DLL.last());
}
@Test
public void insertaNodoEnMitadDeVariosConBefore() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
DLL.insertBeginning(node_1);
Object node_2 = new Object();
DLL.insertEnd(node_2);
DoublyLinkedList.Node<Object> linkedNode_2 = DLL.lastNode();
DoublyLinkedList.Node<Object> linkedNode_3 = new DoublyLinkedList.Node<Object>(new Object(), null, null);
DLL.insertBefore(linkedNode_2, linkedNode_3);
assertEquals(node_1, DLL.first());
assertEquals(node_2, DLL.last());
}
@Test
public void eliminarUltimoNodoDeListaUnitariaYObtenerPrimerNodo() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
DLL.insertBeginning(node_1);
DLL.deleteLast();
assertTrue(DLL.isEmpty());
}
@Test
public void eliminarUltimoNodoDeListaUnitariaYObtenerUltimoNodo() throws DoublyLinkedListException {
DoublyLinkedList<Object> DLL = new DoublyLinkedList<Object>();
Object node_1 = new Object();
DLL.insertBeginning(node_1);
DLL.deleteLast();
assertTrue(DLL.isEmpty());
}
}
|
package solution;
/**
* User: jieyu
* Date: 11/5/16.
*/
public class FindPeakElement162 {
public int findPeakElement(int[] nums) {
if (nums.length < 2 || nums[0] > nums[1]) return 0;
if (nums.length == 2) return (nums[0] > nums[1]) ? 0 : 1;
for (int i = 1; i < nums.length; i++) {
if (i == nums.length - 1) break;
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) return i;
}
return nums.length - 1;
}
}
|
public class ListUtilities {
public LinkedList arrayToList(int[] array) {
LinkedList list = new LinkedList();
for(int i = 0; i < array.length; i++) {
list.addInt(array[i]);
}
return list;
}
public void bubbleSort(LinkedList list) {
list.bubbleSort();
}
public void cocktailSort(LinkedList list) {
list.cocktailSort();
}
public void benchmark(LinkedList list, String algorithm) {
if (algorithm == "bubble") {
long start = System.nanoTime();
list.bubbleSort();
long result = System.nanoTime() - start;
System.out.println(algorithm + " sorted in " + result + "ns!");
} else if (algorithm == "cocktail") {
long start = System.nanoTime();
list.cocktailSort();
long result = System.nanoTime() - start;
System.out.println(algorithm + " sorted in " + result + "ns!");
}
}
} |
package com.tt.miniapp.webbridge.sync;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.WebViewManager;
import com.tt.miniapp.webbridge.WebEventHandler;
import com.tt.miniapphost.AppBrandLogger;
import org.json.JSONObject;
public abstract class BasePickerEventHandler extends WebEventHandler {
public BasePickerEventHandler(WebViewManager.IRender paramIRender, String paramString, int paramInt) {
super(paramIRender, paramString, paramInt);
}
protected void makeCancelMsg(String paramString) {
AppBrandLogger.d("tma_BasePickerEventHandler", new Object[] { "timePicker onCancel" });
try {
JSONObject jSONObject = new JSONObject();
jSONObject.put("errMsg", buildErrorMsg(paramString, "cancel"));
AppbrandApplicationImpl.getInst().getWebViewManager().invokeHandler(this.mRender.getWebViewId(), this.mCallBackId, jSONObject.toString());
return;
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "tma_BasePickerEventHandler", exception.getStackTrace());
return;
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\webbridge\sync\BasePickerEventHandler.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.elepy.admin.concepts;
import com.elepy.ElepyPostConfiguration;
import com.elepy.admin.ElepyAdminPanel;
import com.elepy.http.HttpService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PluginHandler {
private final ElepyAdminPanel adminPanel;
private final List<ElepyAdminPanelPlugin> plugins;
private final HttpService http;
public PluginHandler(ElepyAdminPanel adminPanel, HttpService http) {
this.adminPanel = adminPanel;
this.http = http;
this.plugins = new ArrayList<>();
}
public void setupPlugins(ElepyPostConfiguration elepyPostConfiguration) {
for (ElepyAdminPanelPlugin plugin : this.plugins) {
plugin.setup(http, elepyPostConfiguration);
}
}
public void setupRoutes(ElepyPostConfiguration elepyPostConfiguration) {
http.before("/plugins/*", ctx -> ctx.request().loggedInUserOrThrow());
http.before("/plugins/*/*", ctx -> ctx.request().loggedInUserOrThrow());
for (ElepyAdminPanelPlugin plugin : this.plugins) {
plugin.setup(http, elepyPostConfiguration);
http.get("/plugins/" + plugin.getSlug(), (request, response) -> {
Map<String, Object> model = new HashMap<>();
String content = plugin.renderContent(model);
model.put("content", content);
model.put("plugin", plugin);
response.result(adminPanel.renderWithDefaults(model, "admin-templates/plugin.peb"));
});
}
}
public ElepyAdminPanel addPlugin(ElepyAdminPanelPlugin plugin) {
if (adminPanel.isInitiated()) {
throw new IllegalStateException("Can't add plugins after before() has been called!");
}
plugin.setAdminPanel(adminPanel);
plugins.add(plugin);
return adminPanel;
}
public ElepyAdminPanel getAdminPanel() {
return adminPanel;
}
public List<ElepyAdminPanelPlugin> getPlugins() {
return plugins;
}
}
|
package com.university.wanstudy.adapters;
import android.content.Context;
import android.graphics.Color;
import android.widget.ImageView;
import android.widget.TextView;
import com.university.wanstudy.MyApp;
import com.university.wanstudy.R;
import com.university.wanstudy.model.MajorModel;
import org.xutils.x;
import java.util.List;
/**
* 课程适列表配器
*/
public class MajorAdapter extends MyBaseAdapter<MajorModel> {
public MajorAdapter(Context context, List<MajorModel> data, int... layouts) {
super(context, data, layouts);
}
@Override
public void bindData(ViewHolder holder, MajorModel majorModel) {
//图片
ImageView majorImg = (ImageView) holder.getView(R.id.major_item_img);
String logoUrl = majorModel.getLogoUrl();
if (logoUrl != null) {
x.image().bind(majorImg, logoUrl, MyApp.options);
}
//标题
TextView majorTitle = (TextView) holder.getView(R.id.major_item_title);
majorTitle.setText(majorModel.getName());
majorTitle.setTextColor(Color.BLACK);
//简介
TextView majorDescription = (TextView) holder.getView(R.id.major_item_content);
majorDescription.setText(majorModel.getShortDescription());
majorDescription.setTextColor(Color.BLACK);
//讲师
((TextView) holder.getView(R.id.major_item_teacherName)).setText(majorModel.getTeacherName());
//课时
((TextView) holder.getView(R.id.major_item_numOfClasses)).setText(majorModel.getNumOfClasses() + "讲");
//时长
((TextView) holder.getView(R.id.major_item_timePerPart)).setText(majorModel.getTimePerPart() + "分/讲");
}
}
|
/*
If user chooses from home screen to view all public cases, this is where he is brought to and shown all public cases
*/
//TODO Right now nothing happens if user taps on case....Must add functionality that it should show list of that cases's mishnayos
package com.example.mna.mishnapals;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by MNA on 8/15/2017.
*/
public class PublicCases extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.avail_public_cases);
ListView listView = (ListView) findViewById(R.id.publicCasesList);
ArrayList<String> caseNames = new ArrayList<>();
caseNames = getIntent().getStringArrayListExtra("caseNames");
Bundle sentCases = getIntent().getBundleExtra("cases");
final ArrayList<Case> publicCases = (ArrayList<Case>) sentCases.getSerializable("Arraylist");
final ArrayList<String> publicCaseIds = getIntent().getStringArrayListExtra("caseIds");
final String[] cases = new String[caseNames.size()];
for (int i = 0; i < caseNames.size(); i++) {
cases[i] = caseNames.get(i);
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.case_info, cases);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Case caseTakenInfo = publicCases.get(position);
Intent intent = new Intent(getBaseContext(), MasechtosList.class);
Log.d("lololol", caseTakenInfo.getCaseId());
Log.d("opopopo", publicCaseIds.get(0));
startActivity(new Intent(getBaseContext(), MasechtosList.class).putExtra("caseId", caseTakenInfo.getCaseId()).putExtra("caseKey", publicCaseIds.get(position)));
}
});
}
}
|
package com.example.demo.ch6BecomUnbecom;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class RequestActor6 extends AbstractActor {
protected final String name;
protected final LoggingAdapter log = Logging.getLogger(context().system(),this);
private Receive hiHandler ;
private Receive helloHandler;
public RequestActor6(String name) {
this.name = name;
hiHandler = receiveBuilder()
.matchEquals("Hi",message -> {log.info(message); getContext().become(helloHandler); })
.matchAny(message -> {log.error(message.toString());})
.build();
helloHandler = receiveBuilder()
.matchEquals("Hello",message -> {log.info(message); getContext().become(hiHandler);})
.matchAny(message -> {log.error(message.toString());})
.build();
}
public static Props props(String name) {
return Props.create(RequestActor6.class,name);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(String.class,message -> {
log.info(message);
getContext().become(helloHandler);
})
.build();
}
}
|
/*
* Copyright 2006 Ameer Antar.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.antfarmer.ejce.test.util;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.Properties;
import javax.crypto.Cipher;
import org.antfarmer.ejce.Encryptor;
import org.antfarmer.ejce.EncryptorStore;
import org.antfarmer.ejce.encoder.Base32Encoder;
import org.antfarmer.ejce.encoder.Base64Encoder;
import org.antfarmer.ejce.encoder.Base64UrlEncoder;
import org.antfarmer.ejce.encoder.HexEncoder;
import org.antfarmer.ejce.exception.EncryptorConfigurationException;
import org.antfarmer.ejce.parameter.AbstractAlgorithmParameters;
import org.antfarmer.ejce.parameter.AesParameters;
import org.antfarmer.ejce.parameter.BlowfishParameters;
import org.antfarmer.ejce.parameter.CamelliaParameters;
import org.antfarmer.ejce.parameter.DesEdeParameters;
import org.antfarmer.ejce.parameter.PbeParameters;
import org.antfarmer.ejce.parameter.Rc4Parameters;
import org.antfarmer.ejce.parameter.RsaParameters;
import org.antfarmer.ejce.parameter.TwofishParameters;
import org.antfarmer.ejce.parameter.key_loader.KeyLoader;
import org.antfarmer.ejce.parameter.salt.SaltGenerator;
import org.antfarmer.ejce.parameter.salt.SaltMatcher;
import org.antfarmer.ejce.password.ConfigurablePasswordEncoder;
import org.antfarmer.ejce.password.PasswordEncoderStore;
import org.antfarmer.ejce.password.encoder.spring.SpringBcryptEncoder;
import org.antfarmer.ejce.test.AbstractTest;
import org.antfarmer.ejce.util.ConfigurerUtil;
import org.antfarmer.ejce.util.CryptoUtil;
import org.antfarmer.ejce.util.ReflectionUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.After;
import org.junit.Test;
/**
*
* @author Ameer Antar
* @version 1.0
*/
public class ConfigurerUtilTest extends AbstractTest {
@After
public void after() {
EncryptorStore.clear();
PasswordEncoderStore.clear();
}
/**
*
*/
@Test
public void testSetStoredEncryptor() {
final String name = "name";
final DesEdeParameters parameters = new DesEdeParameters();
parameters.setKeySize(DesEdeParameters.KEY_SIZE_DES_EDE_112)
.setBlockMode(DesEdeParameters.BLOCK_MODE_CFB)
.setPadding(DesEdeParameters.PADDING_PKCS5)
.setMacAlgorithm(DesEdeParameters.MAC_ALGORITHM_HMAC_MD5)
.setMacKeySize(DesEdeParameters.MAC_KEY_SIZE_128);
final Encryptor encryptor = new Encryptor().setAlgorithmParameters(parameters);
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCRYPTOR_STORE_KEY, name);
EncryptorStore.add(name, encryptor);
assertSame(encryptor, ConfigurerUtil.configureEncryptor(properties));
// check missing encryptor from store
EncryptorStore.remove(name);
Exception ex = null;
try {
ConfigurerUtil.configureEncryptor(properties);
}
catch (final Exception e) {
ex = e;
}
assertEquals(EncryptorConfigurationException.class, ex.getClass());
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValues() throws Exception {
final String key = Base32Encoder.getInstance().encode("SMOKESOMEOFMYTIE".getBytes());
final String macKey = Base32Encoder.getInstance().encode("SMOKEAJAYINTHEGOODOLUSA".getBytes());
final String saltSize = "6";
final String iterations = "700";
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCODER_CLASS, HexEncoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, PbeParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, key);
properties.setProperty(ConfigurerUtil.KEY_ALGORITHM, PbeParameters.ALGORITHM_PBE_MD5_DES);
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, sun.security.provider.Sun.class.getName());
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, PbeParameters.MAC_ALGORITHM_HMAC_MD5);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY, macKey);
properties.setProperty(ConfigurerUtil.KEY_BLOCK_MODE, PbeParameters.BLOCK_MODE_OFB);
properties.setProperty(ConfigurerUtil.KEY_PADDING, PbeParameters.PADDING_PKCS5);
properties.setProperty(ConfigurerUtil.KEY_SALT_SIZE, saltSize);
properties.setProperty(ConfigurerUtil.KEY_ITERATION_COUNT, iterations);
properties.setProperty(ConfigurerUtil.KEY_SALT_GENERATOR, DefaultSaltGenerator.class.getName());
properties.setProperty(ConfigurerUtil.KEY_SALT_MATCHER, DefaultSaltMatcher.class.getName());
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final PbeParameters parameters = (PbeParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(HexEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(UTF8, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(PbeParameters.ALGORITHM_PBE_MD5_DES, parameters.getAlgorithm());
assertEquals(sun.security.provider.Sun.class, parameters.getProvider().getClass());
assertEquals(PbeParameters.MAC_ALGORITHM_HMAC_MD5, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(PbeParameters.BLOCK_MODE_OFB, parameters.getBlockMode());
assertEquals(PbeParameters.GCM_AUTH_TAG_LEN_128, parameters.getGcmTagLen());
assertEquals(PbeParameters.PADDING_PKCS5, parameters.getPadding());
assertEquals(Integer.valueOf(8), (Integer)parameters.getBlockSize());
assertEquals(Integer.valueOf(saltSize), (Integer)parameters.getSaltSize());
assertEquals(Integer.valueOf(iterations), (Integer)parameters.getIterationCount());
assertEquals(DefaultSaltGenerator.class, ReflectionUtil.getFieldValue(parameters, "saltGenerator").getClass());
assertEquals(DefaultSaltMatcher.class, ReflectionUtil.getFieldValue(parameters, "saltMatcher").getClass());
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValuesNoPbeConfig() throws Exception {
final String key = Base32Encoder.getInstance().encode("SMOKESOMEOFMYTIE".getBytes());
final String macKey = Base32Encoder.getInstance().encode("SMOKEAJAYINTHEGOODOLUSA".getBytes());
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCODER_CLASS, HexEncoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, PbeParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, key);
properties.setProperty(ConfigurerUtil.KEY_ALGORITHM, PbeParameters.ALGORITHM_PBE_MD5_DES);
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, sun.security.provider.Sun.class.getName());
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, PbeParameters.MAC_ALGORITHM_HMAC_MD5);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY, macKey);
properties.setProperty(ConfigurerUtil.KEY_BLOCK_MODE, PbeParameters.BLOCK_MODE_OFB);
properties.setProperty(ConfigurerUtil.KEY_PADDING, PbeParameters.PADDING_PKCS5);
properties.setProperty(ConfigurerUtil.KEY_SALT_GENERATOR, DefaultSaltGenerator.class.getName());
properties.setProperty(ConfigurerUtil.KEY_SALT_MATCHER, DefaultSaltMatcher.class.getName());
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final PbeParameters parameters = (PbeParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(HexEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(UTF8, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(PbeParameters.ALGORITHM_PBE_MD5_DES, parameters.getAlgorithm());
assertEquals(sun.security.provider.Sun.class, parameters.getProvider().getClass());
assertEquals(PbeParameters.MAC_ALGORITHM_HMAC_MD5, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(PbeParameters.BLOCK_MODE_OFB, parameters.getBlockMode());
assertEquals(PbeParameters.GCM_AUTH_TAG_LEN_128, parameters.getGcmTagLen());
assertEquals(PbeParameters.PADDING_PKCS5, parameters.getPadding());
assertEquals(Integer.valueOf(8), (Integer)parameters.getBlockSize());
assertEquals(DefaultSaltGenerator.class, ReflectionUtil.getFieldValue(parameters, "saltGenerator").getClass());
assertEquals(DefaultSaltMatcher.class, ReflectionUtil.getFieldValue(parameters, "saltMatcher").getClass());
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValues2() throws Exception {
final Charset cs = Charset.forName("US-ASCII");
final String key = Base32Encoder.getInstance().encode("BINGBINGA".getBytes());
final String macKey = Base32Encoder.getInstance().encode("BEEOWANOWEEWEE".getBytes());
final String providerName = "SunJCE";
final String blockSize = "16";
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_CHARSET, cs.name());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, BlowfishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, key);
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_NAME, providerName);
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY, macKey);
properties.setProperty(ConfigurerUtil.KEY_BLOCK_MODE, BlowfishParameters.BLOCK_MODE_CFB);
properties.setProperty(ConfigurerUtil.KEY_BLOCK_SIZE, blockSize);
properties.setProperty(ConfigurerUtil.KEY_PADDING, BlowfishParameters.PADDING_NONE);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final BlowfishParameters parameters = (BlowfishParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(providerName, parameters.getProviderName());
assertEquals(BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(BlowfishParameters.BLOCK_MODE_CFB, parameters.getBlockMode());
assertEquals(Integer.valueOf(blockSize), (Integer)parameters.getBlockSize());
assertEquals(BlowfishParameters.PADDING_NONE, parameters.getPadding());
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValues3() throws Exception {
final Charset cs = Charset.forName("US-ASCII");
final String providerName = "SunJCE";
final String blockSize = "16";
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCODER_CLASS, Base64UrlEncoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CHARSET, cs.name());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, BlowfishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_KEY_LOADER, MyKeyLoader.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_NAME, providerName);
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY_LOADER, MyMacKeyLoader.class.getName());
properties.setProperty(ConfigurerUtil.KEY_BLOCK_MODE, BlowfishParameters.BLOCK_MODE_GCM);
properties.setProperty(ConfigurerUtil.KEY_BLOCK_SIZE, blockSize);
properties.setProperty(ConfigurerUtil.KEY_GCM_TAG_LEN, String.valueOf(BlowfishParameters.GCM_AUTH_TAG_LEN_96));
properties.setProperty(ConfigurerUtil.KEY_PADDING, BlowfishParameters.PADDING_NONE);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final BlowfishParameters parameters = (BlowfishParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
parameters.getKey();
parameters.getMacKey();
assertEquals(Base64UrlEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertArrayEquals(MyKeyLoader.key.getEncoded(), parameters.getKey().getEncoded());
assertEquals(providerName, parameters.getProviderName());
assertEquals(BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertArrayEquals(MyMacKeyLoader.key.getEncoded(), parameters.getMacKey().getEncoded());
assertEquals(BlowfishParameters.BLOCK_MODE_GCM, parameters.getBlockMode());
assertEquals(BlowfishParameters.GCM_AUTH_TAG_LEN_96, parameters.getGcmTagLen());
assertEquals(Integer.valueOf(8), (Integer)parameters.getBlockSize());
assertEquals(BlowfishParameters.PADDING_NONE, parameters.getPadding());
}
@Test
public void testSetParameterValues4() throws Exception {
final Class<? extends Provider> providerClass = BouncyCastleProvider.class;
final Charset cs = Charset.forName("UTF-16");
final String key = Base32Encoder.getInstance().encode("BINGBINGA".getBytes());
final String macKey = Base32Encoder.getInstance().encode("BEEOWANOWEEWEE".getBytes());
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_CHARSET, cs.name());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, Rc4Parameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, key);
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, providerClass.getName());
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, Rc4Parameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY, macKey);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final Rc4Parameters parameters = (Rc4Parameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertSame(providerClass, parameters.getProvider().getClass());
assertEquals(Rc4Parameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
}
public void testSetParameterValues5() throws Exception {
final Class<? extends Provider> providerClass = BouncyCastleProvider.class;
final Charset cs = Charset.forName("UTF-16");
final KeyPair pair = CryptoUtil.generateAsymmetricKeyPair(RsaParameters.ALGORITHM_RSA);
final String privKey = Base32Encoder.getInstance().encode(pair.getPrivate().getEncoded());
final String publicKey = Base32Encoder.getInstance().encode(pair.getPrivate().getEncoded());
final String macKey = Base32Encoder.getInstance().encode("BEEOWANOWEEWEE".getBytes());
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_CHARSET, cs.name());
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, RsaParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, Base32Encoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_ENCRYPTION_KEY, privKey);
properties.setProperty(ConfigurerUtil.KEY_DECRYPTION_KEY, publicKey);
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, providerClass.getName());
properties.setProperty(ConfigurerUtil.KEY_MAC_ALGORITHM, RsaParameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(ConfigurerUtil.KEY_MAC_KEY, macKey);
properties.setProperty(ConfigurerUtil.KEY_PADDING, RsaParameters.PADDING_PKCS1);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties);
final RsaParameters parameters = (RsaParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(privKey, parameters.getEncryptionKey());
assertEquals(publicKey, parameters.getDecryptionKey());
assertSame(providerClass, parameters.getProvider().getClass());
assertEquals(RsaParameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(RsaParameters.PADDING_PKCS1, parameters.getPadding());
}
/**
*
*/
@Test
public void testSetStoredEncryptorViaSysProps() {
final DesEdeParameters parameters = new DesEdeParameters();
parameters.setKeySize(DesEdeParameters.KEY_SIZE_DES_EDE_112)
.setBlockMode(DesEdeParameters.BLOCK_MODE_CFB)
.setPadding(DesEdeParameters.PADDING_PKCS5)
.setMacAlgorithm(DesEdeParameters.MAC_ALGORITHM_HMAC_MD5)
.setMacKeySize(DesEdeParameters.MAC_KEY_SIZE_128);
final Encryptor encryptor = new Encryptor().setAlgorithmParameters(parameters);
EncryptorStore.add("name", encryptor);
final VolatileProperties properties = new VolatileProperties(System.getProperties());
final String propPrefix = "ejce.encryptor1";
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCRYPTOR_STORE_KEY), "name");
assertSame(encryptor, ConfigurerUtil.configureEncryptor(properties.getProperties(), propPrefix));
properties.rollback();
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValuesViaSysProps1() throws Exception {
final Charset cs = UTF8;
final String key = Base32Encoder.getInstance().encode("SMOKESOMEOFMYTIE".getBytes());
final String macKey = Base32Encoder.getInstance().encode("SMOKEAJAYINTHEGOODOLUSA".getBytes());
final String gcmSize = String.valueOf(CamelliaParameters.GCM_AUTH_TAG_LEN_128);
final String propPrefix = "ejce.encryptor5";
final VolatileProperties sysProps = new VolatileProperties(System.getProperties());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCODER_CLASS), Base64Encoder.class.getName());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CHARSET), cs.name());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_CLASS), CamelliaParameters.class.getName());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_ENCODER_CLASS), Base32Encoder.class.getName());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CIPHER_KEY), key);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ALGORITHM), CamelliaParameters.ALGORITHM_CAMELLIA);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PROVIDER_CLASS), sun.security.provider.Sun.class.getName());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_ALGORITHM), CamelliaParameters.MAC_ALGORITHM_HMAC_MD5);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_KEY), macKey);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_MODE), CamelliaParameters.BLOCK_MODE_GCM);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PADDING), CamelliaParameters.PADDING_PKCS5);
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_GCM_TAG_LEN), gcmSize);
final Properties props = new Properties();
props.setProperty(ConfigurerUtil.KEY_PROPERTY_PREFIX, propPrefix);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(props);
final CamelliaParameters parameters = (CamelliaParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base64Encoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(CamelliaParameters.ALGORITHM_CAMELLIA, parameters.getAlgorithm());
assertEquals(sun.security.provider.Sun.class, parameters.getProvider().getClass());
assertEquals(CamelliaParameters.MAC_ALGORITHM_HMAC_MD5, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(CamelliaParameters.BLOCK_MODE_GCM, parameters.getBlockMode());
assertEquals(CamelliaParameters.GCM_AUTH_TAG_LEN_128, parameters.getGcmTagLen());
assertEquals(CamelliaParameters.PADDING_PKCS5, parameters.getPadding());
assertEquals(Integer.valueOf(gcmSize), (Integer)parameters.getGcmTagLen());
sysProps.rollback();
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValuesViaSysProps2() throws Exception {
final Charset cs = Charset.forName("UTF-16");
final String key = Base32Encoder.getInstance().encode("SMOKESOMEOFMYTIE".getBytes());
final String macKey = Base32Encoder.getInstance().encode("SMOKEAJAYINTHEGOODOLUSA".getBytes());
final String saltSize = "6";
final String iterations = "700";
final String propPrefix = "ejce.encryptor1";
final VolatileProperties properties = new VolatileProperties(System.getProperties());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCODER_CLASS), HexEncoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CHARSET), cs.name());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_CLASS), PbeParameters.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_ENCODER_CLASS), Base32Encoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CIPHER_KEY), key);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ALGORITHM), PbeParameters.ALGORITHM_PBE_MD5_DES);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PROVIDER_CLASS), sun.security.provider.Sun.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_ALGORITHM), PbeParameters.MAC_ALGORITHM_HMAC_MD5);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_KEY), macKey);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_MODE), PbeParameters.BLOCK_MODE_OFB);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PADDING), PbeParameters.PADDING_PKCS5);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_SALT_SIZE), saltSize);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ITERATION_COUNT), iterations);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties.getProperties(), propPrefix);
final PbeParameters parameters = (PbeParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(HexEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(PbeParameters.ALGORITHM_PBE_MD5_DES, parameters.getAlgorithm());
assertEquals(sun.security.provider.Sun.class, parameters.getProvider().getClass());
assertEquals(PbeParameters.MAC_ALGORITHM_HMAC_MD5, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(PbeParameters.BLOCK_MODE_OFB, parameters.getBlockMode());
assertEquals(PbeParameters.GCM_AUTH_TAG_LEN_128, parameters.getGcmTagLen());
assertEquals(PbeParameters.PADDING_PKCS5, parameters.getPadding());
assertEquals(Integer.valueOf(saltSize), (Integer)parameters.getSaltSize());
assertEquals(Integer.valueOf(iterations), (Integer)parameters.getIterationCount());
properties.rollback();
}
@Test(expected = EncryptorConfigurationException.class)
public void testSetParameterValuesViaSysPropsWrongProps() {
final VolatileProperties sysProps = new VolatileProperties(System.getProperties());
sysProps.setProperty(ConfigurerUtil.KEY_PROPERTY_PREFIX, "prefix");
try {
ConfigurerUtil.configureEncryptor(sysProps.getProperties());
}
finally {
sysProps.rollback();
}
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValues2ViaSysProps() throws Exception {
final Charset cs = Charset.forName("ISO-8859-1");
final String key = Base32Encoder.getInstance().encode("BINGBINGA".getBytes());
final String macKey = Base32Encoder.getInstance().encode("BEEOWANOWEEWEE".getBytes());
final String providerName = "SunJCE";
final String blockSize = "16";
final String propPrefix = "ejce.encryptor3";
final VolatileProperties properties = new VolatileProperties(System.getProperties());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCODER_CLASS), Base64UrlEncoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CHARSET), cs.name());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_CLASS), BlowfishParameters.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_ENCODER_CLASS), Base32Encoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CIPHER_KEY), key);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PROVIDER_NAME), providerName);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_ALGORITHM), BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_KEY), macKey);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_MODE), BlowfishParameters.BLOCK_MODE_OFB);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_SIZE), blockSize);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PADDING), BlowfishParameters.PADDING_NONE);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties.getProperties(), propPrefix);
final BlowfishParameters parameters = (BlowfishParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base64UrlEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(providerName, parameters.getProviderName());
assertEquals(BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(BlowfishParameters.BLOCK_MODE_OFB, parameters.getBlockMode());
assertEquals(Integer.valueOf(blockSize), (Integer)parameters.getBlockSize());
assertEquals(BlowfishParameters.PADDING_NONE, parameters.getPadding());
properties.rollback();
}
/**
* @throws Exception Exception
*/
@Test
public void testSetParameterValues3ViaSysProps() throws Exception {
final Charset cs = Charset.forName("ISO-8859-1");
final String key = Base32Encoder.getInstance().encode("BINGBINGA".getBytes());
final String macKey = Base32Encoder.getInstance().encode("BEEOWANOWEEWEE".getBytes());
final String providerName = "SunJCE";
final String blockSize = "16";
final String propPrefix = "ejce.encryptor2";
final VolatileProperties properties = new VolatileProperties(System.getProperties());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCODER_CLASS), Base64UrlEncoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CHARSET), cs.name());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_CLASS), BlowfishParameters.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PARAM_ENCODER_CLASS), Base32Encoder.class.getName());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_CIPHER_KEY), key);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PROVIDER_NAME), providerName);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_ALGORITHM), BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_MAC_KEY), macKey);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_MODE), BlowfishParameters.BLOCK_MODE_GCM);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_GCM_TAG_LEN), String.valueOf(BlowfishParameters.GCM_AUTH_TAG_LEN_112));
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_BLOCK_SIZE), blockSize);
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PADDING), BlowfishParameters.PADDING_NONE);
final Encryptor encryptor = ConfigurerUtil.configureEncryptor(properties.getProperties(), propPrefix);
final BlowfishParameters parameters = (BlowfishParameters) ReflectionUtil.getFieldValue(encryptor, "parameters");
assertEquals(Base64UrlEncoder.class, ReflectionUtil.getFieldValue(encryptor, "textEncoder").getClass());
assertEquals(Base32Encoder.class, ReflectionUtil.getFieldValue(parameters, "textEncoder").getClass());
assertEquals(cs, encryptor.getCharset());
assertEquals(key, Base32Encoder.getInstance().encode(parameters.getKey().getEncoded()));
assertEquals(providerName, parameters.getProviderName());
assertEquals(BlowfishParameters.MAC_ALGORITHM_HMAC_SHA1, parameters.getMacAlgorithm());
assertEquals(macKey, Base32Encoder.getInstance().encode(parameters.getMacKey().getEncoded()));
assertEquals(BlowfishParameters.BLOCK_MODE_GCM, parameters.getBlockMode());
assertEquals(BlowfishParameters.GCM_AUTH_TAG_LEN_112, parameters.getGcmTagLen());
assertEquals(Integer.valueOf(8), (Integer)parameters.getBlockSize());
assertEquals(BlowfishParameters.PADDING_NONE, parameters.getPadding());
properties.rollback();
}
/**
* @throws Exception Exception
*/
@Test(expected = EncryptorConfigurationException.class)
public void testAsymetric() throws Exception {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, RsaParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_ALGORITHM, RsaParameters.ALGORITHM_RSA);
ConfigurerUtil.loadAlgorithmParameters(properties, null);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadEncoder() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCODER_CLASS, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadCharset() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_CHARSET, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesNoParams() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, "");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadParams1() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadParams2() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, Integer.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadParamEncoder() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PARAM_ENCODER_CLASS, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesNoKey() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadKeyLoader() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_KEY_LOADER, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesWrongKeyLoader() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_KEY_LOADER, Integer.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadProvider1() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadProvider2() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_PROVIDER_CLASS, Double.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadSaltGenerator1() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_SALT_GENERATOR, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadSaltGenerator2() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_SALT_GENERATOR, Integer.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadSaltMatcher1() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_SALT_MATCHER, "o");
ConfigurerUtil.configureEncryptor(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testParameterValuesBadSaltMatcher2() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PARAM_CLASS, TwofishParameters.class.getName());
properties.setProperty(ConfigurerUtil.KEY_CIPHER_KEY, "MYSECRETKEY");
properties.setProperty(ConfigurerUtil.KEY_SALT_MATCHER, Integer.class.getName());
ConfigurerUtil.configureEncryptor(properties);
}
/**
* @throws Exception Exception
*/
@Test
public void testPswdEncoderParameterValues() throws Exception {
final String exportKey = "org.antfarmer.test.springPswdEncoder";
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PSWD_ENCODER_CLASS, SpringBcryptEncoder.class.getName());
properties.setProperty(ConfigurerUtil.KEY_PSWD_ENCODER_STORE_EXPORT_KEY, exportKey);
final ConfigurablePasswordEncoder encoder = ConfigurerUtil.configurePswdEncoder(properties);
assertEquals(SpringBcryptEncoder.class, encoder.getClass());
assertSame(encoder, PasswordEncoderStore.get(exportKey));
}
/**
* @throws Exception Exception
*/
@Test
public void testPswdEncoderViaStore() throws Exception {
final String name = "name";
final SpringBcryptEncoder pswdEnc = new SpringBcryptEncoder();
PasswordEncoderStore.add(name, pswdEnc);
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_ENCRYPTOR_STORE_KEY, name);
assertSame(pswdEnc, ConfigurerUtil.configurePswdEncoder(properties));
// check missing encryptor from store
PasswordEncoderStore.remove(name);
Exception ex = null;
try {
ConfigurerUtil.configurePswdEncoder(properties);
}
catch (final Exception e) {
ex = e;
}
assertEquals(EncryptorConfigurationException.class, ex.getClass());
}
/**
*
*/
@Test
public void testPswdEncoderStoredViaSysProps() {
final SpringBcryptEncoder pswdEnc = new SpringBcryptEncoder();
PasswordEncoderStore.add("name", pswdEnc);
final VolatileProperties properties = new VolatileProperties(System.getProperties());
final String propPrefix = "ejce.pswdEnc1";
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_ENCRYPTOR_STORE_KEY), "name");
assertSame(pswdEnc, ConfigurerUtil.configurePswdEncoder(properties.getProperties(), propPrefix));
properties.rollback();
}
/**
* @throws Exception Exception
*/
@Test
public void testPswdEncoderParameterValuesViaSysProps1() throws Exception {
final String propPrefix = "ejce.pswdEnc1";
final String exportKey = "org.antfarmer.test.springPswdEncoder";
final VolatileProperties sysProps = new VolatileProperties(System.getProperties());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PSWD_ENCODER_CLASS), SpringBcryptEncoder.class.getName());
sysProps.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PSWD_ENCODER_STORE_EXPORT_KEY), exportKey);
final Properties props = new Properties();
props.setProperty(ConfigurerUtil.KEY_PROPERTY_PREFIX, propPrefix);
final ConfigurablePasswordEncoder encoder = ConfigurerUtil.configurePswdEncoder(props);
assertEquals(SpringBcryptEncoder.class, encoder.getClass());
assertSame(encoder, PasswordEncoderStore.get(exportKey));
sysProps.rollback();
}
/**
* @throws Exception Exception
*/
@Test
public void testPswdEncoderParameterValuesViaSysProps2() throws Exception {
final String propPrefix = "ejce.pswdEnc1";
final String exportKey = "org.antfarmer.test.springPswdEncoder";
final VolatileProperties properties = new VolatileProperties(System.getProperties());
properties.setProperty(getPropertyName(propPrefix, ConfigurerUtil.KEY_PSWD_ENCODER_CLASS), SpringBcryptEncoder.class.getName());
final ConfigurablePasswordEncoder encoder = ConfigurerUtil.configurePswdEncoder(properties.getProperties(), propPrefix);
assertEquals(SpringBcryptEncoder.class, encoder.getClass());
assertNull(PasswordEncoderStore.get(exportKey));
properties.rollback();
}
@Test(expected = EncryptorConfigurationException.class)
public void testPswdEncoderParameterValuesViaSysPropsWrongProps() {
final VolatileProperties sysProps = new VolatileProperties(System.getProperties());
sysProps.setProperty(ConfigurerUtil.KEY_PROPERTY_PREFIX, "prefix");
try {
ConfigurerUtil.configurePswdEncoder(sysProps.getProperties());
}
finally {
sysProps.rollback();
}
}
@Test(expected = EncryptorConfigurationException.class)
public void testPswdEncoderNoClass() {
final Properties properties = new Properties();
ConfigurerUtil.configurePswdEncoder(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testPswdEncoderBadClass() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PSWD_ENCODER_CLASS, "o");
ConfigurerUtil.configurePswdEncoder(properties);
}
@Test(expected = EncryptorConfigurationException.class)
public void testPswdEncoderWrongClass() {
final Properties properties = new Properties();
properties.setProperty(ConfigurerUtil.KEY_PSWD_ENCODER_CLASS, Integer.class.getName());
ConfigurerUtil.configurePswdEncoder(properties);
}
@Test
public void testGetCipherInstance() throws GeneralSecurityException {
Cipher cipher;
final AesParameters params = new AesParameters();
cipher = ConfigurerUtil.getCipherInstance(params);
assertEquals(AesParameters.ALGORITHM_AES + '/' + params.getBlockMode() + '/' + params.getPadding(), cipher.getAlgorithm());
params.setBlockMode(AesParameters.BLOCK_MODE_CFB).setPadding(AesParameters.PADDING_PKCS5);
cipher = ConfigurerUtil.getCipherInstance(params);
assertEquals(AesParameters.ALGORITHM_AES + '/' + AesParameters.BLOCK_MODE_CFB + '/' + AesParameters.PADDING_PKCS5, cipher.getAlgorithm());
params.setBlockMode(AesParameters.BLOCK_MODE_OFB).setPadding(AesParameters.PADDING_NONE).setProvider(BC_PROVIDER);
cipher = ConfigurerUtil.getCipherInstance(params);
assertEquals(AesParameters.ALGORITHM_AES + '/' + AesParameters.BLOCK_MODE_OFB + '/' + AesParameters.PADDING_NONE, cipher.getAlgorithm());
assertEquals(BouncyCastleProvider.class, cipher.getProvider().getClass());
}
@Test
public void testParseInt() {
assertEquals(new Integer(1), ConfigurerUtil.parseInt("1"));
assertEquals(new Integer(1), ConfigurerUtil.parseInt("01"));
assertEquals(new Integer(10), ConfigurerUtil.parseInt("10"));
assertEquals(new Integer(-10), ConfigurerUtil.parseInt("-10"));
assertNull(ConfigurerUtil.parseInt("ddd"));
assertNull(ConfigurerUtil.parseInt("d6d"));
assertNull(ConfigurerUtil.parseInt(""));
}
private String getPropertyName(final String prefix, final String key) {
return prefix == null ? key : prefix + "." + key;
}
public static class DefaultSaltGenerator implements SaltGenerator {
/**
* {@inheritDoc}
*/
@Override
public void generateSalt(final byte[] saltData) {
// nothing
}
}
public static class DefaultSaltMatcher implements SaltMatcher {
/**
* {@inheritDoc}
*/
@Override
public void verifySaltMatch(final byte[] cipherSalt) throws GeneralSecurityException {
// nothing
}
}
public static class MyKeyLoader implements KeyLoader {
private static Key key;
@Override
public Key loadKey(final String algorithm) {
try {
return key = CryptoUtil.generateSecretKey(AbstractAlgorithmParameters.KEY_SIZE_128, algorithm);
}
catch (final NoSuchAlgorithmException e) {
throw new EncryptorConfigurationException(e);
}
}
}
public static class MyMacKeyLoader implements KeyLoader {
private static Key key;
@Override
public Key loadKey(final String algorithm) {
try {
return key = CryptoUtil.generateSecretKey(AbstractAlgorithmParameters.KEY_SIZE_128, algorithm);
}
catch (final NoSuchAlgorithmException e) {
throw new EncryptorConfigurationException(e);
}
}
}
}
|
package ch.ubx.startlist.client;
import java.util.List;
import ch.ubx.startlist.client.ui.FlightEntryListGUI;
import ch.ubx.startlist.shared.FeDate;
import ch.ubx.startlist.shared.FeFlightEntry;
import ch.ubx.startlist.shared.FePlace;
import ch.ubx.startlist.shared.FeYear;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class FlightEntryServiceDelegate {
private FlightEntryServiceAsync flightEntryService = GWT.create(FlightEntryService.class);
FlightEntryListGUI gui;
public void createOrUpdateFlightEntry(final FeFlightEntry flightEntry) {
flightEntryService.createOrUpdateFlightEntry(flightEntry, new AsyncCallback<FeFlightEntry>() {
@Override
public void onFailure(Throwable caught) {
gui.service_eventUpdateFlightEntryFailed(caught);
}
@Override
public void onSuccess(FeFlightEntry result) {
gui.service_eventUpdateSuccessful(result);
}
});
}
public void removeFlightEntry(final FeFlightEntry flightEntry) {
flightEntryService.removeFlightEntry(flightEntry, new AsyncCallback<FeFlightEntry>() {
@Override
public void onFailure(Throwable caught) {
gui.service_eventRemoveFlightEntryFailed(caught);
}
@Override
public void onSuccess(FeFlightEntry result) {
gui.service_eventRemoveFlightEntrySuccessful(result);
}
});
}
public void listDate(final FePlace place) {
flightEntryService.listDate(place, new AsyncCallback<List<FeDate>>() {
@Override
public void onFailure(Throwable caught) {
gui.service_eventListDatesFailed(caught);
}
@Override
public void onSuccess(List<FeDate> result) {
gui.service_eventListDatesSuccessful(result);
}
});
}
public void listYears() {
flightEntryService.listYear(new AsyncCallback<List<FeYear>>() {
@Override
public void onFailure(Throwable caught) {
gui.service_eventListYearsFailed(caught);
}
@Override
public void onSuccess(List<FeYear> result) {
gui.service_eventListYearsSuccessful(result);
}
});
}
public void listPlaces(FeYear year) {
flightEntryService.listPlace(year, new AsyncCallback<List<FePlace>>() {
@Override
public void onFailure(Throwable caught) {
gui.service_eventListPlacesFailed(caught);
}
@Override
public void onSuccess(List<FePlace> result) {
gui.service_eventListPlacesSuccessful(result);
}
});
}
}
|
/*
* 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 frsjavaseclient;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import ws.client.partner.CustomerNotFoundException_Exception;
import ws.client.partner.GeneralException_Exception;
import ws.client.partner.Partner;
import ws.client.reservation.FlightReservation;
import ws.client.reservation.FlightReservationNotFoundException_Exception;
/**
*
* @author Administrator
*/
public class FRSJavaSeClient {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of partner> ");
String username = scanner.nextLine().trim();
try {
Partner currentPartner = partnerLogin(username);
} catch (CustomerNotFoundException_Exception | GeneralException_Exception ex) {
System.out.println(ex);
}
Integer response = 0;
while (true) {
System.out.println("*** FRS Management :: Flight Planning Module ***\n");
System.out.println("1: Reserve Flight");
System.out.println("2: Retrieve Flight Reservation By ID");
System.out.println("3: Logout\n");
response = 0;
while (response < 1 || response > 3) {
System.out.print("> ");
response = scanner.nextInt();
if (response == 1) {
System.out.print("Enter number of passengers> ");
Integer numOfPassengers = Integer.valueOf(scanner.nextLine().trim());
List<String[]> passengerList;
List<String> creditCardList;
for (int i = 0; i < numOfPassengers; i++)
{
System.out.print("Enter passenger particulars> ");
String passenger = scanner.nextLine().trim();
String[] passengerParticulars = passenger.split(",");
passengerList.add(passengerParticulars);
System.out.print("Enter credit card number> ");
String cardNumber = scanner.nextLine().trim();
creditCardList.add(cardNumber);
System.out.print("Enter credit card number> ");
String cabinClassType = scanner.nextLine().trim();
}
System.out.print("Enter number of passengers> ");
Integer numOfPassengers = Integer.valueOf(scanner.nextLine().trim());
System.out.print("Enter number of passengers> ");
Integer numOfPassengers = Integer.valueOf(scanner.nextLine().trim());
System.out.print("Enter number of passengers> ");
Integer numOfPassengers = Integer.valueOf(scanner.nextLine().trim());
} else if (response == 2) {
System.out.print("Enter flight reservation ID> ");
Long reservationId = Long.valueOf(scanner.nextLine().trim());
try {
FlightReservation flightReservation = retrieveFlightReservationByID(reservationId);
System.out.println(flightReservation);
} catch (FlightReservationNotFoundException_Exception ex) {
System.out.println(ex);
}
} else if (response == 3) {
break;
} else {
System.out.println("Invalid option, please try again!\n");
}
}
if (response == 3) {
break;
}
}
}
private static Partner partnerLogin(java.lang.String username) throws CustomerNotFoundException_Exception, GeneralException_Exception {
ws.client.partner.PartnerEntityWebService_Service service = new ws.client.partner.PartnerEntityWebService_Service();
ws.client.partner.PartnerEntityWebService port = service.getPartnerEntityWebServicePort();
return port.partnerLogin(username);
}
private static FlightReservation retrieveFlightReservationByID(java.lang.Long flightReservationId) throws FlightReservationNotFoundException_Exception {
ws.client.reservation.FlightReservationWebService_Service service = new ws.client.reservation.FlightReservationWebService_Service();
ws.client.reservation.FlightReservationWebService port = service.getFlightReservationWebServicePort();
return port.retrieveFlightReservationByID(flightReservationId);
}
private static Long reserveFlight(java.lang.Integer numOfPassengers, java.util.List<ws.client.reservation.StringArray> passengers,
java.util.List<java.lang.String> creditCard, ws.client.reservation.CabinClassType cabinClassType, java.util.List<java.lang.Long> flightScheduleIds,
java.util.List<java.lang.Long> returnFlightScheduleIds, ws.client.reservation.Customer customer) {
ws.client.reservation.FlightReservationWebService_Service service = new ws.client.reservation.FlightReservationWebService_Service();
ws.client.reservation.FlightReservationWebService port = service.getFlightReservationWebServicePort();
return port.reserveFlight(numOfPassengers, passengers, creditCard, cabinClassType, flightScheduleIds, returnFlightScheduleIds, customer);
}
}
|
package ej3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Ejercicio3 {
/*
* Implemente un programa que indique si una palabra es un palíndromo. Una
* palabra es palidromo si se lee igual de izquierda a derecha que de
* derecha a izquierda.
*/
public static void main(String[] args) throws IOException {
BufferedReader t = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Ingrese una palabra");
String palabra = t.readLine();
System.out.println(palabraInversa(palabra));
}
public static String palabraInversa(String palabra) {
String palabra_inversa = "";
for (int i = palabra.length() - 1; i >= 0; i--) {
palabra_inversa += palabra.charAt(i);
}
if (palabra_inversa.equals(palabra)) {
return "Es Palindromo";
} else {
return "No es Palindromo";
}
}
}
|
package edu.cecar.controlador;
import edu.cecar.modelo.Dato;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripperByArea;
/**
*Clase que controla en scraping a los PDF
*
*/
public class ScrapingPdf {
public String obtenerTextoPdf(int pagina, int x, int y, int ancho, int alto, String rutaArchivo) throws IOException {
PDDocument document = PDDocument.load(new File(rutaArchivo));
PDFTextStripperByArea textStripper = new PDFTextStripperByArea();
Rectangle2D rectangulo = new java.awt.geom.Rectangle2D.Float(x, y, ancho, alto);
textStripper.addRegion("region", rectangulo);
PDPage docPage = document.getPage(pagina);
textStripper.extractRegions(docPage);
String contenido = textStripper.getTextForRegion("region");
document.close();
return contenido;
}
public List<Dato> obtenerDatosPdf(String rutaArchivo, int pagina) {
int y = 300;
List<Dato> datos = new ArrayList();
System.out.println("------------------------------------------------------");
try {
for (int i = 0; i < 10; i++) {
Dato dato = new Dato();
String fecha = obtenerTextoPdf(0, 350, 220, 100, 20,rutaArchivo);
String nombrePais = obtenerTextoPdf(pagina, -375, y, 550, 20, rutaArchivo);
String totalCasos = obtenerTextoPdf(pagina, 200, y, 100, 20, rutaArchivo);
String casosNuevos = obtenerTextoPdf(pagina, 250, y, 100, 20, rutaArchivo);
String muertos = obtenerTextoPdf(pagina, 350, y, 100, 20, rutaArchivo);
String muertosNuevos = obtenerTextoPdf(pagina, 430, y, 100, 20, rutaArchivo);
nombrePais = nombrePais.replaceAll("\\s", "");
nombrePais = nombrePais.replaceAll("[()]", "");
totalCasos = totalCasos.replaceAll("\\s", "");
casosNuevos = casosNuevos.replaceAll("\\s", "");
muertos = muertos.replaceAll("\\s", "");
muertosNuevos = muertosNuevos.replaceAll("\\s", "");
System.out.println("Fecha = "+fecha.trim());
System.out.println("Pais = "+nombrePais);
System.out.println("Casos Confirmados = "+totalCasos);
System.out.println("Casos Confirmados Nuevos = "+casosNuevos);
System.out.println("Total Muertes = "+muertos);
System.out.println("Total Nuevas Muertes = "+muertosNuevos);
System.out.println("");
dato.setFecha(fecha);
dato.setNombrePais(nombrePais);
dato.setCasosConfirmados(totalCasos);
dato.setCasosConfirmadosNuevos(casosNuevos);
dato.setTotalMuertes(muertos);
dato.setTotalNuevasMuertes(muertosNuevos);
datos.add(dato);
y += 20;
}
return datos;
} catch (IOException ex) {
Logger.getLogger(ScrapingPdf.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
|
package com.gmail.ivanytskyy.vitaliy.service;
import java.util.List;
import com.gmail.ivanytskyy.vitaliy.model.LessonInterval;
/*
* Service interface for controllers which need a point of entry to LessonIntervalRepository
* @author Vitaliy Ivanytskyy
*/
public interface LessonIntervalService {
LessonInterval create(LessonInterval lessonInterval);
LessonInterval findById(long id);
List<LessonInterval> findAll();
void deleteById(long id);
boolean isExistsWithParameters(String lessonStart, String lessonFinish);
} |
package Iterator;
/**
*
* @author MSI
*/
public class errorsInPatientList implements Iterator{
public errorsInPatientList(){
}
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object next() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package com.xiaodao.admin.client;
import com.github.pagehelper.PageInfo;
import com.xiaodao.feign.config.MultipartSupportConfig;
import com.xiaodao.core.result.RespDataVO;
import com.xiaodao.core.result.RespVO;
import com.xiaodao.core.result.RespVOBuilder;
import com.xiaodao.admin.entity.SysMenu;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@FeignClient(value = "system-service", path = "/sysMenu", fallbackFactory = SysMenuClientFallback.class, configuration = MultipartSupportConfig.class)
public interface SysMenuClient {
/**
* 新增
*
* @param sysMenu
* @return
*/
@PostMapping("/insert")
RespVO insert(@RequestBody SysMenu sysMenu);
/**
* 带有空值判断的新增
*
* @param sysMenu
* @return
*/
@PostMapping("/insertSelective")
RespVO insertSelective(@RequestBody SysMenu sysMenu);
/**
* 批量新增
*
* @param list
* @return
*/
@PostMapping("/batchInsert")
RespVO batchInsert(@RequestBody List<SysMenu> list);
/**
* 带有空值判断的新增
*
* @param list
* @return
*/
@PostMapping("/batchInsertSelective")
RespVO batchInsertSelective(@RequestBody List<SysMenu> list);
/**
* 根据主键更新
*
* @param sysMenu
* @return
*/
@PutMapping("/updateByPrimaryKey")
RespVO updateByPrimaryKey(@RequestBody SysMenu sysMenu);
/**
* 根据空值判断的主键更新
*
* @param sysMenu
* @return
*/
@PutMapping("/updateSelectiveByPrimaryKey")
RespVO updateSelectiveByPrimaryKey(@RequestBody SysMenu sysMenu);
/**
* 批量更新
*
* @param list
* @return
*/
@PutMapping("/batchUpdate")
RespVO batchUpdate(@RequestBody List<SysMenu> list);
/**
* 带有空值判断的批量更新
*
* @param list
* @return
*/
@PutMapping("/batchUpdateSelective")
RespVO batchUpdateSelective(@RequestBody List<SysMenu> list);
/**
* 更新插入
*
* @param sysMenu
* @return
*/
@PostMapping("/upsert")
RespVO upsert(@RequestBody SysMenu sysMenu);
/**
* 带有空值判断的更新插入
*
* @param sysMenu
* @return
*/
@PostMapping("/upsertSelective")
RespVO upsertSelective(@RequestBody SysMenu sysMenu);
/**
* 批量更新插入
*
* @param list
* @return
*/
@PostMapping("/batchUpsert")
RespVO batchUpsert(@RequestBody List<SysMenu> list);
/**
* 带有空值判断的批量更新插入
*
* @param list
* @return
*/
@PostMapping("/batchUpsertSelective")
RespVO batchUpsertSelective(@RequestBody List<SysMenu> list);
/**
* 通过主键删除
*
* @param menuId
* @return
*/
@DeleteMapping("/{menuId}")
RespVO deleteByPrimaryKey(@PathVariable(value = "menuId") Long menuId);
/**
* 通过主键批量删除
*
* @param list
* @return
*/
@DeleteMapping("/deleteBatchByPrimaryKeys")
RespVO deleteBatchByPrimaryKeys(@RequestBody List<Long> list);
/**
* 条件删除
*
* @param sysMenu
* @return
*/
@DeleteMapping("/delete")
RespVO delete(@RequestBody SysMenu sysMenu);
/**
* 通过主键查询
*
* @param menuId
* @return
*/
@GetMapping("/{menuId}")
RespVO<SysMenu> queryByPrimaryKey(@PathVariable(value = "menuId") Long menuId);
/**
* 通过主键批量查询
*
* @param list
* @return
*/
@PostMapping("/queryBatchPrimaryKeys")
RespVO<RespDataVO<SysMenu>> queryBatchPrimaryKeys(@RequestBody List<Long> list);
/**
* 条件查询一个
*
* @param sysMenu
* @return
*/
@PostMapping("/queryOne")
RespVO<SysMenu> queryOne(@RequestBody SysMenu sysMenu);
/**
* 条件查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryByCondition")
RespVO<RespDataVO<SysMenu>> queryByCondition(@RequestBody SysMenu sysMenu);
/**
* 条件分页查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryPageByCondition")
RespVO<PageInfo<SysMenu>> queryPageByCondition(@RequestBody SysMenu sysMenu);
/**
* 模糊查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryFuzzy")
RespVO<RespDataVO<SysMenu>> queryFuzzy(@RequestBody SysMenu sysMenu);
/**
* 模糊分页查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryPageFuzzy")
RespVO<PageInfo<SysMenu>> queryPageFuzzy(@RequestBody SysMenu sysMenu);
/**
* 模糊条件查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryByLikeCondition")
RespVO<RespDataVO<SysMenu>> queryByLikeCondition(@RequestBody SysMenu sysMenu);
/**
* 模糊分页条件查询
*
* @param sysMenu
* @return
*/
@PostMapping("/queryPageByLikeCondition")
RespVO<PageInfo<SysMenu>> queryPageByLikeCondition(@RequestBody SysMenu sysMenu);
/**
* 条件查询数量
*
* @param sysMenu
* @return
*/
@PostMapping("/queryCount")
RespVO<Long> queryCount(@RequestBody SysMenu sysMenu);
/**
* 分组统计
*
* @param sysMenu
* @return
*/
@PostMapping("/statisticsGroup")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroup(@RequestBody SysMenu sysMenu);
/**
* 日统计
*
* @param sysMenu
* @return
*/
@PostMapping("/statisticsGroupByDay")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByDay(@RequestBody SysMenu sysMenu);
/**
* 月统计
*
* @param sysMenu
* @return
*/
@PostMapping("/statisticsGroupByMonth")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByMonth(@RequestBody SysMenu sysMenu);
/**
* 年统计
*
* @param sysMenu
* @return
*/
@PostMapping("/statisticsGroupByYear")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByYear(@RequestBody SysMenu sysMenu);
/**
* 查询系统所有菜单(含按钮)
*
* @return 菜单列表
*/
@GetMapping("/selectMenuAll")
RespVO<RespDataVO<SysMenu>> selectMenuAll();
/**
* 查询系统正常显示菜单(不含按钮)
*
* @return 菜单列表
*/
@GetMapping("/selectMenuNormalAll")
RespVO<RespDataVO<SysMenu>> selectMenuNormalAll();
/**
* 根据用户ID查询菜单
*
* @param userId 用户ID
* @return 菜单列表
*/
@GetMapping("/selectMenusByUserId")
RespVO<RespDataVO<SysMenu>> selectMenusByUserId(@RequestParam("userId") Long userId);
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
@GetMapping("/selectPermsByUserId")
RespVO<RespDataVO<String>> selectPermsByUserId(@RequestParam("userId") Long userId);
/**
* 根据角色ID查询菜单ID
*
* @param roleId 角色ID
* @return 权限列表
*/
@GetMapping("/selectMenuIdsByRoleId")
public RespVO<RespDataVO<Long>> selectMenuIdsByRoleId(@RequestParam("roleId") Long roleId);
/**
* @param roleId 角色ID
* @return 菜单列表
*/
@GetMapping("/selectMenuTree")
RespVO<RespDataVO<String>> selectMenuTree(@RequestParam("roleId") Long roleId);
}
class SysMenuClientFallback implements SysMenuClient {
@Override
public RespVO insert(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO insertSelective(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchInsert(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchInsertSelective(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO updateByPrimaryKey(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO updateSelectiveByPrimaryKey(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpdate(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpdateSelective(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO upsert(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO upsertSelective(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpsert(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpsertSelective(List<SysMenu> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO deleteByPrimaryKey(Long menuId) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO deleteBatchByPrimaryKeys(List<Long> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO delete(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<SysMenu> queryByPrimaryKey(Long menuId) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> queryBatchPrimaryKeys(List<Long> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<SysMenu> queryOne(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> queryByCondition(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysMenu>> queryPageByCondition(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> queryFuzzy(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysMenu>> queryPageFuzzy(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> queryByLikeCondition(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysMenu>> queryPageByLikeCondition(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<Long> queryCount(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroup(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByDay(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByMonth(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByYear(SysMenu sysMenu) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> selectMenuAll() {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> selectMenuNormalAll() {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysMenu>> selectMenusByUserId(Long userId) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<String>> selectPermsByUserId(Long userId) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Long>> selectMenuIdsByRoleId(Long roleId) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<String>> selectMenuTree(Long roleId) {
return RespVOBuilder.failure("system-service服务不可用");
}
} |
package misc.exceptions;
public class InvalidElementException extends RuntimeException {
public InvalidElementException() {
super();
}
public InvalidElementException(String message) {
super(message);
}
public InvalidElementException(String message, Throwable cause) {
super(message, cause);
}
public InvalidElementException(Throwable cause) {
super(cause);
}
}
|
package th.ac.rru.csit.benjawan53023263010;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends Activity {
Button bback,bplus;
EditText edt1,edt2;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
bback = (Button)findViewById(R.id.BackCalculator);
bplus = (Button)findViewById(R.id.plus);
edt1 = (EditText)findViewById(R.id.editText1);
edt2 = (EditText)findViewById(R.id.editText2);
tv = (TextView)findViewById(R.id.textView2);
bback.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.setClass(Calculator.this, MainActivity.class);
startActivity(i);
}
});
bplus.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText( Integer.parseInt(edt1.getText().toString())+
Integer.parseInt(edt2.getText().toString())+
"");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_calculator, menu);
return true;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public class qf {
private static String a = "tencentmap";
public static void a(String str) {
boolean z = qe.a;
}
}
|
package com.example.user.catchthemonster;
/**
* Created by User on 08.06.2017.
*/
public class Monstrik extends GameObject {
Direction movementDirection = Direction.NONE;
static final int MOVE_SPEED = 50;
Monstrik(int x, int y){
super(x, y);
}
@Override
public void update(long millisSinceLastUpdate) {
float seconds = (float) millisSinceLastUpdate / 1000;
switch (movementDirection) {
case LEFT:
break;
case TOP:
break;
case DOWN:
break;
case RIGHT:
this.x += seconds * MOVE_SPEED;
break;
case NONE:
break;
}
}
void goRight(){
movementDirection = Direction.RIGHT;
}
}
|
/*
* Minesweeper Project
* by Group3 : Arnaud BABOL, Guillaume SIMMONEAU
*/
package View.GraphicalViews.Scores;
import Controler.Minesweeper;
import Model.Events.RefreshEvent;
import Model.Game.WorldModel;
import Model.Options.GameDifficulty;
import genericGraphicalComponents.ObservationEvent;
import genericGraphicalComponents.Observer;
import genericGraphicalComponents.ValidateButton;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.GregorianCalendar;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
*
* @author simonneau
*/
public class LogScorePanel extends JDialog implements Observer{
private static final String DEFAULT_PSEUDO ="anonymous";
private int score;
private GameDifficulty gd;
private JTextField pseudo = new JTextField(LogScorePanel.DEFAULT_PSEUDO);
private ValidateButton save = new ValidateButton("save");
/**
*
*/
public LogScorePanel() {
this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
this.setVisible(false);
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout());
this.setMinimumSize(new Dimension(200,115));
this.add(new JLabel("Save your score !"));
this.add(pseudo);
this.add(save);
save.addObserver(this);
}
/**
*
* @param ev
*/
@Override
public void reactToChanges(ObservationEvent ev) {
Minesweeper.getInstance().getScores().saveScore(pseudo.getText(), this.score, new GregorianCalendar(), this.gd.getName());
this.setVisible(false);
}
/**
*
* @param event
*/
public void refresh(RefreshEvent event){
WorldModel wm = (WorldModel)event.getSource();
this.score = wm.getTime();
this.gd = wm.getGameDifficulty();
if (this.gd != GameDifficulty.CUSTOM) {
Minesweeper.getInstance().getScores().LoadScores(gd.getName());
if(Minesweeper.getInstance().getScores().isBetterThanLastPerformanceSaved(this.score)){
this.setVisible(true);
}
}
}
}
|
/*
* 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 people;
/**
*
* @author student
*/
public class PersonDialog extends javax.swing.JDialog {
private Human person;
private String actionButton = "Storno";
/**
* Creates new form PersonDialog
*/
public PersonDialog(java.awt.Frame parent, boolean modal, Human person) {
super(parent, modal);
initComponents();
this.person = person;
name.setText(person.getName());
age.setValue(person.getAge());
weight.setValue(person.getWeight());
}
public String showDialog(){
this.setVisible(true);
return actionButton;
}
public Human getPerson(){
this.person.setName(name.getText());
this.person.setAge((int)age.getValue());
this.person.setWeight((int)weight.getValue());
return this.person;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
name = new javax.swing.JTextField();
nameLabel = new javax.swing.JLabel();
OKButton = new javax.swing.JButton();
CancelButton = new javax.swing.JButton();
age = new javax.swing.JSpinner();
ageLabel = new javax.swing.JLabel();
weight = new javax.swing.JSlider();
weightLabel = new javax.swing.JLabel();
showWeight = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setModal(true);
name.setToolTipText("Zadej jméno");
nameLabel.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
nameLabel.setText("Jméno");
OKButton.setText("OK");
OKButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OKButtonActionPerformed(evt);
}
});
CancelButton.setText("Storno");
CancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CancelButtonActionPerformed(evt);
}
});
ageLabel.setText("Věk");
weight.setMajorTickSpacing(30);
weight.setMaximum(150);
weight.setMinorTickSpacing(10);
weight.setPaintLabels(true);
weightLabel.setText("Váha");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(68, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(OKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(CancelButton))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
.addComponent(ageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(weightLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(weight, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(showWeight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(age, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(52, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(showWeight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(weightLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(weight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OKButton)
.addComponent(CancelButton))
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
actionButton = "OK";
this.dispose();
}//GEN-LAST:event_OKButtonActionPerformed
private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
actionButton = "Storno";
this.dispose();
}//GEN-LAST:event_CancelButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton CancelButton;
private javax.swing.JButton OKButton;
private javax.swing.JSpinner age;
private javax.swing.JLabel ageLabel;
private javax.swing.JTextField name;
private javax.swing.JLabel nameLabel;
private javax.swing.JLabel showWeight;
private javax.swing.JSlider weight;
private javax.swing.JLabel weightLabel;
// End of variables declaration//GEN-END:variables
}
|
//package com.pain.treeobservabledemo.src;
//
//import android.app.Activity;
//import android.graphics.Color;
//import android.os.Bundle;
//import android.view.View;
//import android.view.ViewTreeObserver;
//import android.view.ViewTreeObserver.OnGlobalLayoutListener;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;
//import android.widget.ImageView;
//
//import com.example.d_changealphabyscroll.widget.ObservableScrollView.ScrollViewListener;
//
//public class MainActivity extends Activity implements ScrollViewListener{
//
// private View layoutHead;
// private ObservableScrollView scrollView;
// private ImageView imageView;
// private WebView webView;
//
// private int height ;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// initView();
// }
//
//
// private void initView() {
// webView = (WebView) findViewById(R.id.webview1);
// scrollView = (ObservableScrollView) findViewById(R.id.scrollview);
// layoutHead = findViewById(R.id.view_head);
// imageView = (ImageView) findViewById(R.id.imageView1);
// layoutHead.setBackgroundColor(Color.argb(0, 0xfd, 0x91, 0x5b));
//
// //初始化webview
// //启用支持javascript
// WebSettings settings = webView.getSettings();
// settings.setJavaScriptEnabled(true);
// webView.loadUrl("http://www.baidu.com/");
// //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
// webView.setWebViewClient(new WebViewClient(){
// @Override
// public boolean shouldOverrideUrlLoading(WebView view, String url) {
// //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
// view.loadUrl(url);
// return true;
// }
// });
//
//
// //获取顶部图片高度后,设置滚动监听
// ViewTreeObserver vto = imageView.getViewTreeObserver();
// vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
// @Override
// public void onGlobalLayout() {
// imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// height = imageView.getHeight();
// imageView.getWidth();
//
// scrollView.setScrollViewListener(MainActivity.this);
// }
// });
//
//
//
// }
//
//
// @Override
// public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
// int oldx, int oldy) {
//
//// Log.i("TAG","y--->"+y+" height-->"+height);
// if(y<=height){
// float scale =(float) y /height;
// float alpha = (255 * scale);
//// Log.i("TAG","alpha--->"+alpha);
//
// //layout全部透明
//// layoutHead.setAlpha(scale);
//
// //只是layout背景透明(仿知乎滑动效果)
// layoutHead.setBackgroundColor(Color.argb((int) alpha, 0xfd, 0x91, 0x5b));
// }
//
// }
//}
|
/*
* Copyright 2008 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.extrt;
import vanadis.core.system.VM;
import vanadis.common.text.Printer;
import vanadis.ext.CommandExecution;
import vanadis.osgi.Context;
final class EnvExecution implements CommandExecution {
@Override
public void exec(String command, String[] args, Printer p, Context context) {
p.p("Location : ").p(context.getLocation().toLocationString()).cr();
p.p("Home : ").p(context.getHome()).cr();
p.p("PID : ").p(VM.pid()).cr();
p.p("VM : ").p(VM.VERSION).cr();
p.p("cwd : ").p(VM.CWD).cr();
p.p("tmp : ").p(VM.TMP).cr();
}
}
|
import java.util.Scanner;
public class exer22 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int c1 = 0;
int c2 = 0;
int c3 = 0;
System.out.println("Digite o número total de votantes:");
int v = input.nextInt();
for(int i = 1; i <= v; i++) {
System.out.println("Digite 1 - Candidato A; 2 - Candidato B; 3 - Candidato C");
int c = input.nextInt();
if(c == 1)
c1++;
else if(c == 2)
c2++;
else if(c == 3)
c3++;
else
System.out.println("Candidato inválido! Comece novamente.");
}
System.out.println("Quantidade de votos de cada candidato: ");
System.out.println("Candidato A = " + c1);
System.out.println("Candidato B = " + c2);
System.out.println("Candidato C = " + c3);
input.close();
}
}
|
package com.example.ahmed.octopusmart.Interfaces;
/**
* Created by sotra on 12/19/2017.
*/
public interface LoadingActionClick {
void OnClick();
}
|
package com.skyley.skstack_ip.api.skcommands;
import com.skyley.skstack_ip.api.SKUtil;
/**
* SKLL64コマンドに対応したクラス、SKCommandを継承
*/
public class SKLL64 extends SKCommand {
/** 接続先HEXアドレス */
private String hexAddress;
/**
* コンストラクタ
* @param hexAddress 接続先HEXアドレス
*/
public SKLL64(String hexAddress) {
this.hexAddress = hexAddress;
}
/**
* 引数チェック
*/
@Override
public boolean checkArgs() {
// TODO 自動生成されたメソッド・スタブ
return SKUtil.isValidHexString(hexAddress, 16);
}
/**
* コマンド文字列組み立て
*/
@Override
public void buildCommand() {
// TODO 自動生成されたメソッド・スタブ
commandString = "SKLL64 " + hexAddress + "\r\n";
}
}
|
package view;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import control.DBConnection;
import toolkit.Utility;
import model.Usercode;
/**
* Created by Jordan on 2017/11/19.
*/
public class LoginView extends JFrame implements ActionListener{
private static LoginView instance;
public static LoginView getInstance(){
if(instance==null)instance=new LoginView();
return instance;
}
private JPanel jPanel1,jPanel2,jPanel3;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton jButtonConfirm,jButtonCancel;
private LoginView(){
super("Login");
//Toolkit toolkit=Toolkit.getDefaultToolkit();
//Dimension screenSize=toolkit.getScreenSize();
GridLayout gridLayout=new GridLayout(3,1);
Container container=this.getContentPane();
container.setLayout(gridLayout);
jPanel1=new JPanel();
//jPanel1.setLayout(new FlowLayout());
usernameField =new JTextField(10);
jPanel1.add(new JLabel("Username:"));
jPanel1.add(usernameField);
container.add(jPanel1);
jPanel2=new JPanel(new FlowLayout());
passwordField =new JPasswordField(10);
jPanel2.add(new JLabel("Password:"));
jPanel2.add(passwordField);
container.add(jPanel2);
jPanel3=new JPanel(new FlowLayout());
jButtonConfirm=new JButton("Confirm");
jButtonConfirm.addActionListener(this);
jButtonCancel=new JButton("Quit");
jButtonCancel.addActionListener(this);
jPanel3.add(jButtonConfirm);
jPanel3.add(jButtonCancel);
container.add(jPanel3);
this.setSize(300,200);
this.setVisible(true);
Utility.setWindowAtCenter(this);
//this.setLocation((screenSize.width-this.getWidth())/2,(screenSize.height-this.getHeight())/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButtonConfirm){
boolean correct=false;
Statement statement;
ResultSet resultSet;
try{
statement=DBConnection.getConnection().createStatement();
resultSet = statement.executeQuery("select * from "+ Usercode.TABLE);
System.out.println(resultSet.wasNull());
while (resultSet.next()){
if(resultSet.getString(Usercode.NAME).equals(usernameField.getText()))
if(String.valueOf(passwordField.getPassword()).equals(resultSet.getString(Usercode.PW))){
correct=true;break;
}
}
resultSet.close();
statement.close();
}catch (SQLException er){
er.printStackTrace();
}finally {
if(!correct)
JOptionPane.showMessageDialog(this,"The username or password is incorrect.",
"Invalid",JOptionPane.ERROR_MESSAGE);
else {
System.out.println("login:ok");
MainPageView.getInstance();
this.dispose();
}
}
}else{
this.dispose();
}
}
}
|
package ibd.web;
import ibd.persistence.entity.ClosedQuestion;
import ibd.service.SubcategoryService;
import ibd.service.ClosedQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
@RequestMapping("/closed-questions")
public class ClosedQuestionController {
@Autowired
private ClosedQuestionService closedQuestionService;
@Autowired
private SubcategoryService subcategoryService;
@RequestMapping("")
public String listAll(Model model){
model.addAttribute("questions", closedQuestionService.findAll());
return "closed-questions/list";
}
@GetMapping("/add")
public String add(Model model){
model.addAttribute("closedQuestion", new ClosedQuestion());
model.addAttribute("subcategories", subcategoryService.findAll());
return "closed-questions/add";
}
@PostMapping("/add")
public String postAdd(@Valid ClosedQuestion question, BindingResult bindingResult, Model model){
if (bindingResult.hasErrors()) {
model.addAttribute("subcategories", subcategoryService.findAll());
return "closed-questions/add";
}
closedQuestionService.save(question);
return "redirect:/closed-questions";
}
@GetMapping("/delete")
public String remove(@RequestParam Long id){
closedQuestionService.remove(id);
return "redirect:/closed-questions";
}
@GetMapping("/edit")
public String edit(@RequestParam Long id, Model model){
model.addAttribute("closedQuestion", closedQuestionService.findOne(id));
model.addAttribute("subcategories", subcategoryService.findAll());
return "closed-questions/edit";
}
@PostMapping("/edit")
public String postEdit(@Valid ClosedQuestion question, BindingResult bindingResult, Model model){
if (bindingResult.hasErrors()) {
model.addAttribute("subcategories", subcategoryService.findAll());
return "closed-questions/edit";
}
closedQuestionService.save(question);
return "redirect:/closed-questions";
}
}
|
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2014, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.snmp;
import java.io.IOException;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.CommunityTarget;
import org.snmp4j.MessageDispatcher;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.Snmp;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.security.Priv3DES;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.AbstractTransportMapping;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
/**
* <p>Title: TrapReceiver</p>
* <p>Description: Testing Trap receiver</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.snmp.TrapReceiver</code></p>
*/
///** Instance logger */
//protected final Logger log = LoggerFactory.getLogger(getClass());
public class TrapReceiver implements CommandResponder {
public static void main(String[] args) {
TrapReceiver snmp4jTrapReceiver = new TrapReceiver();
try {
snmp4jTrapReceiver.listen(new UdpAddress("localhost/1062"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Trap Listner
*/
public synchronized void listen(TransportIpAddress address) throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mDispathcher.addMessageProcessingModel(new MPv1());
mDispathcher.addMessageProcessingModel(new MPv2c());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
// Create Target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
Snmp snmp = new Snmp(mDispathcher, transport);
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on " + address);
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* This method will be called whenever a pdu is received on the given port
* specified in the listen() method
*/
public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
System.out.println("Received PDU...");
PDU pdu = cmdRespEvent.getPDU();
if (pdu != null) {
if(pdu instanceof PDUv1) {
PDUv1 p1 = (PDUv1)pdu;
System.out.println("Timestamp = " + p1.getTimestamp());
}
System.out.println("Trap Type = " + pdu.getType());
System.out.println("Variables = " + pdu.getVariableBindings());
System.out.println("================================================");
}
}
} |
/**
* Write a description of class WHMan here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class WHMan extends LoginAccount
{
public WHMan(String name, String pass, String first, String last, String email)
{
super(name, pass, first, last, email);
}
public String accountOptions()
{
return "test";
}
}
|
package com.szcinda.express.params;
import com.szcinda.express.FeeDeclareStatus;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
@EqualsAndHashCode(callSuper = true)
@Data
public class QueryFeeDeclareParams extends PageParams {
private String cindaNo;
private LocalDate createTimeStart;
private LocalDate createTimeEnd;
private LocalDate deliveryDateStart;
private LocalDate deliveryDateEnd;
private FeeDeclareStatus status;
}
|
package com.ai.lovejoy777.ant;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Created by steve on 02/06/16.
*/
public class TimerLaunch extends Activity {
private TimerDbAdapter dbHelper;
private Long mRowId;
// To send and receive data to/from amica node v1
DatagramSocket d1;
InetAddress ip;
DatagramPacket send;
private ImageView myimage;
TextView swName;
TextView Name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_launch);
dbHelper = new TimerDbAdapter(this);
myimage = (ImageView) findViewById(R.id.image);
Name = (TextView) findViewById(R.id.textName);
swName = (TextView) findViewById(R.id.textswName);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(TimerDbAdapter.KEY_ROWID)
: null;
dbHelper.open();
setRowIdFromIntent();
Cursor ft = dbHelper.fetchTimer(mRowId);
ft.moveToFirst();
String name = ft.getString(ft.getColumnIndex(TimerDbAdapter.KEY_NAME));
String swname = ft.getString(ft.getColumnIndex(TimerDbAdapter.KEY_SWNAME));
if (!ft.isClosed()) {
ft.close();
}
Name.setText(name);
swName.setText(swname);
sendCom();
Thread timer = new Thread() {
public void run() {
try {
rotateAnimation(myimage);
//Display for 5 seconds
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// delete timer if it was a one off (not repeating).
Cursor ft1 = dbHelper.fetchTimer(mRowId);
ft1.moveToFirst();
String repeat = ft1.getString(ft1.getColumnIndex(TimerDbAdapter.KEY_REPEAT));
if (!ft1.isClosed()) {
ft1.close();
}
if (repeat.equals("Once")) {
dbHelper.deleteTimer(mRowId); // deletes from the database
}
dbHelper.close();
finish();
}
}
};
timer.start();
dbHelper.close();
}
private void setRowIdFromIntent() {
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(TimerDbAdapter.KEY_ROWID)
: null;
}
}
private void rotateAnimation(View view) {
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
myimage.startAnimation(animation);
}
@Override
protected void onPause() {
super.onPause();
dbHelper.close();
}
@Override
protected void onResume() {
super.onResume();
dbHelper.open();
setRowIdFromIntent();
sendCom();
}
private void sendCom() {
Cursor rs = dbHelper.fetchTimer(mRowId);
rs.moveToFirst();
String address = rs.getString(rs.getColumnIndex(TimerDbAdapter.KEY_ADDRESS));
String code = rs.getString(rs.getColumnIndex(TimerDbAdapter.KEY_CODE));
if (!rs.isClosed()) {
rs.close();
}
try {
new SendData().execute(address + code);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "No Connection", Toast.LENGTH_SHORT).show();
System.out.println("No connection");
}
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
return false;
}
private class SendData extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String s = params[0];
Cursor rs = dbHelper.fetchTimer(mRowId);
rs.moveToFirst();
String localip = rs.getString(rs.getColumnIndex(TimerDbAdapter.KEY_LOCALIP));
String port = rs.getString(rs.getColumnIndex(TimerDbAdapter.KEY_PORT));
if (!rs.isClosed()) {
rs.close();
}
int port1 = Integer.valueOf(port);
byte[] b = (s.getBytes());
if (isOnline()) {
try {
ip = InetAddress.getByName(localip);
d1 = new DatagramSocket();
send = new DatagramPacket(b, b.length, ip, port1);
d1.send(send);
d1.setSoTimeout(3000);
//Toast.makeText(getApplicationContext(), "Sw Code: " + code, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "No Connection", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "No network", Toast.LENGTH_SHORT).show();
}
return null;
}
}
@Override
public void onDestroy() {
dbHelper.close();
super.onDestroy();
overridePendingTransition(R.anim.back2, R.anim.back1);
}
}
|
/** Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HftpFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.SleepJob;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.ToolRunner;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class TestTokenCache {
private static final int NUM_OF_KEYS = 10;
// my sleep class - adds check for tokenCache
static class MySleepMapper extends SleepJob.SleepMapper {
/**
* attempts to access tokenCache as from client
*/
@Override
public void map(IntWritable key, IntWritable value, Context context)
throws IOException, InterruptedException {
// get token storage and a key
Credentials ts = context.getCredentials();
byte[] key1 = ts.getSecretKey(new Text("alias1"));
Collection<Token<? extends TokenIdentifier>> dts = ts.getAllTokens();
int dts_size = 0;
if(dts != null)
dts_size = dts.size();
if(dts_size != 2) { // one job token and one delegation token
throw new RuntimeException("tokens are not available"); // fail the test
}
if(key1 == null || ts == null || ts.numberOfSecretKeys() != NUM_OF_KEYS) {
throw new RuntimeException("secret keys are not available"); // fail the test
}
super.map(key, value, context);
}
}
class MySleepJob extends SleepJob {
@Override
public Job createJob(int numMapper, int numReducer,
long mapSleepTime, int mapSleepCount,
long reduceSleepTime, int reduceSleepCount)
throws IOException {
Job job = super.createJob(numMapper, numReducer,
mapSleepTime, mapSleepCount,
reduceSleepTime, reduceSleepCount);
job.setMapperClass(MySleepMapper.class);
//Populate tokens here because security is disabled.
populateTokens(job);
return job;
}
private void populateTokens(Job job) {
// Credentials in the job will not have delegation tokens
// because security is disabled. Fetch delegation tokens
// and populate the credential in the job.
try {
Credentials ts = job.getCredentials();
Path p1 = new Path("file1");
p1 = p1.getFileSystem(job.getConfiguration()).makeQualified(p1);
Credentials cred = new Credentials();
TokenCache.obtainTokensForNamenodesInternal(cred, new Path[] { p1 },
job.getConfiguration());
for (Token<? extends TokenIdentifier> t : cred.getAllTokens()) {
ts.addToken(new Text("Hdfs"), t);
}
} catch (IOException e) {
Assert.fail("Exception " + e);
}
}
}
private static MiniMRCluster mrCluster;
private static MiniDFSCluster dfsCluster;
private static final Path TEST_DIR =
new Path(System.getProperty("test.build.data","/tmp"), "sleepTest");
private static final Path tokenFileName = new Path(TEST_DIR, "tokenFile.json");
private static int numSlaves = 1;
private static JobConf jConf;
private static ObjectMapper mapper = new ObjectMapper();
private static Path p1;
private static Path p2;
@BeforeClass
public static void setUp() throws Exception {
Configuration conf = new Configuration();
dfsCluster = new MiniDFSCluster(conf, numSlaves, true, null);
jConf = new JobConf(conf);
mrCluster = new MiniMRCluster(0, 0, numSlaves,
dfsCluster.getFileSystem().getUri().toString(), 1, null, null, null,
jConf);
createTokenFileJson();
verifySecretKeysInJSONFile();
dfsCluster.getNamesystem().getDelegationTokenSecretManager().startThreads();
FileSystem fs = dfsCluster.getFileSystem();
p1 = new Path("file1");
p2 = new Path("file2");
p1 = fs.makeQualified(p1);
}
@AfterClass
public static void tearDown() throws Exception {
if(mrCluster != null)
mrCluster.shutdown();
mrCluster = null;
if(dfsCluster != null)
dfsCluster.shutdown();
dfsCluster = null;
}
// create jason file and put some keys into it..
private static void createTokenFileJson() throws IOException {
Map<String, String> map = new HashMap<String, String>();
try {
KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
for(int i=0; i<NUM_OF_KEYS; i++) {
SecretKeySpec key = (SecretKeySpec) kg.generateKey();
byte [] enc_key = key.getEncoded();
map.put("alias"+i, new String(Base64.encodeBase64(enc_key)));
}
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
try {
File p = new File(tokenFileName.getParent().toString());
p.mkdirs();
// convert to JSON and save to the file
mapper.writeValue(new File(tokenFileName.toString()), map);
} catch (Exception e) {
System.out.println("failed with :" + e.getLocalizedMessage());
}
}
@SuppressWarnings("unchecked")
private static void verifySecretKeysInJSONFile() throws IOException {
Map<String, String> map;
map = mapper.readValue(new File(tokenFileName.toString()), Map.class);
assertEquals("didn't read JSON correctly", map.size(), NUM_OF_KEYS);
}
/**
* run a distributed job and verify that TokenCache is available
* @throws IOException
*/
@Test
public void testTokenCache() throws IOException {
System.out.println("running dist job");
// make sure JT starts
jConf = mrCluster.createJobConf();
// provide namenodes names for the job to get the delegation tokens for
String nnUri = dfsCluster.getURI().toString();
jConf.set(MRJobConfig.JOB_NAMENODES, nnUri + "," + nnUri);
// job tracker principla id..
jConf.set(JTConfig.JT_USER_NAME, "jt_id");
// using argument to pass the file name
String[] args = {
"-tokenCacheFile", tokenFileName.toString(),
"-m", "1", "-r", "1", "-mt", "1", "-rt", "1"
};
int res = -1;
try {
res = ToolRunner.run(jConf, new MySleepJob(), args);
} catch (Exception e) {
System.out.println("Job failed with" + e.getLocalizedMessage());
e.printStackTrace(System.out);
fail("Job failed");
}
assertEquals("dist job res is not 0", res, 0);
}
/**
* run a local job and verify that TokenCache is available
* @throws NoSuchAlgorithmException
* @throws IOException
*/
@Test
public void testLocalJobTokenCache() throws NoSuchAlgorithmException, IOException {
System.out.println("running local job");
// this is local job
String[] args = {"-m", "1", "-r", "1", "-mt", "1", "-rt", "1"};
jConf.set("mapreduce.job.credentials.json", tokenFileName.toString());
int res = -1;
try {
res = ToolRunner.run(jConf, new MySleepJob(), args);
} catch (Exception e) {
System.out.println("Job failed with" + e.getLocalizedMessage());
e.printStackTrace(System.out);
fail("local Job failed");
}
assertEquals("local job res is not 0", res, 0);
}
@Test
public void testGetTokensForNamenodes() throws IOException {
Credentials credentials = new Credentials();
TokenCache.obtainTokensForNamenodesInternal(credentials, new Path[] { p1,
p2 }, jConf);
// this token is keyed by hostname:port key.
String fs_addr =
SecurityUtil.buildDTServiceName(p1.toUri(), NameNode.DEFAULT_PORT);
Token<DelegationTokenIdentifier> nnt = TokenCache.getDelegationToken(
credentials, fs_addr);
System.out.println("dt for " + p1 + "(" + fs_addr + ")" + " = " + nnt);
assertNotNull("Token for nn is null", nnt);
// verify the size
Collection<Token<? extends TokenIdentifier>> tns = credentials.getAllTokens();
assertEquals("number of tokens is not 1", 1, tns.size());
boolean found = false;
for(Token<? extends TokenIdentifier> t: tns) {
if(t.getKind().equals(DelegationTokenIdentifier.HDFS_DELEGATION_KIND) &&
t.getService().equals(new Text(fs_addr))) {
found = true;
}
assertTrue("didn't find token for " + p1 ,found);
}
}
@Test
public void testGetTokensForHftpFS() throws IOException, URISyntaxException {
HftpFileSystem hfs = mock(HftpFileSystem.class);
DelegationTokenSecretManager dtSecretManager =
dfsCluster.getNamesystem().getDelegationTokenSecretManager();
String renewer = "renewer";
jConf.set(JTConfig.JT_USER_NAME,renewer);
DelegationTokenIdentifier dtId =
new DelegationTokenIdentifier(new Text("user"), new Text(renewer), null);
final Token<DelegationTokenIdentifier> t =
new Token<DelegationTokenIdentifier>(dtId, dtSecretManager);
final URI uri = new URI("hftp://host:2222/file1");
final String fs_addr =
SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT);
t.setService(new Text(fs_addr));
//when(hfs.getUri()).thenReturn(uri);
Mockito.doAnswer(new Answer<URI>(){
@Override
public URI answer(InvocationOnMock invocation)
throws Throwable {
return uri;
}}).when(hfs).getUri();
//when(hfs.getDelegationToken()).thenReturn((Token<? extends TokenIdentifier>) t);
Mockito.doAnswer(new Answer<Token<DelegationTokenIdentifier>>(){
@Override
public Token<DelegationTokenIdentifier> answer(InvocationOnMock invocation)
throws Throwable {
return t;
}}).when(hfs).getDelegationToken(renewer);
//when(hfs.getCanonicalServiceName).thenReturn(fs_addr);
Mockito.doAnswer(new Answer<String>(){
@Override
public String answer(InvocationOnMock invocation)
throws Throwable {
return fs_addr;
}}).when(hfs).getCanonicalServiceName();
Credentials credentials = new Credentials();
Path p = new Path(uri.toString());
System.out.println("Path for hftp="+ p + "; fs_addr="+fs_addr + "; rn=" + renewer);
TokenCache.obtainTokensForNamenodesInternal(hfs, credentials, jConf);
Collection<Token<? extends TokenIdentifier>> tns = credentials.getAllTokens();
assertEquals("number of tokens is not 1", 1, tns.size());
boolean found = false;
for(Token<? extends TokenIdentifier> tt: tns) {
System.out.println("token="+tt);
if(tt.getKind().equals(DelegationTokenIdentifier.HDFS_DELEGATION_KIND) &&
tt.getService().equals(new Text(fs_addr))) {
found = true;
assertEquals("different token", tt, t);
}
assertTrue("didn't find token for " + p, found);
}
}
}
|
/*
* 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 databaseinterface;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
* @author Veronika
*/
public class NewWorkerForm extends javax.swing.JFrame {
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/mydbtest?useUnicode=true&useSSL=true&useJDBCCompliantTimezoneShift=true";
/**
* Creates new form NewWorkerForm
*/
public NewWorkerForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
genderWorker = new javax.swing.JComboBox<>();
textNameWorker = new javax.swing.JTextField();
textPostWorker = new javax.swing.JComboBox<>();
textDateWorker = new javax.swing.JTextField();
textCountryWorker = new javax.swing.JTextField();
textEmailWorker = new javax.swing.JTextField();
textSalaryWorker = new javax.swing.JTextField();
textPassWorker = new javax.swing.JTextField();
textPhoneWorker = new javax.swing.JTextField();
textSurnameWorker = new javax.swing.JTextField();
textLoginWorker = new javax.swing.JTextField();
textCityWorker = new javax.swing.JTextField();
IDworker = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
nextbuttWorker = new javax.swing.JButton();
LogoutaddWorker = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(1320, 867));
getContentPane().setLayout(null);
genderWorker.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{"Male", "Female"}));
genderWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
genderWorkerActionPerformed(evt);
}
});
getContentPane().add(genderWorker);
genderWorker.setBounds(760, 410, 150, 40);
textNameWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textNameWorkerActionPerformed(evt);
}
});
getContentPane().add(textNameWorker);
textNameWorker.setBounds(330, 330, 150, 40);
textPostWorker.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{"Administrator", "Hotel Manager", "Assistant Hotel Manager", "Housekeeping Supervisor", "Front Desk Supervisor", "Supervisor of Guest Services", "Housekeeping"}));
textPostWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textPostWorkerActionPerformed(evt);
}
});
getContentPane().add(textPostWorker);
textPostWorker.setBounds(330, 650, 150, 40);
getContentPane().add(textDateWorker);
textDateWorker.setBounds(330, 410, 150, 40);
getContentPane().add(textCountryWorker);
textCountryWorker.setBounds(330, 490, 150, 40);
getContentPane().add(textEmailWorker);
textEmailWorker.setBounds(330, 570, 150, 40);
getContentPane().add(textSalaryWorker);
textSalaryWorker.setBounds(760, 650, 150, 40);
getContentPane().add(textPassWorker);
textPassWorker.setBounds(1110, 410, 150, 40);
getContentPane().add(textPhoneWorker);
textPhoneWorker.setBounds(760, 490, 150, 40);
getContentPane().add(textSurnameWorker);
textSurnameWorker.setBounds(760, 330, 150, 40);
getContentPane().add(textLoginWorker);
textLoginWorker.setBounds(1110, 330, 150, 40);
getContentPane().add(textCityWorker);
textCityWorker.setBounds(760, 570, 150, 40);
IDworker.setEditable(false);
IDworker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
IDworkerActionPerformed(evt);
}
});
getContentPane().add(IDworker);
IDworker.setBounds(330, 170, 150, 50);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/AddWorker.png"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 1300, 890);
nextbuttWorker.setText("jButton1");
nextbuttWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextbuttWorkerActionPerformed(evt);
}
});
getContentPane().add(nextbuttWorker);
nextbuttWorker.setBounds(710, 730, 170, 40);
LogoutaddWorker.setText("jButton2");
LogoutaddWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogoutaddWorkerActionPerformed(evt);
}
});
getContentPane().add(LogoutaddWorker);
LogoutaddWorker.setBounds(1240, 60, 50, 50);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
getContentPane().add(jComboBox1);
jComboBox1.setBounds(760, 650, 150, 40);
pack();
}// </editor-fold>//GEN-END:initComponents
private void nextbuttWorkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextbuttWorkerActionPerformed
try {
// TODO add your handling code here:
//save to database
sqlKey workersKey = new sqlKey();
int id = workersKey.id_incrementable();
if (new DBclass().add(id, textNameWorker.getText(), textSurnameWorker.getText(), Integer.parseInt(textDateWorker.getText()), textCountryWorker.getText(), textEmailWorker.getText(), textPostWorker.getSelectedItem().toString(), genderWorker.getSelectedItem().toString(), Integer.parseInt(textPhoneWorker.getText()), textCityWorker.getText(), Integer.parseInt(textSalaryWorker.getText()), textLoginWorker.getText(), textPassWorker.getText())) {
WorkerPortail workerPortail = new WorkerPortail();
workerPortail.setVisible(true);
this.hide();
System.out.println("Successfully Inserted");
} else {
System.out.println("Error");
}
} catch (SQLException ex) {
Logger.getLogger(NewWorkerForm.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_nextbuttWorkerActionPerformed
private void LogoutaddWorkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutaddWorkerActionPerformed
// TODO add your handling code here:
Interface interFace = new Interface();
interFace.setVisible(true);
this.hide();
}//GEN-LAST:event_LogoutaddWorkerActionPerformed
private void genderWorkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genderWorkerActionPerformed
// TODO add your handling code here:
String[] gender = {"Male", "Female"};
}//GEN-LAST:event_genderWorkerActionPerformed
private void textNameWorkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNameWorkerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textNameWorkerActionPerformed
private void IDworkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IDworkerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_IDworkerActionPerformed
private void textPostWorkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPostWorkerActionPerformed
// TODO add your handling code here:
String[] post = {"Administrator", "Hotel Manager", "Assistant Hotel Manager", "Housekeeping Supervisor", "Front Desk Supervisor", "Supervisor of Guest Services", "Housekeeping"};
}//GEN-LAST:event_textPostWorkerActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewWorkerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewWorkerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewWorkerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewWorkerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewWorkerForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField IDworker;
private javax.swing.JButton LogoutaddWorker;
private javax.swing.JComboBox<String> genderWorker;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton nextbuttWorker;
private javax.swing.JTextField textCityWorker;
private javax.swing.JTextField textCountryWorker;
private javax.swing.JTextField textDateWorker;
private javax.swing.JTextField textEmailWorker;
private javax.swing.JTextField textLoginWorker;
private javax.swing.JTextField textNameWorker;
private javax.swing.JTextField textPassWorker;
private javax.swing.JTextField textPhoneWorker;
private javax.swing.JComboBox<String> textPostWorker;
private javax.swing.JTextField textSalaryWorker;
private javax.swing.JTextField textSurnameWorker;
// End of variables declaration//GEN-END:variables
}
|
package security.implementations;
import security.BlockCipher;
/**
* Fundamentals Of Security, Assignment 2
* Created by Jacob Dunk
*/
public class EmptyBlockCipher extends BlockCipher {
public EmptyBlockCipher(int blockSize) {
super(blockSize);
}
@Override
protected byte[] encrypt(byte[] block, byte[] previousEncryptedBlock) {
return block.clone();
}
@Override
protected byte[] decrypt(byte[] block, byte[] previousEncryptedBlock) {
return block.clone();
}
}
|
package com.podarbetweenus.Activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.podarbetweenus.BetweenUsConstant.Constant;
import com.podarbetweenus.Entity.LoginDetails;
import com.podarbetweenus.R;
import com.podarbetweenus.Services.DataFetchService;
import com.podarbetweenus.Utility.AppController;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Administrator on 10/3/2015.
*/
public class MedicalInformationActivity extends Activity implements View.OnClickListener{
//LayoutEntities
HeaderControler header;
LoginDetails login_Details;
DataFetchService dft;
//Button
Button btn_savemedical_info,btn_medicalcancel,btn_editmedical_info,btn_medicalnext;
//Linear Layout
LinearLayout lay_back_investment,ll_edit_medical_info,ll_save_medical_info;
//EditText
EditText ed_select_bloddgroup,ed_all_allergies,ed_health_info,ed_height,ed_weight,ed_regular_medication,ed_regular_medication_with_dosage,ed_any_impairment,
ed_exemption_from_activities;
//ProgressDialog
ProgressDialog progressDialog;
KeyListener variable;
String clt_id,msd_ID,usl_id,board_name,school_name,versionName,blood_group_id,all_allergies,health_info,height,weight,regular_medication,regular_medication_with_dosage,any_impairment,exemption_from_activities;
String MedicalInfoMethod_name = "GetMedicalInfo";
String methodName="GetParentInfoDropDown";
String updateMedicalInfoMethod_name = "UpdateMedicalInfo";
Context mcontext;
ArrayList<String> strings_blood_group = new ArrayList<String>();
String[] select_blood_group;
String TAG = "Medical Information";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.medicalinformation);
getIntentId();
findViews();
init();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getEdittextvariable();
//setEditText Disable
disableEditText();
AppController.editButtonClicked="false";
//Call Webservice for EmergencyContact Info
callWebserviceforMedicaltInfo(AppController.msd_ID);
}
private void disableEditText() {
ed_select_bloddgroup.setKeyListener(null);
ed_height.setKeyListener(null);
ed_health_info.setKeyListener(null);
ed_weight.setKeyListener(null);
ed_exemption_from_activities.setKeyListener(null);
ed_all_allergies.setKeyListener(null);
ed_any_impairment.setKeyListener(null);
ed_regular_medication_with_dosage.setKeyListener(null);
ed_regular_medication.setKeyListener(null);
}
private void getIntentId() {
Intent intent = getIntent();
board_name = intent.getStringExtra("board_name");
clt_id = intent.getStringExtra("clt_id");
msd_ID = intent.getStringExtra("msd_ID");
usl_id = intent.getStringExtra("usl_id");
school_name = intent.getStringExtra("School_name");
versionName = intent.getStringExtra("version_name");
AppController.versionName = versionName;
AppController.dropdownSelected = intent.getStringExtra("DropDownSelected");
AppController.school_name = school_name;
AppController.Board_name = board_name;
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
}
private void getEdittextvariable() {
variable= ed_select_bloddgroup.getKeyListener();
variable= ed_height.getKeyListener();
variable= ed_health_info.getKeyListener();
variable= ed_weight.getKeyListener();
variable= ed_exemption_from_activities.getKeyListener();
variable= ed_all_allergies.getKeyListener();
variable= ed_any_impairment.getKeyListener();
variable= ed_regular_medication_with_dosage.getKeyListener();
variable= ed_regular_medication.getKeyListener();
}
private void findViews() {
//Button
btn_medicalcancel = (Button) findViewById(R.id.btn_medicalcancel);
btn_editmedical_info = (Button) findViewById(R.id.btn_editmedical_info);
btn_medicalnext = (Button) findViewById(R.id.btn_medicalnext);
btn_savemedical_info = (Button) findViewById(R.id.btn_savemedical_info);
//Linear Layout
lay_back_investment = (LinearLayout) findViewById(R.id.lay_back_investment);
ll_edit_medical_info = (LinearLayout) findViewById(R.id.ll_edit_medical_info);
ll_save_medical_info = (LinearLayout) findViewById(R.id.ll_save_medical_info);
//EditText
ed_select_bloddgroup = (EditText) findViewById(R.id.ed_select_bloddgroup);
ed_all_allergies = (EditText) findViewById(R.id.ed_all_allergies);
ed_any_impairment = (EditText) findViewById(R.id.ed_any_impairment);
ed_exemption_from_activities = (EditText) findViewById(R.id.ed_exemption_from_activities);
ed_health_info = (EditText) findViewById(R.id.ed_health_info);
ed_height = (EditText) findViewById(R.id.ed_height);
ed_weight = (EditText) findViewById(R.id.ed_weight);
ed_regular_medication = (EditText) findViewById(R.id.ed_regular_medication);
ed_regular_medication_with_dosage = (EditText) findViewById(R.id.ed_regular_medication_with_dosage);
}
private void init() {
header = new HeaderControler(this,true,false,"Parent Information");
login_Details =new LoginDetails();
dft = new DataFetchService(this);
progressDialog = Constant.getProgressDialog(this);
btn_medicalcancel.setOnClickListener(this);
btn_medicalnext.setOnClickListener(this);
btn_savemedical_info.setOnClickListener(this);
btn_editmedical_info.setOnClickListener(this);
lay_back_investment.setOnClickListener(this);
ed_select_bloddgroup.setOnClickListener(this);
}
private void callWebserviceforMedicaltInfo(String msd_id) {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
dft.getparentInfo(msd_id, MedicalInfoMethod_name, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
login_Details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_Details.Status.equalsIgnoreCase("1")) {
setUIData();
} else if (login_Details.Status.equalsIgnoreCase("0")) {
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("ParentInfo", "ERROR.._---" + error.getCause());
}
});
}
private void setUIData() {
ed_select_bloddgroup.setText(login_Details.ParentInfoMedical.get(0).blg_name);
ed_all_allergies.setText(login_Details.ParentInfoMedical.get(0).hlt_Allergies);
ed_health_info.setText(login_Details.ParentInfoMedical.get(0).hlt_healthproblems);
ed_height.setText(login_Details.ParentInfoMedical.get(0).hlt_Height);
ed_weight.setText(login_Details.ParentInfoMedical.get(0).hlt_Weight);
ed_regular_medication.setText(login_Details.ParentInfoMedical.get(0).hlt_regmedications);
ed_regular_medication_with_dosage.setText(login_Details.ParentInfoMedical.get(0).hlt_regmeddosage);
ed_any_impairment.setText(login_Details.ParentInfoMedical.get(0).hlt_impairment);
ed_exemption_from_activities.setText(login_Details.ParentInfoMedical.get(0).hlt_expfromactivities);
blood_group_id = login_Details.ParentInfoMedical.get(0).blg_id;
AppController.blood_groupId = blood_group_id;
}
@Override
public void onClick(View v) {
if(v==btn_medicalcancel)
{
View view = this.getCurrentFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
AppController.editButtonClicked="false";
ll_edit_medical_info.setVisibility(View.VISIBLE);
ll_save_medical_info.setVisibility(View.GONE);
disableEditText();
//Call Webservice for EmergencyContact Info
callWebserviceforMedicaltInfo(AppController.msd_ID);
}
else if(v==btn_editmedical_info)
{
ll_save_medical_info.setVisibility(View.VISIBLE);
ll_edit_medical_info.setVisibility(View.GONE);
AppController.editButtonClicked="true";
//Enable Editiong
enableEditText();
}
else if(v==ed_select_bloddgroup){
if(AppController.editButtonClicked.equalsIgnoreCase("true")){
//Call Wenservice for blood group
callWebserviceForBloodGroup(mcontext);
}
}
else if(v==btn_savemedical_info){
saveInfo();
callWebserviceSaveMedicalInfo(AppController.msd_ID, AppController.blood_groupId,all_allergies, health_info,height,weight,regular_medication,regular_medication_with_dosage,any_impairment,exemption_from_activities);
}
else if(v==lay_back_investment)
{
Intent back = new Intent(MedicalInformationActivity.this,EmergencyContactActivity.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
/*if(AppController.SiblingActivity.equalsIgnoreCase("true"))
{
Intent back = new Intent(MedicalInformationActivity.this,Profile_Sibling.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
}
else {
Intent back = new Intent(MedicalInformationActivity.this,ProfileActivity.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.Board_name = board_name;
AppController.school_name = school_name;
back.putExtra("clt_id",AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
}*/
}
}
private void callWebserviceSaveMedicalInfo(String msd_ID,String blood_group_id,String all_allergies,String health_info,String height,String weight,String regular_medication,String regular_medication_with_dosage,String any_impairment
,String exemption_from_activities) {
if(!progressDialog.isShowing()) {
progressDialog.show();
}
dft.updateMedicalInfo(msd_ID, blood_group_id,all_allergies, health_info, height, weight, regular_medication, regular_medication_with_dosage, any_impairment, exemption_from_activities, updateMedicalInfoMethod_name, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
login_Details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_Details.Status.equalsIgnoreCase("1")) {
Constant.showOkPopup(MedicalInformationActivity.this, login_Details.StatusMsg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (AppController.SiblingActivity.equalsIgnoreCase("true")) {
Intent back = new Intent(MedicalInformationActivity.this, Profile_Sibling.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
// AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name", AppController.Board_name);
back.putExtra("School_name", AppController.school_name);
back.putExtra("version_name", AppController.versionName);
startActivity(back);
} else {
Intent back = new Intent(MedicalInformationActivity.this, ProfileActivity.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
// AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.Board_name = board_name;
AppController.school_name = school_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name", AppController.Board_name);
back.putExtra("School_name", AppController.school_name);
back.putExtra("version_name", AppController.versionName);
startActivity(back);
}
}
});
} else if (login_Details.Status.equalsIgnoreCase("0")) {
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("ParentInfo", "ERROR.._---" + error.getCause());
}
});
}
private void saveInfo() {
all_allergies = ed_all_allergies.getText().toString();
health_info = ed_health_info.getText().toString();
height = ed_height.getText().toString();
weight = ed_weight.getText().toString();
regular_medication = ed_regular_medication.getText().toString();
regular_medication_with_dosage = ed_regular_medication_with_dosage.getText().toString();
any_impairment = ed_any_impairment.getText().toString();
exemption_from_activities = ed_exemption_from_activities.getText().toString();
}
private void enableEditText() {
// ed_select_bloddgroup.setKeyListener(variable);
ed_height.setKeyListener(variable);
ed_health_info.setKeyListener(variable);
ed_weight.setKeyListener(variable);
ed_exemption_from_activities.setKeyListener(variable);
ed_all_allergies.setKeyListener(variable);
ed_any_impairment.setKeyListener(variable);
ed_regular_medication_with_dosage.setKeyListener(variable);
ed_regular_medication.setKeyListener(variable);
}
public void callWebserviceForBloodGroup(Context mcontext) {
if(!progressDialog.isShowing()) {
progressDialog.show();
}
dft.getCountryList(methodName, Request.Method.GET,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
login_Details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
strings_blood_group = new ArrayList<String>();
try {
for (int i = 0; i < login_Details.ParentInfoBloddGroup.size(); i++) {
strings_blood_group.add(login_Details.ParentInfoBloddGroup.get(i).blg_name);
select_blood_group = new String[strings_blood_group.size()];
select_blood_group = strings_blood_group.toArray(select_blood_group);
}
selectDropdown(select_blood_group);
} catch (Exception e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "" + volleyError);
/* Constant.showOkPopup(HomeActivity.this, volleyError.toString(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});*/
}
}, null);
}
private void selectDropdown(final String[] select_dropdownvalue) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select Blood Group");
final ListView select_list = (ListView) convertView.findViewById(R.id.select_list);
alertDialog.setItems(select_dropdownvalue, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
ed_select_bloddgroup.setText(select_dropdownvalue[item]);
String selectedvalue = select_dropdownvalue[item];
Log.e("Religion", selectedvalue);
blood_group_id = getID(selectedvalue);
AppController.blood_groupId = blood_group_id;
Log.e("blood_group_id", blood_group_id);
dialog.dismiss();
}
});
alertDialog.show();
}
private String getID(String selectedvalue) {
String id = "0";
for (int i = 0; i < login_Details.ParentInfoBloddGroup.size(); i++) {
if (login_Details.ParentInfoBloddGroup.get(i).blg_name.equalsIgnoreCase(selectedvalue)) {
id = login_Details.ParentInfoBloddGroup.get(i).blg_id;
}
} return id;
}
@Override
public void onBackPressed() {
/*if(AppController.SiblingActivity.equalsIgnoreCase("true"))
{
Intent back = new Intent(MedicalInformationActivity.this,Profile_Sibling.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
}
else {
Intent back = new Intent(MedicalInformationActivity.this,ProfileActivity.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.Board_name = board_name;
AppController.school_name = school_name;
back.putExtra("clt_id",AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
}*/
Intent back = new Intent(MedicalInformationActivity.this,EmergencyContactActivity.class);
AppController.OnBackpressed = "false";
AppController.editButtonClicked = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID",AppController.msd_ID);
back.putExtra("usl_id",AppController.usl_id);
back.putExtra("board_name",AppController.Board_name);
back.putExtra("School_name",AppController.school_name);
back.putExtra("version_name",AppController.versionName);
startActivity(back);
}
}
|
/*InFix to PostFix*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args)
{
CP sc =new CP();
int tt = sc.nextInt();
while (tt-- > 0) {
String s = sc.nextLine().trim();
System.out.println(infixToPostfix(s));
}
}
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String exp)
{
// initializing empty String for result
StringBuilder result = new StringBuilder();
// initializing empty stack
Stack<Character> stack = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
// If the scanned character is an operand, add it to output.
if (Character.isLetterOrDigit(c))
result.append(c);
// If the scanned character is an '(', push it to the stack.
else if (c == '(')
stack.push(c);
// If the scanned character is an ')', pop and output from the stack
// until an '(' is encountered.
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result.append(stack.pop());
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression"; // invalid expression
else
stack.pop();
}
else // an operator is encountered
{
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){
if(stack.peek() == '(')
return "Invalid Expression";
result.append(stack.pop());
}
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result.append(stack.pop());
}
return result.toString();
}
/*****************************************************************************/
static class CP
{
BufferedReader bufferedReader;
StringTokenizer stringTokenizer;
public CP() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
int nextInt() {
return Integer.parseInt(NNNN());
}
long nextLong() {
return Long.parseLong(NNNN());
}
double nextDouble() {
return Double.parseDouble(NNNN());
}
String NNNN() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
String nextLine() {
String spl = "";
try {
spl = bufferedReader.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return spl;
}
}
/*****************************************************************************/
} |
package com.liemily.tradesimulation.account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.math.BigDecimal;
/**
* Created by Emily Li on 12/08/2017.
*/
public interface AccountRepository extends JpaRepository<Account, String> {
@Modifying
@Query("UPDATE Account SET credits = credits - ?2 WHERE username = ?1 AND credits - ?2 >= 0")
int removeCredits(String username, BigDecimal credits);
}
|
package valatava.lab.warehouse.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import valatava.lab.warehouse.model.Customer;
/**
* Spring Data JPA repository for the {@link Customer} entity.
*
* @author Yuriy Govorushkin
*/
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
|
package Day15;
import java.util.ArrayList;
import java.util.List;
public class Day15_2 {
public static void main(String[] args) {
//컬렉션 프레임워크 ㅣ 메모리 관리 클래스 집합
//컬렉션 : 수집
//프레임워크 : 미리 만들어진 프로그램
//1.List 컬렉션
//1. ArrayList, 2. Vector , 3. LinkedList
//1. 배열과 차이점 : 배열[고정메모리] / list[가변메모리]
// 배열 : int[] 배열명 = new int[0]
//2. 인덱스 사용 : 저장되는 순서 [0번부터 시작]
//3. 추가, 삭제시 : 인덱스 자동 변경
//4. 자주 사용되는 메소드
//1. 리스트명.add("객체명")
//2. 리스트명.get(인덱스번호)
//3. 리스트명.remove(인덱스번호)
//4. 리스트명.size()
//5. 리스트명.clear
//5. ArrayList vs Vector :
// ex1) ArrayList 클래스
//1. 선언
List<String> list = new ArrayList<>();
ArrayList <String> list = new ArrayList<>();
//인터페이스/클래스명 <리스트에 들어가는 클래스명> 리스트명 = new ArrayList<생략가능>();
//2. 메소드
list.add("java"); //리스트에 객체 넣기
list.add("123"); //add하고싶은 클래스를 넣는다 //리스트에 선언된 클래스만 넣기 가능
list.add("python");
list.add("database");
list.add("c++"); //list에 추가할때는 add를 사용한다. - 쌤왈
//2. 리스트에 객체 호출하기
System.out.println(list.get(0));
//3. 리스트 삭제하기
list.remove(0);
System.out.println(list.get(0));
//4. 리스트내 객체수
System.out.println(list.size());
//5. 반복문 활용1
for(int i = 0; i<list.size();i++) {
System.err.println(list.get(i));
}
//6. 반복문 활용2
for(String temp : list) {
System.out.println(temp);
}
//7. 객체 모두 삭제
list.clear(); //모두가 삭제가 됨.
//2. Set 컬렉션
//3. Map
}
}
|
package HomeWork;
import java.util.Arrays;
public class day02 {
//实现方法 compareTo
public static void main(String[] args) {
String s1="hello";
String s2="helo";
System.out.println(s1.compareTo(s2));
System.out.println(MycompareTo(s1,s2));
}
public static int MycompareTo(String s1, String s2) {
char[] ch1=s1.toCharArray();
char[] ch2=s2.toCharArray();
int n=ch1.length>ch2.length?ch1.length:ch2.length;
for(int i=0;i<n;++i){
if(ch1[i]==ch2[i])
continue;
if(ch1[i]!=ch2[i])
return ch1[i]-ch2[i];
}
return 0;
}
//实现方法 contains, 能够判定字符串中是否包含子串
// public static void main(String[] args) {
// String s1="hello";
// System.out.println(s1.contains("ea"));
// System.out.println(Mycontains(s1,"el"));
// System.out.println(Mycontains(s1,"ea"));
// }
//
// public static boolean Mycontains(String s1, String el) {
// if(s1.indexOf(el)>=0)
// return true;
// else
// return false;
// }
//实现方法 indexOf
// public static void main(String[] args) {
// String s1="hello";
// int n=s1.indexOf("lo");
// System.out.println(n);
// int n1=MyindexOf(s1,"lo");
// System.out.println(n1);
// }
// public static int MyindexOf(String s1, String el) {
// char[] ch1=s1.toCharArray();
// char[] ch2=el.toCharArray();
// if(ch1.length<ch2.length)
// return -1;
// for(int i=0;i<ch1.length;++i){//s1字符串
// int count=0;
// for(int j=0;j<ch2.length;++j) {//el字符串
// if (ch1[i+count] == ch2[j])//匹配上一个进行计数,从零开始
// count++;
// }
// if(count==ch2.length)
// return i;
// }
// return -1;
// }
//实现方法 replace
// public static void main(String[] args) {
// String s1="hello";
// String s2=s1.replace("he","Ah");
// System.out.println(s2);
// String s3=Myreplace(s2,"he","Ah");
// System.out.println(s3);
// }
// public static String Myreplace(String s2, String he, String ah) {
// StringBuffer stringBuffer=new StringBuffer(s2);
// if(stringBuffer.indexOf(he)>=0){
// int start=stringBuffer.indexOf(he);
// stringBuffer.delete(start,he.length()+1);
// stringBuffer.insert(start,ah);
// }
// String string=stringBuffer.substring(0);
// return string;
// }
//实现方法 split
// public static void main(String[] args) {
// String s1="helleo";
// String[] s2=s1.split("el");
// String[] s3=MySplit(s1,"el");
// System.out.println(s1);
// System.out.println(Arrays.toString(s2));
// System.out.println(Arrays.toString(s3));
// }
// public static String[] MySplit(String s1,String str){
// int n=0;
// String[] strings=new String[s1.length()];
// StringBuffer stringBuffer=new StringBuffer(s1);
// for (int i=0;i<strings.length-1;++i) {
// if (stringBuffer.indexOf(str)>=0) {
// int start=stringBuffer.indexOf(str);
// stringBuffer.delete(start,str.length()+start);
// strings[i]=stringBuffer.substring(n,start);
// strings[i+1]=stringBuffer.substring(start);
// n=str.length()+start-1;
// continue;
// }
// String[] st1=new String[n];
// for(int j=0;j<st1.length;++j){
// st1[j]=strings[j];
// }
// return st1;
// }
// return strings;
// }
// public static void main(String[] args) {
// String s1="abc"+"def";//1
// String s2=new String(s1);//2
// String s3=s2.substring(1,3);
// System.out.println(s2);
// System.out.println(s3);
// if(s1.equals(s2))//3
// System.out.println(".equals succeeded");//4
// if(s1==s2)//5
// System.out.println("==succeeded");//
// }
// public static boolean isAdmin(String userId){
// System.out.println(userId.toLowerCase());
// return userId.toLowerCase()=="admin";
// }
// public static void main(String[] args){
// System.out.println(isAdmin("Admin"));
// }
// String str = new String("good");
// char[ ] ch = { 'a' , 'b' , 'c' };
// public static void main(String args[]){
// day02 ex = new day02();
// ex.change(ex.str,ex.ch);
// System.out.print(ex.str + " and ");
// System.out.print(ex.ch);
// }
// public void change(String str,char ch[ ]){
// str = "test ok";
// ch[0] = 'g';
// }
//目标值不存在于数组中,返回它将会被按顺序插入的位置。
// public static void main(String[] args) {
// int[] ar=new int[]{1,3,5,6};
// int n=2;
// int a=searchInsert(ar,n);
// System.out.println(a);
// }
// public static int searchInsert(int[] nums, int target) {
// int lift=0;
// int right=nums.length-1;
// int mid=0;
// if(nums[right]<target){
// return right+1;
// }
// if(nums[lift]>=target){
// return lift;
// }
// while(lift<right){
// mid=(lift+right)/2;
// if(nums[mid]==target){
// return mid;
// }
// if(nums[mid]>target){
// right=mid;
// }
// if(nums[mid]<target){
// lift=mid+1;
// }
// }
// return lift;
// }
// public static void main(String[] args) {
// int[] nums={0};
// int val=0;
// int n=removeElement(nums,val);
// System.out.println(n);
// }
// public static int removeElement(int[] nums, int val) {
// int lift=0;
// int right=nums.length-1;
// while(lift<right){
// while(lift<right && nums[lift]!=val){
// lift++;
// }
// while(lift<right && nums[right]==val){
// right--;
// }
// int temp=nums[lift];
// nums[lift]=nums[right];
// nums[right]=temp;
// }
// if(lift==right && nums[lift]!=val)
// lift++;
// return lift;
// }
}
|
/**
* Class MyEnglish3 extends Homework3
*
* @author C. Thurston
* @version 5/7/2014
*/
public class MyScience extends Homework
{
MyScience()
{
super();
}
public void createAssignment(int pages)
{
setPagesRead(pages);
setTypeHomework("Science");
}
public String toString()
{
return getTypeHomework() + " - must read " + getPagesRead() + " pages.";
}
} |
package com.java8.features;
import java.util.Hashtable;
@FunctionalInterface
public interface AA {
public void add(int a, int b);
public default int mul(int a, int b) {
return a * b;
}
public default int go(int a, int b) {
return a * b;
}
public static int statM(int a, int b) {
return a * b;
}
public static int ok(int a, int b) {
return a * b;
}
public static void main(String[] args) {
Hashtable<String, Integer> hs = new Hashtable();
hs.put("BBBBBBBBBBBB", null);
hs.put("AAA", 10);
System.out.println(hs);
}
}
|
/** ****************************************************************************
* Copyright (c) The Spray Project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spray Dev Team - initial API and implementation
**************************************************************************** */
package org.eclipselabs.spray.xtext.ui.hover;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.xtext.common.types.JvmGenericType;
import org.eclipse.xtext.common.types.JvmType;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.eclipse.xtext.common.types.access.jdt.IJavaProjectProvider;
import org.eclipse.xtext.ui.editor.hover.html.DefaultEObjectHoverProvider;
import org.eclipselabs.spray.shapes.ConnectionDefinition;
import org.eclipselabs.spray.shapes.ShapeDefinition;
import org.eclipselabs.spray.shapes.ui.hover.ImageResourceVisitor;
import javax.inject.Inject;
public class SprayEObjectHoverProvider extends DefaultEObjectHoverProvider {
private String typeKey = "Other";
private Map<String, IInformationControlCreator> hoverControlCreators = new HashMap<String, IInformationControlCreator>();
@Inject
private IJavaProjectProvider javaProjectProvider;
@Inject
private ImageResourceVisitor imageResourceVisitor;
@Override
public String getDocumentation(EObject o) {
String shapeName = null;
if (o instanceof JvmGenericType && hasExpectedShapeSuperType((JvmGenericType) o)) {
JvmGenericType type = (JvmGenericType) o;
shapeName = getShapeName(shapeName, type);
} else if (o instanceof ShapeDefinition) {
shapeName = ((ShapeDefinition) o).getName();
} else if (o instanceof ConnectionDefinition) {
shapeName = ((ConnectionDefinition) o).getName();
} else {
}
if (shapeName != null) {
typeKey = "Shape";
IJavaProject javaProject = javaProjectProvider.getJavaProject(o.eResource().getResourceSet());
if (javaProject != null) {
try {
imageResourceVisitor.setShapeName(shapeName);
javaProject.getProject().accept(imageResourceVisitor);
String imagePath = imageResourceVisitor.getImagePath();
if (imagePath != null && imagePath.endsWith(".png")) {
String alternativeText = "Shapes preview for " + shapeName;
return "<br /><br /><img src=\"" + imagePath + "\" alt=\"" + alternativeText + "\" />";
}
} catch (CoreException e) {
e.printStackTrace();
}
}
} else {
typeKey = "Other";
}
return super.getDocumentation(o);
}
private String getShapeName(String shapeName, JvmType type) {
String name = type.getQualifiedName();
int index = name.lastIndexOf(".");
if (index > 0 && index + 1 < name.length()) {
shapeName = name.substring(index + 1);
}
return shapeName;
}
private boolean hasExpectedShapeSuperType(JvmGenericType type) {
for (JvmTypeReference superType : type.getSuperTypes()) {
if ("org.eclipselabs.spray.runtime.graphiti.shape.DefaultSprayShape".equals(superType.getQualifiedName()) || "org.eclipselabs.spray.runtime.graphiti.shape.DefaultSprayConnection".equals(superType.getQualifiedName())) {
return true;
}
}
return false;
}
@Override
public IInformationControlCreator getHoverControlCreator() {
if ("Shape".equals(typeKey)) {
if (hoverControlCreators.get(typeKey) == null) {
hoverControlCreators.put(typeKey, new SprayHoverControlCreator(this, getInformationPresenterControlCreator()));
}
} else {
hoverControlCreators.put(typeKey, super.getHoverControlCreator());
}
IInformationControlCreator creator = hoverControlCreators.get(typeKey);
typeKey = "Other";
return creator;
}
@Override
public IInformationControlCreatorProvider getHoverInfo(final EObject object, final ITextViewer viewer, final IRegion region) {
return new IInformationControlCreatorProvider() {
public IInformationControlCreator getHoverControlCreator() {
return SprayEObjectHoverProvider.this.getHoverControlCreator();
}
public Object getInfo() {
return getHoverInfo(object, region, null);
}
};
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.util;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.hibernate.engine.spi.SessionImplementor;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.interfaces.RoomAvailabilityInterface;
import org.unitime.timetable.model.dao._RootDAO;
/**
* @author Tomas Muller
*/
public class BlobRoomAvailabilityService extends RoomAvailabilityService {
private static Log sLog = LogFactory.getLog(RoomAvailabilityInterface.class);
private String iRequestSql = ApplicationProperty.BlobRoomAvailabilityRequestSQL.value();
private String iResponseSql = ApplicationProperty.BlobRoomAvailabilityResponseSQL.value();
protected void sendRequest(Document request) throws IOException {
try {
StringWriter writer = new StringWriter();
(new XMLWriter(writer,OutputFormat.createPrettyPrint())).write(request);
writer.flush(); writer.close();
SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
Connection connection = session.getJdbcConnectionAccess().obtainConnection();
try {
CallableStatement call = connection.prepareCall(iRequestSql);
call.setString(1, writer.getBuffer().toString());
call.execute();
call.close();
} finally {
session.getJdbcConnectionAccess().releaseConnection(connection);
}
} catch (Exception e) {
sLog.error("Unable to send request: "+e.getMessage(),e);
} finally {
_RootDAO.closeCurrentThreadSessions();
}
}
protected Document receiveResponse() throws IOException, DocumentException {
try {
SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
Connection connection = session.getJdbcConnectionAccess().obtainConnection();
String response = null;
try {
CallableStatement call = connection.prepareCall(iResponseSql);
call.registerOutParameter(1, java.sql.Types.CLOB);
call.execute();
response = call.getString(1);
call.close();
} finally {
session.getJdbcConnectionAccess().releaseConnection(connection);
}
if (response==null || response.length()==0) return null;
StringReader reader = new StringReader(response);
Document document = (new SAXReader()).read(reader);
reader.close();
return document;
} catch (Exception e) {
sLog.error("Unable to receive response: "+e.getMessage(),e);
return null;
} finally {
_RootDAO.closeCurrentThreadSessions();
}
}
}
|
package eu.rethink.globalregistry;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import eu.rethink.globalregistry.configuration.Config;
import eu.rethink.globalregistry.dht.DHTManager;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
/**
* Main class for GlobalRegistry daemon
*
* @date 06.04.2017
* @version 3
* @author Sebastian Göndör, Parth Singh
*/
@SpringBootApplication
@EnableScheduling
public class GlobalRegistryServer implements Daemon
{
private static Logger LOGGER;
public static void main(String[] args)
{
System.out.println("Initializing GlobalRegistry");
Config config = Config.getInstance();
Options options = new Options();
Option helpOption = Option.builder("h")
.longOpt("help")
.desc("displays help on cli parameters")
.build();
//Option reconnectIntervalOption = Option.builder("r")
// .longOpt("reconnect_interval")
// .desc("sets the reconnect interval in hours. 0 disables reconnect [" + config.getReconnectInterval() + "]")
// .hasArg()
// .build();
Option portRESTOption = Option.builder("p")
.longOpt("port_rest")
.desc("sets the port for the REST interface [" + config.getPortREST() + "]")
.hasArg()
.build();
Option networkInterfaceOption = Option.builder("n")
.longOpt("network_interface")
.desc("sets the network interface [" + config.getNetworkInterface() + "]")
.hasArg()
.build();
Option logPathOption = Option.builder("l")
.longOpt("log_path")
.desc("sets the directory for the log files [" + config.getLogPath() + "]")
.hasArg()
.build();
Option connectNodeOption = Option.builder("c")
.longOpt("connect_node")
.desc("sets the GReg node to connect to [" + config.getConnectNode() + "]")
.hasArg()
.build();
//options.addOption(reconnectIntervalOption);
options.addOption(helpOption);
options.addOption(portRESTOption);
options.addOption(networkInterfaceOption);
options.addOption(logPathOption);
options.addOption(connectNodeOption);
// parse command line parameters
CommandLineParser parser = new DefaultParser();
try
{
CommandLine cmd = parser.parse(options, args);
if(cmd.hasOption("h"))
{
HelpFormatter formater = new HelpFormatter();
formater.printHelp("GReg help", options);
System.exit(0);
}
//if(cmd.hasOption("r"))
//{
// config.setReconnectInterval(Integer.parseInt(cmd.getOptionValue("r"))); // TODO check for valid values
//}
if(cmd.hasOption("p"))
{
config.setPortREST(Integer.parseInt(cmd.getOptionValue("p"))); // TODO check for valid values
}
if(cmd.hasOption("n"))
{
config.setNetworkInterface(cmd.getOptionValue("n")); // TODO check for valid values
}
if(cmd.hasOption("l"))
{
config.setLogPath(cmd.getOptionValue("l")); // TODO check for valid values
}
if(cmd.hasOption("c"))
{
config.setConnectNode(cmd.getOptionValue("c")); // TODO check for valid values
}
System.out.println("-----Configuration: ");
//System.out.println("reconnectInterval: " + config.getReconnectInterval());
System.out.println("connectNode: " + config.getConnectNode());
System.out.println("portREST: " + config.getPortREST());
System.out.println("networkInterface: " + config.getNetworkInterface());
System.out.println("logPath: " + config.getLogPath() + "\n-----");
// setup logging
System.setProperty("loginfofile", config.getLogPath() + "log-info.log");
System.setProperty("logdebugfile", config.getLogPath() + "log-debug.log");
LOGGER = LoggerFactory.getLogger(GlobalRegistryServer.class);
LOGGER.info(config.getProductName() + " " + config.getVersionName() + " " + config.getVersionCode());
LOGGER.info("Build #" + config.getVersionNumber() + " (" + config.getVersionDate() + ")\n");
}
catch (ParseException e)
{
System.out.println("Wrong parameter. Error: " + e.getMessage());
}
try
{
LOGGER.info("initializing DHT... ");
DHTManager.getInstance().initDHT();
LOGGER.info("DHT initialized successfully");
LOGGER.info("initializing Global Registry server... ");
// Registering the port for the REST interface to listen on
System.getProperties().put("server.port", config.getPortREST());
LOGGER.info("REST interface listening on " + config.getPortREST());
SpringApplication.run(GlobalRegistryServer.class, args);
}
catch (Exception e)
{
LOGGER.info("failed!");
e.printStackTrace();
}
}
// 5 minute delay, then every 12 hours
//@Scheduled(initialDelay=5 * 1000, fixedRate=30 * 1000)
@Scheduled(initialDelay=2 * 60 * 1000, fixedRate=1 * 60 * 60 * 1000)
protected void reconnect()
{
LOGGER.info("running reconnect functionality...");
try
{
DHTManager.getInstance().connectToConnectNode();
}
catch (Exception e)
{
LOGGER.info("reconnect functionality failed!");
e.printStackTrace();
}
}
@Override
public void init(DaemonContext daemonContext) throws DaemonInitException, Exception
{
//System.out.println("deamon: init()");
String arguments[] = daemonContext.getArguments();
System.out.println(arguments);
GlobalRegistryServer.main(arguments);
}
@Override
public void start() throws Exception
{
//System.out.println("deamon: start()");
}
@Override
public void stop() throws Exception
{
//System.out.println("deamon: exception()");
}
@Override
public void destroy()
{
//System.out.println("deamon: destroy()");
}
} |
package com.voksel.electric.pc.component;
/**
* Created by Edsarp on 7/3/2016.
*/
public interface MenuTreeItem {
String getId();
String getUrl();
String getMenuName();
boolean isProgram();
String getParentId();
}
|
package com.yinghai.a24divine_user.module.shop.shopcar.submit;
import com.example.fansonlib.base.BaseModel;
import com.example.fansonlib.http.HttpResponseCallback;
import com.example.fansonlib.http.HttpUtils;
import com.example.fansonlib.utils.SharePreferenceHelper;
import com.yinghai.a24divine_user.bean.NoDataBean;
import com.yinghai.a24divine_user.bean.SubmitShopCarBean;
import com.yinghai.a24divine_user.constant.ConHttp;
import com.yinghai.a24divine_user.constant.ConResultCode;
import com.yinghai.a24divine_user.constant.ConstantPreference;
import com.yinghai.a24divine_user.http.ApiFactoryImpl;
import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil;
import java.util.HashMap;
import java.util.Map;
import io.reactivex.subscribers.ResourceSubscriber;
/**
* @author Created by:fanson
* Created Time: 2017/11/13 16:31
* Describe:提交购物车的M层
*/
public class SubmitShopCarModel extends BaseModel implements ContractSubmitShopCar.ISubmitModel {
private ISubmitCallback mSubmitCallback;
private IDeleteCallback mDeleteCallback;
@Override
public void submitShopCar(String carIds, String amounts, int addressId, ISubmitCallback callback) {
mSubmitCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String, Object> maps = new HashMap<>(6);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, 0));
maps.put("carIds", carIds);
maps.put("addressId", addressId);
maps.put("quantities", amounts);
maps.put("apiSendTime", time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
//TODO 底层封装有问题,有时会不触发,所以这里没有使用统一的方式
addSubscrebe(new ApiFactoryImpl().createApi(ConHttp.SUBMIT_SHOP_CAR, maps), new ResourceSubscriber<SubmitShopCarBean>() {
@Override
public void onNext(SubmitShopCarBean bean) {
if (mSubmitCallback == null) {
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mSubmitCallback.onSubmitSuccess(bean);
break;
case ConResultCode.NOT_REGISTER:
mSubmitCallback.onSubmitFailure(bean.getMsg());
break;
default:
mSubmitCallback.handlerResultCode(bean.getCode());
break;
}
}
@Override
public void onError(Throwable t) {
if (mSubmitCallback!=null){
mSubmitCallback.onSubmitFailure(t.getMessage());
}
}
@Override
public void onComplete() {
}
});
}
@Override
public void deleteShopCar(final int carId, IDeleteCallback callback) {
mDeleteCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String, Object> maps = new HashMap<>(4);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, 0));
maps.put("carId", carId);
maps.put("apiSendTime", time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
HttpUtils.getHttpUtils().post(ConHttp.DELETE_SHOP_CAR, maps, new HttpResponseCallback<NoDataBean>() {
@Override
public void onSuccess(NoDataBean bean) {
if (mDeleteCallback == null) {
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mDeleteCallback.onDeleteSuccess(carId, bean);
break;
default:
mDeleteCallback.handlerResultCode(bean.getCode());
break;
}
}
@Override
public void onFailure(String errorMsg) {
if (mDeleteCallback != null) {
mDeleteCallback.onDeleteFailure(errorMsg);
}
}
});
}
@Override
public void edtiShopCar(int carId, IEditCallback callback) {
// String time = String.valueOf(System.currentTimeMillis());
// Map<String,Object> maps = new HashMap<>(5);
// maps.put("userId", 5);
// maps.put("carId",carId);
// maps.put("Authorization", "46541231test");
// maps.put("apiSendTime", String.valueOf(System.currentTimeMillis()));
// maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
// HttpUtils.getHttpUtils().post(ConHttp.DELETE_SHOP_CAR,maps, new HttpResponseCallback<NoDataBean>() {
// @Override
// public void onSuccess(NoDataBean bean) {
// if (mDeleteCallback ==null){
// return;
// }
// switch (bean.getCode()) {
// case ConResultCode.SUCCESS:
// mDeleteCallback.onDeleteSuccess(carId, bean);
// break;
// default:
// mDeleteCallback.handlerResultCode(bean.getCode());
// break;
// }
// }
//
// @Override
// public void onFailure(String errorMsg) {
// if (mDeleteCallback!=null){
// mDeleteCallback.onDeleteFailure(errorMsg);
// }
// }
// });
}
@Override
public void onDestroy() {
super.onDestroy();
mSubmitCallback = null;
mDeleteCallback = null;
}
}
|
package pl.pkrysztofiak.skeleton2.view.panel.toolbar;
import pl.pkrysztofiak.skeleton2.view.panel.PanelPresenter;
public class PanelToolbarPresenter {
public PanelToolbarPresenter(PanelPresenter panelPresenter) {
}
}
|
package com.heartmarket.model.dao;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.heartmarket.model.dto.Mail;
import com.heartmarket.model.dto.User;
@Repository
public interface MailRepository extends JpaRepository<Mail, Integer> {
List<Mail> findAllByTradeTradeNo(int tradeNo);
Mail findBySenderUserNo(int userNo);
Mail findBySenderUserNoAndMailNo(int userNo,int mailNo);
Mail findByReceiverUserNo(int userNo);
List<Mail> findAllByReceiverUserNoAndReadDelAndReadDateIsNull(int userNo,int readDel);
List<Mail> findAllByReceiverUserNoAndReadDelAndReadDateIsNotNull(int userNo,int readDel);
Mail findByReceiverUserNoAndMailNo(int userNo,int mailNo);
List<Mail> findAllBySenderUserNoAndSendDel(int userNo,int sendDel);
List<Mail> findAllByReceiverUserNoAndReadDel(int userNo,int readDel);
// 거래 완료 대상 찾기
@Query("select distinct m from Mail m where m.trade.tradeNo=?1 and m.receiver.userNo=?2 group by m.sender.userNo")
List<Mail> findDistinctBySenderNoAndTradeNo(int tradeNo, int userNo);
//page 기능
Page<Mail> findAllBySenderUserNoAndSendDel(int userNo,int sendDel,Pageable req);
Page<Mail> findAllByReceiverUserNoAndReadDel(int userNo,int readDel, Pageable req);
Page<Mail> findAllByReceiverUserNoAndReadDelAndReadDateIsNull(int userNo,int readDel,Pageable req);
Page<Mail> findAllByReceiverUserNoAndReadDelAndReadDateIsNotNull(int userNo,int readDel,Pageable req);
}
|
package inheritance.abstractinterface;
public abstract class Shape {
protected double x,y;
public Shape(double x, double y) {
this.x = x;
this.y = y;
}
public void drawCenter() {
System.out.println("중심좌표(x,y) = " +x +" , " + y);
}
public abstract void draw(); // 추상클래스 끝에 ; 로 마무리지어줌
public static void main(String[] args) {
// TODO Auto-generated method stub
//Shape s = new Shape(3.4,1,2); 추상클래스는 객체화될수없다.
}
}
|
/**
* Copyright CopperMobile
*
* */
package com.atn.app.utils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.support.v7.app.ActionBarActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.Toast;
import com.atn.app.R;
import com.atn.app.datamodels.ReviewTag;
import com.atn.app.provider.Atn;
/***
* Utility class for
* */
public class UiUtil {
/**
* show toast message
*
* @param context
* application context
* @param msg
* toast message.
* */
public static void showToast(Context context, String msg) {
if(context==null) return ;
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* show toast message
*
* @param context
* application context
* @param msg
* toast message resourse id.
* */
public static void showToast(Context context, int regId) {
if(regId!=0)
showToast(context, context.getResources().getString(regId));
}
public static boolean showToastIfTrue(Context context, int regId,
boolean condition) {
if (condition) {
showToast(context, regId);
}
return condition;
}
private static final int[] RES_IDS_ACTION_BAR_SIZE = { R.attr.actionBarSize };
/** Calculates the Action Bar height in pixels. */
public static int calculateActionBarSize(Context context) {
if (context == null) {
return 0;
}
Resources.Theme curTheme = context.getTheme();
if (curTheme == null) {
return 0;
}
TypedArray att = curTheme
.obtainStyledAttributes(RES_IDS_ACTION_BAR_SIZE);
if (att == null) {
return 0;
}
float size = att.getDimension(0, 0);
att.recycle();
return (int) size;
}
public static int setColorAlpha(int color, float alpha) {
int alpha_int = Math.min(Math.max((int) (alpha * 255.0f), 0), 255);
return Color.argb(alpha_int, Color.red(color), Color.green(color),
Color.blue(color));
}
public static int scaleColor(int color, float factor, boolean scaleAlpha) {
return Color.argb(
scaleAlpha ? (Math.round(Color.alpha(color) * factor)) : Color
.alpha(color), Math.round(Color.red(color) * factor),
Math.round(Color.green(color) * factor), Math.round(Color
.blue(color) * factor));
}
public static boolean hasActionBar(ActionBarActivity activity) {
return activity.getSupportActionBar() != null;
}
//cell height
public static int mCellHeight = 0;
/*
* All Screen big photos size will be 40 % of total height of screen.
* calculate once if not calculated.
*
* ***/
public static int getLoopPhotoSize(Activity context) {
if(mCellHeight==0){
final DisplayMetrics displayMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mCellHeight = (displayMetrics.heightPixels*40/100);
}
return mCellHeight;
}
/**
* Here apply color filter on imageview
* */
public static void makeImageViewBlackAndWhite(ImageView iv) {
float brightness = -10f;// (float)(200 - 255);
float[] colorMatrix = { 0.33f, 0.33f, 0.33f, 0, brightness, // red
0.33f, 0.33f, 0.33f, 0, brightness, // green
0.33f, 0.33f, 0.33f, 0, brightness, // blue
0, 0, 0, 1, 0 // alpha
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
//return screen width in dpi only for foursqare photo url
public static int getScreenWidth(Activity context) {
final DisplayMetrics displayMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.densityDpi;
}
public static int getPixelScreenWidth(Activity context) {
final DisplayMetrics displayMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
/**
* Appned Social name and user name with two different font
* **/
public static Spannable getSocialTitle(Context context,int titleResId,String name) {
if(context==null) return null;
//Typeface titleFont = TypefaceUtils.getTypeface(context, TypefaceUtils.ROBOTO_MEDIUM);
String title = context.getResources().getString(titleResId);
SpannableStringBuilder span = new SpannableStringBuilder(title+" "+name);
span.setSpan (new ForegroundColorSpan(Color.BLACK),0,title.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
span.setSpan (new ForegroundColorSpan(Color.GRAY), title.length()+1, span.length() ,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
span.setSpan (new StyleSpan(android.graphics.Typeface.BOLD),0,title.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
span.setSpan (new StyleSpan(android.graphics.Typeface.ITALIC), title.length()+1, span.length() ,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
return span;
}
//show alert dialog with title and message
/*
* @params activity activity on which dialog will appear
* @oarams title
* **/
public static void showAlertDialog(Activity activity, int title,
int message) {
showAlertDialog(activity, title == 0 ? null : activity.getResources()
.getString(title), activity.getResources().getString(message));
}
//show alert dialog with title and message
public static void showAlertDialog(Activity activity,
String title, String message) {
AlertDialog.Builder errorAlertDialog = new AlertDialog.Builder(activity);
if(!TextUtils.isEmpty(title))
errorAlertDialog.setTitle(title);
else
errorAlertDialog.setTitle(R.string.app_name);
errorAlertDialog.setMessage(message);
errorAlertDialog.setCancelable(true);
errorAlertDialog.setPositiveButton(activity.getResources().getString(R.string.dialog_button_dismiss),null);
errorAlertDialog.show();
}
// /show dialog with text
public static void showAlertDialog(Activity activity,
String message) {
showAlertDialog(activity,null,message);
}
public static void showAlertDialog(Activity activity, int message) {
showAlertDialog(activity,0,message);
}
public static void showAlertDialog(Activity activity,
Exception ex) {
String message = ex.getLocalizedMessage();
if(TextUtils.isEmpty(message))
message = ex.getLocalizedMessage();
if(TextUtils.isEmpty(message))
message = "Unknow error!";
showAlertDialog(activity,null,message);
}
//return review text
public static String getReviewCountText(int count){
if (count <= 1) {
return count+" REVIEW";
} else {
return count+" REVIEWS";
}
}
/**
* Evaluate rating if rating between x.0 to x.05 then rating will be x.5
* and if rating between x.6 to x.9 then rating will be x+1;
* **/
public static float calculateRating(float rating) {
if(rating==0) {
return 0;
}
DecimalFormat df = new DecimalFormat("#.#");
rating = Float.valueOf(df.format(rating));
float precision = (float) (rating-Math.floor(rating));
if(precision==0.0f) {
return rating;
}
if(precision<=0.5) {
rating = (float) (Math.floor(rating)+0.5f);
} else {
rating = (float) (Math.floor(rating)+1.0f);
}
return rating;
}
/***
* Return Top Two Tags comma seperated
* @param venueId foursquare venue id
* @param context app context
* */
public static String getTopTwoTags(Context context,String venueId) {
StringBuilder builder = new StringBuilder();
ArrayList<ReviewTag> list = Atn.ReviewTable.getVenueTwoReviewTag(context, venueId);
for (ReviewTag reviewTag : list) {
builder.append(reviewTag.getName());
builder.append(", ");
}
if(builder.length()>0) {
//1 for space
builder.deleteCharAt(builder.length()-2);
}
return builder.toString().trim();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package co.th.aten.hospital.dao;
import co.th.aten.hospital.model.BreedModel;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
/**
*
* @author Atenpunk
*/
public class JdbcBreedDao implements BreedDao {
private final Log logger = LogFactory.getLog(getClass());
private SimpleJdbcTemplate simpleJdbcTemplate;
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
public List<BreedModel> getBreedListOrderByEngName(int typeId) {
try {
String sqlId = "";
if (typeId != -1) {
sqlId = " Where type_id = "+typeId+" ";
}
String sql = " select breed_id, breed_eng_name, breed_thai_name, type_id "
+ " from pet_breed " + sqlId + " order by breed_eng_name ";
ParameterizedRowMapper<BreedModel> mapper = new ParameterizedRowMapper<BreedModel>() {
@Override
public BreedModel mapRow(ResultSet rs, int arg1) throws SQLException {
BreedModel model = new BreedModel();
model.setBreedId(rs.getInt("breed_id"));
model.setEngName(rs.getString("breed_eng_name"));
model.setThaiName(rs.getString("breed_thai_name"));
model.setTypeId(rs.getInt("type_id"));
return model;
}
};
return this.simpleJdbcTemplate.query(sql, mapper);
} catch (Exception e) {
logger.info("" + e);
e.printStackTrace();
return null;
}
}
}
|
package venus.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
public class SetCharacterEncodingFilter implements Filter {
private static Logger log = Logger.getLogger(SetCharacterEncodingFilter.class);
private String default_encoding = "utf-8";
public void init(FilterConfig config) throws ServletException {
String encoding = config.getInitParameter("encoding");
if (encoding != null) {
log.info("using encoding : " + encoding);
default_encoding = encoding;
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
req.setCharacterEncoding(default_encoding);
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
|
package rhtn_homework;
public class PROG_신규아이디추천 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String new_id = "abcdefghijklmn.p";
System.out.println(solution(new_id));
}
public static String solution(String new_id) {
StringBuilder answer = new StringBuilder();
// 1. 소문자
new_id = new_id.toLowerCase();
char[] ans = new_id.toCharArray();
boolean lastDot = false;
for (int i = 0; i < ans.length; i++) {
// 2. 특수 문자 제거
char c = ans[i];
if(!(Character.isLetterOrDigit(c) ||(c == '-' || c=='_' || c =='.'))) continue;
if(c =='.') {
// 4번 조건, 3번 조건
if(answer.length() == 0 || lastDot) continue;
lastDot = true;
}else {
lastDot = false;
}
answer.append(c);
}
// 5번
if(answer.length() == 0) answer.append("a");
// 6번
if(answer.length()>=16) {
answer.setLength(15);
}
// 4번, 6번
if(answer.charAt(answer.length()-1) == '.') answer.deleteCharAt(answer.length()-1);
// 7번
if(answer.length()<=2) {
char c = answer.charAt(answer.length()-1);
while(answer.length()<3) {
answer.append(c);
}
}
return answer.toString();
}
}
|
package Warenkorb;
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
public static void main(String[] args) {
CartUsernameComparator test=new CartUsernameComparator();
AnonymeComparator anoyn=new AnonymeComparator();
ArrayList<cart>list=new ArrayList<>();
list.add(new cart("warenkorb1", 4, 5, 12));
list.add(new cart("warenkorb4", 5, 5, 19));
list.add(new cart("warenkorb3", 6, 5, 18));
for (cart cart : list) {
System.out.println(cart);
}
System.out.println();
Collections.sort(list);
for (cart cart : list) {
System.out.println(cart);
}
System.out.println();
Collections.sort(list,test);
for (cart cart : list) {
System.out.println(cart);
}
System.out.println();
Collections.sort(list,anoyn);
for (cart cart : list) {
System.out.println(cart);
}
}
}
|
/*
* 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 sigu.view;
import aplikasisigu.Home;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import sigu.controller.controllerBarangMasuk;
import sigu.db.koneksiDatabase;
/**
*
* @author Luky Mulana
*/
public class viewListDataBarangMasuk extends javax.swing.JFrame {
/**
* Creates new form viewListDataBarang
*/
private Home ho;
private DefaultTableModel modelDataListBarang;
private String sql = "";
public viewListDataBarangMasuk(Home ho) throws IOException {
initComponents();
this.ho = ho;
modelDataListBarang = new DefaultTableModel();
tabelListDataBarang.setModel(modelDataListBarang);
modelDataListBarang.addColumn("Kode Barang");
modelDataListBarang.addColumn("Nama Barang");
modelDataListBarang.addColumn("Nama Kategori");
modelDataListBarang.addColumn("ID Kategori");
modelDataListBarang.addColumn("Nama Supplier");
modelDataListBarang.addColumn("ID Supplier");
modelDataListBarang.addColumn("Stok");
modelDataListBarang.addColumn("Satuan");
TableColumnModel tcm = tabelListDataBarang.getColumnModel();
tcm.removeColumn(tabelListDataBarang.getColumnModel().getColumn(3));
tcm.removeColumn(tabelListDataBarang.getColumnModel().getColumn(4));
tampilDataListBarang("");
}
public void tampilDataListBarang(String data) throws IOException {
modelDataListBarang.getDataVector().removeAllElements();
modelDataListBarang.fireTableDataChanged();
//kondisi pengecekan
if (data.equals("")) {
sql = "SELECT b.kode_barang, b.nama_barang, k.nama_kategori, k.kode_kategori, s.nama_supplier, s.kode_supplier,b.stok, b.satuan "
+ "from barang b, kategori k, supplier s where b.kode_kategori = k.kode_kategori "
+ "and b.kode_supplier = s.kode_supplier order by b.kode_barang asc";
} else sql = "SELECT b.kode_barang, b.nama_barang, k.nama_kategori, k.kode_kategori, s.nama_supplier, s.kode_supplier,b.stok, b.satuan "
+ "from barang b, kategori k, supplier s where b.kode_kategori = k.kode_kategori "
+ "and b.kode_supplier = s.kode_supplier and b.kode_barang like '%"+data+"%' order by b.kode_barang asc";
try {
Statement stat = (Statement) koneksiDatabase.getKoneksi().createStatement();
ResultSet res = stat.executeQuery(sql);
while (res.next()) {
Object[] hasil;
hasil = new Object[8];
hasil[0] = res.getString("kode_barang");
hasil[1] = res.getString("nama_barang");
hasil[2] = res.getString("nama_kategori");
hasil[3] = res.getString("kode_kategori");
hasil[4] = res.getString("nama_supplier");
hasil[5] = res.getString("kode_supplier");
hasil[6] = res.getString("stok");
hasil[7] = res.getString("satuan");
modelDataListBarang.addRow(hasil);
}
} catch (SQLException ex) {
Logger.getLogger(viewListDataBarangMasuk.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabelListDataBarang = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
txtKodeBarangViewListDataBarang = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(182, 205, 205));
tabelListDataBarang.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabelListDataBarang.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabelListDataBarangMouseClicked(evt);
}
});
tabelListDataBarang.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
tabelListDataBarangKeyPressed(evt);
}
});
jScrollPane1.setViewportView(tabelListDataBarang);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(55, 78, 78));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("LIST DATA BARANG");
txtKodeBarangViewListDataBarang.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtKodeBarangViewListDataBarangKeyPressed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(55, 78, 78));
jLabel2.setText("Kode Barang");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(txtKodeBarangViewListDataBarang, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 80, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtKodeBarangViewListDataBarang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(341, Short.MAX_VALUE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void txtKodeBarangViewListDataBarangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKodeBarangViewListDataBarangKeyPressed
try {
// TODO add your handling code here:
// fungsi ini akan di eksekusi ketika kita mencari nama barang
tampilDataListBarang(txtKodeBarangViewListDataBarang.getText());
} catch (IOException ex) {
Logger.getLogger(viewListDataBarangMasuk.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_txtKodeBarangViewListDataBarangKeyPressed
private void tabelListDataBarangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabelListDataBarangKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_tabelListDataBarangKeyPressed
private void tabelListDataBarangMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelListDataBarangMouseClicked
// TODO add your handling code here:
int ambilRow = tabelListDataBarang.getSelectedRow();
ho.getTfKodeBarangMasuk().setText((String) tabelListDataBarang.getValueAt(ambilRow, 0));
ho.getTfNamaBarangMasuk().setText(tabelListDataBarang.getValueAt(ambilRow, 1).toString());
ho.getTfNamaSupplierBarangMasuk().setText(tabelListDataBarang.getValueAt(ambilRow, 3).toString());
ho.getTfKodeSupplierBarangMasuk().setText(tabelListDataBarang.getModel().getValueAt(ambilRow, 5).toString());
ho.getTfNoFakturBarangMasuk().requestFocus();
ho.setEnabled(true);
controllerBarangMasuk cBM = new controllerBarangMasuk(ho);
cBM.kontrolButtonTiga();
this.dispose();
}//GEN-LAST:event_tabelListDataBarangMouseClicked
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tabelListDataBarang;
private javax.swing.JTextField txtKodeBarangViewListDataBarang;
// End of variables declaration//GEN-END:variables
}
|
package searchengine;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import storage.DocumentDA;
import storage.LinksDA;
public class BidirectionalSearch implements Runnable
{
int NUM_THREADS = 1;
Queue<WeightedPath> frontier = new PriorityQueue<WeightedPath>();
Map<String, WeightedPath> mySeenNodes = new HashMap<String, WeightedPath>();
Map<String, WeightedPath> seenNodesOther = new HashMap<String, WeightedPath>();
Thread[] threadPool = new Thread[NUM_THREADS];
int k, d;
String word, username;
public BidirectionalSearch(Map<String, WeightedPath> mySeenNodes, Map<String, WeightedPath> seenNodesOther, String word, String username, int k, int d)
{
this.mySeenNodes = mySeenNodes;
this.seenNodesOther = seenNodesOther;
this.word = word;
this.username = username;
this.k = k;
this.d = d;
}
@Override
public void run() {
LinksDA lDa = new LinksDA();
DocumentDA docDa = new DocumentDA();
//Start all the worker threads
for (int i = 0; i < NUM_THREADS; i++)
{
SearchEngineWorker worker_i = new SearchEngineWorker(frontier, mySeenNodes, seenNodesOther, username, lDa, docDa, k, d);
threadPool[i] = new Thread(worker_i);
threadPool[i].start();
}
//Initialize frontier with first word
synchronized(frontier)
{
//System.out.println("initializing frontier with " + word);
WeightedPath currentNode = new WeightedPath(word, 1);
frontier.add(currentNode);
frontier.notify();
}
//Wait for the threads to finish
try {
for (int i = 0; i < NUM_THREADS; i++)
{
threadPool[i].join();
//System.out.println("Thread " + i + " finished");
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
package facing;
import java.util.HashMap;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName LFU.java
* LRU(Least Recently Used) 最近最少使用算法,它是根据时间维度来选择将要淘汰的元素,即删除掉最长时间没被访问的元素。
* LFU(Least Frequently Used) 最近最不常用算法,它是根据频率维度来选择将要淘汰的元素,即删除访问频率最低的元素。
* 如果两个元素的访问频率相同,则淘汰最久没被访问的元素。
* 也就是说LFU淘汰的时候会选择两个维度,先比较频率,选择访问频率最小的元素;如果频率相同,则按时间维度淘汰掉最久远的那个元素。
*
* LRU的实现是一个哈希表加上一个双链表
* 而LFU则要复杂多了,需要用两个哈希表再加上N个双链表才能实现
* @Description 最不经常使用(LFU)缓存算法设计并实现数据结构。
* <p>
* 实现 LFUCache 类:
* <p>
* LFUCache(int capacity) - 用数据结构的容量capacity 初始化对象
* int get(int key)- 如果键存在于缓存中,则获取键的值,否则返回 -1。
* void put(int key, int value)- 如果键已存在,则变更其值;如果键不存在,请插入键值对。
* 当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。
* 在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 (最早使用)的键。
* 注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
* 为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
* 当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。
* <p>
* 思路:
* 双hashmap
* @createTime 2021年08月24日 20:09:00
*/
public class LFU {
class ListNode{
int key;
int value;
int time;
ListNode next;
ListNode pre;
public ListNode(int key, int value) {
this.key = key;
this.value = value;
}
public ListNode() {
}
}
ListNode head = new ListNode();//链表的头
ListNode tail = new ListNode();//链表的尾
HashMap<Integer, ListNode> map = new HashMap<>();//key=结点的key,value=指向的结点
HashMap<Integer,Integer> countMap=new HashMap<>();//key=使用次数,value=使用次数为key的所有结点的最后一个的key
//比如节点1和节点2使用次数都是1,如果1先使用,那它就在链表尾,value=1(从尾部删除保证了删除的是最早(旧)的)
int capacity =0;//map的大小
public LFU(int capacity) {
head.time=Integer.MAX_VALUE;
tail.time=0;//每次都先放到尾部去
this.capacity =capacity;
head.next=tail;//构建双向链表
tail.pre=head;
}
//先写几个辅助函数,也是对链表的操作函数
//将节点从链表中拿开
public void take(ListNode node) {
node.next.pre = node.pre;
node.pre.next = node.next;
}
//将node移动到where节点之后
public void move(ListNode node,ListNode where){
node.next = where.next;
node.next.pre = node;
where.next = node;
node.pre = where;
}
//找到要移动到哪里(找到次数最相近的(大1的))
public ListNode findWhere(int time){
ListNode temp = head;
int nearCount = Integer.MAX_VALUE;
for (Integer count : countMap.keySet()) {
if (count - time > 0 && count - time < nearCount) {
nearCount = count - time;
if (nearCount == 1) {
break;
}
}
}
//在这里找到countMap中相对于传参time大1的的次数即nearCount
//找到使用次数虽然比该节点大,但是也是大中最小的那个(即出现次数只大了1)
//因为尾部删除保证了删除的是最早(旧)的,所以在有新节点进来时要找到在nearCount之前的那个节点
if (nearCount != Integer.MAX_VALUE) {
temp = map.get(countMap.get(time + nearCount));
}
return temp;
}
//返回次数time
public int get(int key) {
if (capacity == 0) {
return -1;
}
//map里有元素
if (map.containsKey(key)) {
ListNode node = map.get(key);
//检查一下该结点是不是在和它使用次数相同结点的首部(首部这一点在put时保证)
if (countMap.get(node.time) == key) {
//是,所以先移除该节点在countMap的记录
countMap.remove(node.time);
int newKey = node.pre.key;
// //检查前一个结点,看看他的使用次数是否和当前元素相同,相同的话,就更新一下
if (map.containsKey(newKey) && map.get(newKey).time == node.time) {
countMap.put(node.time, newKey);
}
}
//该节点没有遇到次数相同的节点
//使用次数加1
node.time++;
// //检查加1后,countmap里是否有使用次数为更新后次数的节点,没有就更新countMap
if(!countMap.containsKey(node.time)){
countMap.put(node.time,key);
}
//将节点从链表中拿开
take(node);
//找到要插入的位置,并将node移到该位置后
move(node, findWhere(node.time));
return node.time;
}
return -1;
}
public void put(int key, int value) {
if(capacity ==0){
return;
}
if (get(key) > -1) {//如果能get到,就将新value赋值
map.get(key).value = value;
} else {//否则就在链表中新建节点(key,value,time=1)
ListNode node = new ListNode(key, value);
node.time = 1;
if (map.size() == capacity) {//新增会遇到容量问题,先删除最近最少使用的缓存,再进行插入。
//还要保证从尾部删除的是最早(旧)的
int rk = tail.pre.key;
int tk = tail.pre.time;
map.remove(rk);
countMap.remove(tk);
int prk = tail.pre.pre.key;
int ptk = tail.pre.pre.time;
if (ptk != Integer.MAX_VALUE) {
countMap.put(ptk, prk);//这一步是真正跟新 countMap的,在遇到容量问题删除链表尾部前节点,同时把尾部前前节点放入countMap
}
//删除尾部节点(插的时候是从头部插的,所以尾部是最旧的)
take(tail.pre);
}
if (!countMap.containsKey(1)) {
countMap.put(1, key);
}
//最后跟新map
map.put(key, node);
//依据node.time把node放链表中合适的位置
move(node, findWhere(node.time));
}
}
}
|
/*
* Copyright (C) 2013-2014 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fantasy.systemui.quicksettings;
import android.content.Context;
import android.content.res.Resources;
import android.net.wifi.WifiManager;
import android.view.View;
import com.android.systemui.statusbar.phone.QuickSettingsController;
import com.android.systemui.statusbar.phone.ResourceUtils;
import com.android.systemui.statusbar.policy.NetworkController;
public class WiFiTile extends NetworkTile {
private boolean mWifiConnected;
private boolean mWifiNotConnected;
private int mWifiSignalIconId;
private String mDescription;
public WiFiTile(Context context, QuickSettingsController qsc, NetworkController controller) {
super(context, qsc, controller, ResourceUtils.getResLayout(context, "quick_settings_tile_wifi"));
mOnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wfm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
wfm.setWifiEnabled(!wfm.isWifiEnabled());
}
};
mOnLongClick = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
};
}
@Override
protected void updateTile() {
if (mWifiConnected) {
mDrawable = mWifiSignalIconId;
mLabel = mDescription.substring(1, mDescription.length()-1);
} else if (mWifiNotConnected) {
mDrawable = ResourceUtils.getResDrawable(mContext, "ic_qs_wifi_0");
mLabel = mContext.getString(ResourceUtils.getResString(mContext, "quick_settings_wifi_label"));
} else {
mDrawable = ResourceUtils.getResDrawable(mContext, "ic_qs_wifi_no_network");
mLabel = mContext.getString(ResourceUtils.getResString(mContext, "quick_settings_wifi_off_label"));
}
}
@Override
public void onWifiSignalChanged(boolean enabled, int wifiSignalIconId,
boolean activityIn, boolean activityOut,
String wifiSignalContentDescriptionId, String description) {
mWifiConnected = enabled && wifiSignalIconId > 0 && description != null;
mWifiNotConnected = wifiSignalIconId > 0 && description == null;
mWifiSignalIconId = wifiSignalIconId;
mDescription = description;
setActivity(activityIn, activityOut);
updateResources();
}
@Override
public void onMobileDataSignalChanged(boolean enabled, int mobileSignalIconId,
String mobileSignalContentDescriptionId, int dataTypeIconId,
boolean activityIn, boolean activityOut,
String dataTypeContentDescriptionId, String description) {
}
@Override
public void onAirplaneModeChanged(boolean enabled) {
}
}
|
package Sem1.HomeWork.Sorts;
import java.util.Random;
/**
* Created by skima on 18.11.2016.
*/
public class StudentsCreator {
private static String[] names = new String[]{"Paul", "Max", "Mark", "Angelina", "Izabell", "Adolf", "Iosif", "Gans", "Maria"};
private Random random;
public StudentsCreator() {
random = new Random();
}
public Student[] Create(int amount){
Student[] students = new Student[amount];
for (int i = 0; i < amount; i++){
students[i] = new Student(getRandomName(), getRandomAge(), getRandomScore());
}
return students;
}
private String getRandomName(){
return names[random.nextInt(names.length)];
}
private int getRandomAge(){
return random.nextInt(10) + 18;
}
private int getRandomScore(){
return random.nextInt(101);
}
}
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.util.regex.Pattern;
/**
* Creates a high score dialog, displaying the top 10 scores.
* Adds a new high score if there is one and lets the user assign his name to it.
*/
public class HighScoresDialog{
private JDialog dialog;
private JPanel mainPanel;
private JTextField newName;
private HighScoresControl scores;
private int scorePlace;
private int queuedScore = -1;
private boolean focus;
private boolean active = false;
/**
* Constructor. Creates a HighScoresDialog with the top 10 high scores stored
* and adds a new one. (If new score is less than 0, no new scores are added)
* @param frame the frame owner of the dialog
* @param scores list of the current top 10 high scores
* @param newScore the new high score to be added
*/
public HighScoresDialog(JFrame frame, HighScoresControl scores, int newScore){
this.scores = scores;
createPanel(newScore);
createDialog(frame);
}
/**
* Constructor. Creates a HighScoresDialog with the top 10 high scores stored
* @param frame the frame owner of the dialog
* @param scores list of the current top 10 high scores
*/
public HighScoresDialog(JFrame frame, HighScoresControl scores){
this(frame,scores,-1);
}
/**
* Creates the high scores dialog.
* @param frame the frame owner of the dialog
*/
private void createDialog(JFrame frame){
dialog = new JDialog(frame,"High Scores");
active = true;
dialog.setContentPane(mainPanel);
dialog.setLocationRelativeTo(frame);
dialog.setResizable(false);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
dispose();
}
});
dialog.pack();
dialog.setFocusableWindowState(focus);
dialog.setVisible(true);
}
/**
* Create the panel displaying the high scores.
* Add new high score if necessary
* @param newScore the new high score
*/
private void createPanel(int newScore){
//set up the panels and their layouts
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.LINE_AXIS));
mainPanel.setPreferredSize(new Dimension(160,185));
JPanel placePanel = new JPanel();
placePanel.setLayout(new GridLayout(11,1));
JPanel namePanel = new JPanel();
namePanel.setLayout(new GridLayout(11,1));
JPanel scorePanel = new JPanel();
scorePanel.setLayout(new GridLayout(11,1));
//add the title row
placePanel.add(new JLabel("No."));
namePanel.add(new JLabel(" NAME"));
scorePanel.add(new JLabel("SCORE"));
for(int i=0; i<10; i++){
placePanel.add(new JLabel(Integer.toString(i+1)+"."));
}
//if no new score, show the current top 10
if(newScore <= 0){
focus = false;
for(int i = 0;i < 10;i++){
namePanel.add(new JLabel(scores.getName(i)));
scorePanel.add(new JLabel(" "+Integer.toString(scores.getScore(i))));
}
}
//if there is a new score add it and let the user add his name to it
else{
focus = true;
queuedScore = newScore;
JPanel newNamePanel = new JPanel();
newNamePanel.setLayout(new BoxLayout(newNamePanel,BoxLayout.LINE_AXIS));
newName = new JTextField(9);
((AbstractDocument) newName.getDocument()).setDocumentFilter(new CustomDocumentFilter());
newName.requestFocusInWindow();
//add the score at it's place and rearange the rest of the scores
for(int i=0;i<10;i++){
if(newScore > scores.getScore(i)){
scorePlace = i;
for(int j = 9;j>i;j--){
scores.setHighScore(j,scores.getName(j-1),scores.getScore(j-1));
}
break;
}
}
//display the scores before the new one
for(int i = 0;i < scorePlace;i++){
namePanel.add(new JLabel(scores.getName(i)));
scorePanel.add(new JLabel(" "+Integer.toString(scores.getScore(i))));
}
//display the new score with a space to assign a name to it
newNamePanel.add(newName);
newNamePanel.setPreferredSize(new Dimension(100, 5));
namePanel.add(newNamePanel);
scorePanel.add(new JLabel(" "+Integer.toString(newScore)));
//display the scores after the new one
for(int i = scorePlace+1;i<10;i++){
namePanel.add(new JLabel(scores.getName(i)));
scorePanel.add(new JLabel(" "+Integer.toString(scores.getScore(i))));
}
//when a name is typed and Enter is pressed finilize the field and save the score
newName.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!newName.getText().isEmpty()){
scores.setHighScore(scorePlace,newName.getText(),newScore);
queuedScore = -1;
newNamePanel.remove(newName);
newNamePanel.add(new JLabel(scores.getName(scorePlace)));
newNamePanel.revalidate();
newNamePanel.repaint();
dialog.getParent().requestFocus();
}
}
});
}
//add the objects to the mainPanel and shape it
mainPanel.add(Box.createRigidArea(new Dimension(5, 0)));
mainPanel.add(placePanel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 0)));
mainPanel.add(namePanel);
mainPanel.add(Box.createHorizontalGlue());
mainPanel.add(scorePanel);
mainPanel.add(Box.createRigidArea(new Dimension(5, 0)));
}
/**
* Dispose of the window if there is one and save the scores
* if there is a queued score for adding, add it with name "NoName".
*/
public void dispose(){
if(active){
if(queuedScore>0){
scores.setHighScore(scorePlace,newName.getText(),queuedScore);
queuedScore = -1;
}
try{
scores.save();
}catch(Exception ex){ ex.printStackTrace(System.out); }
dialog.dispose();
active = false;
}
}
// Filter for the newName text field. Only alphabetical,numerical ,"_" and "-" characters can be entered up to 9 characters.
private class CustomDocumentFilter extends DocumentFilter{
private Pattern regexCheck = Pattern.compile("[A-Za-z0-9_-]+");
private int maxChars = 9;
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attrs) throws BadLocationException{
if (string == null){
return;
}
if(regexCheck.matcher(string).matches()&&(fb.getDocument().getLength() + string.length()) <= maxChars) {
super.insertString(fb,offset,string,attrs);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException{
if(string == null) {
return;
}
if(regexCheck.matcher(string).matches()&&(fb.getDocument().getLength() + string.length() - length) <= maxChars){
fb.replace(offset,length,string,attrs);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
}
} |
package au.com.autogeneral.testAPI;
import au.com.autogeneral.testAPI.domain.ToDo;
import au.com.autogeneral.testAPI.service.ToDoService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApiApplicationTests {
@Autowired
private ToDoService toDoService;
@Test
public void contextLoads() {
}
@Test
public void testPersistence() {
ToDo test = toDoService.createToDo("test");
Optional<ToDo> toDoOptional = toDoService.findToDo(test.getId());
assertTrue("It can be loaded.", toDoOptional.isPresent());
assertEquals("It is the same.", "test", toDoOptional.get().getText());
assertFalse("And it is not completed.", toDoOptional.get().isCompleted());
toDoService.updateToDo(test.getId(), "done", null);
toDoOptional = toDoService.findToDo(test.getId());
assertEquals("It has changed.", "done", toDoOptional.get().getText());
assertFalse("And it is still not completed.", toDoOptional.get().isCompleted());
toDoService.updateToDo(test.getId(), null, true);
toDoOptional = toDoService.findToDo(test.getId());
assertEquals("It has not changed.", "done", toDoOptional.get().getText());
assertTrue("But it is completed.", toDoOptional.get().isCompleted());
}
}
|
/**
* Copyright [http://game2d.sinaapp.com] [xtiqin]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.plter.lib.java.lang;
/**
* 数学相关的类
* @author xtiqin
* @see <a href="http://weibo.com/plter">plter</a>
* @see <a href="http://game2d.sinaapp.com">Game2D</a>
*
*/
public final class Math {
/**
* 求两个值的最小值
* @param a 第一个值
* @param b 第二个值
* @return 最小值
*/
public static float min(float a,float b) {
return a>b?b:a;
}
/**
* 求很float类型值的最小值
* @param args
* @return
*/
public static float min(float...args) {
float minValue=Float.MAX_VALUE;
for (float f : args) {
minValue=min(minValue, f);
}
return minValue;
}
/**
* 求两个值的最大值
* @param a 第一个值
* @param b 第二个值
* @return 最大值
*/
public static float max(float a,float b) {
return a>b?a:b;
}
/**
* 求很多float类型值的最大值
* @param args
* @return
*/
public static float max(float...args) {
float maxValue=Float.MIN_VALUE;
for (float f : args) {
maxValue=max(maxValue, f);
}
return maxValue;
}
}
|
package com.company;
public class Dog extends Animal{
public boolean isCanine;
@Override
public void begForPats() {
System.out.println("If cat doesn't want them, I'll take them!");
}
}
|
package com.dong1990.demo;
public class SmspullReport {
}
|
package com.polsl.edziennik.desktopclient.view.common.panels.preview;
import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import org.jdesktop.swingx.JXDatePicker;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.polsl.edziennik.delegates.AdminDelegate;
import com.polsl.edziennik.delegates.DelegateFactory;
import com.polsl.edziennik.delegates.exceptions.DelegateException;
import com.polsl.edziennik.desktopclient.controller.utils.DateConverter;
import com.polsl.edziennik.desktopclient.controller.utils.LangManager;
import com.polsl.edziennik.desktopclient.controller.utils.factory.GuiComponentFactory;
import com.polsl.edziennik.desktopclient.controller.utils.factory.IGuiComponentAbstractFactory;
import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.ILabel;
import com.polsl.edziennik.desktopclient.model.tables.HappyHoursTableModel;
import com.polsl.edziennik.desktopclient.properties.Properties;
import com.polsl.edziennik.modelDTO.happyhours.HappyHoursDTO;
public class HappyHoursPreviewPanel extends JPanel {
public static final int TEXT_SIZE = 30;
public static final String[] HOURS = new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" };
public static final String[] MINUTES = new String[] { "00", "15", "30", "45" };
private JLabel dateFrom;
private JLabel dateTo;
private JLabel description;
private JTextArea descriptionText;
private JXDatePicker dateFromPicker;
private JXDatePicker dateToPicker;
private JComboBox hoursFrom;
private JComboBox minutesFrom;
private JComboBox hoursTo;
private JComboBox minutesTo;
private CellConstraints cc;
private IGuiComponentAbstractFactory factory = GuiComponentFactory.getInstance();
private HappyHoursTableModel model;
private ResourceBundle bundle = LangManager.getResource(Properties.Component);
private HappyHoursDTO current;
private AdminDelegate admin;
private Integer selected;
private DateConverter dateConverter;
public HappyHoursPreviewPanel(String title, HappyHoursTableModel model) {
this.model = model;
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title),
BorderFactory.createEmptyBorder(0, 6, 6, 6)));
FormLayout layout = new FormLayout(
"pref,4dlu,30dlu,4dlu,30dlu,4dlu, 28dlu,4dlu,28dlu, 4dlu, min",
"pref, 2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref");
setLayout(layout);
ILabel label = factory.createLabel();
factory.createTextButton();
dateFrom = label.getLabel("dateStart");
dateTo = label.getLabel("dateStop");
description = label.getLabel("note");
hoursFrom = new JComboBox(HOURS);
minutesFrom = new JComboBox(MINUTES);
hoursTo = new JComboBox(HOURS);
minutesTo = new JComboBox(MINUTES);
descriptionText = new JTextArea(5, 3);
descriptionText.setLineWrap(true);
descriptionText.setWrapStyleWord(true);
dateFromPicker = new JXDatePicker(null, new Locale("pl"));
dateToPicker = new JXDatePicker(null, new Locale("pl"));
dateConverter = new DateConverter();
setComponents();
setEnabled(false);
}
public void setComponents() {
cc = new CellConstraints();
add(dateFrom, cc.xy(1, 1));
add(dateFromPicker, cc.xyw(3, 1, 5));
add(hoursFrom, cc.xy(9, 1));
add(minutesFrom, cc.xy(11, 1));
add(dateTo, cc.xy(1, 3));
add(dateToPicker, cc.xyw(3, 3, 5));
add(hoursTo, cc.xy(9, 3));
add(minutesTo, cc.xy(11, 3));
add(description, cc.xyw(1, 5, 5));
add(descriptionText, cc.xyw(3, 5, 9));
}
public void setData(HappyHoursDTO a) {
// nowe godziny
if (a == null) {
clear();
} else {
clear();
int tmp = 0;
String str = "";
if (a.getDateFrom() != null) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(a.getDateFrom());
dateFromPicker.setDate(c.getTime());
tmp = c.get(Calendar.HOUR_OF_DAY);
if (tmp < 10)
str = "0" + tmp;
else
str = "" + tmp;
hoursFrom.setSelectedItem(str);
tmp = c.get(Calendar.MINUTE);
if (tmp < 10)
str = "0" + tmp;
else
str = "" + tmp;
minutesFrom.setSelectedItem(str);
}
if (a.getDateTo() != null) {
Calendar c2 = Calendar.getInstance();
c2.setTimeInMillis(a.getDateTo());
dateToPicker.setDate(c2.getTime());
tmp = c2.get(Calendar.HOUR_OF_DAY);
if (tmp < 10)
str = "0" + tmp;
else
str = "" + tmp;
hoursTo.setSelectedItem(str);
tmp = c2.get(Calendar.MINUTE);
if (tmp < 10)
str = "0" + tmp;
else
str = "" + tmp;
minutesTo.setSelectedItem(str);
}
descriptionText.setText(a.getDescription());
}
current = a;
}
public void clear() {
dateFromPicker.setDate(null);
dateToPicker.setDate(null);
hoursFrom.setSelectedIndex(0);
minutesFrom.setSelectedIndex(0);
hoursTo.setSelectedIndex(0);
minutesTo.setSelectedIndex(0);
descriptionText.setText("");
}
@Override
public void setEnabled(boolean b) {
dateFromPicker.setEnabled(b);
hoursFrom.setEnabled(b);
minutesFrom.setEnabled(b);
dateToPicker.setEnabled(b);
hoursTo.setEnabled(b);
minutesTo.setEnabled(b);
descriptionText.setEnabled(b);
}
public void saveHappyHours() throws DelegateException {
// zapis nowych godziń dziekańskich
admin = DelegateFactory.getAdminDelegate();
if (current == null) {
current = new HappyHoursDTO();
setHappyHoursData();
admin.addHappyHours(current);
model.add(current);
} else {
setHappyHoursData();
admin.updateHappyHours(current);
model.update(current, selected);
}
}
private void setHappyHoursData() {
current.setDateFrom(dateConverter.getDate(dateFromPicker.getDate().getTime(),
(String) hoursFrom.getSelectedItem(), (String) minutesFrom.getSelectedItem()));
current.setDateTo(dateConverter.getDate(dateToPicker.getDate().getTime(), (String) hoursTo.getSelectedItem(),
(String) minutesTo.getSelectedItem()));
current.setDescription(descriptionText.getText());
}
public void setSelected(int index) {
selected = index;
}
@Override
public void disable() {
clear();
setEnabled(false);
}
public boolean checkDates() {
if (dateConverter.getDate(dateFromPicker.getDate().getTime(), (String) hoursFrom.getSelectedItem(),
(String) minutesFrom.getSelectedItem()) < dateConverter.getDate(dateToPicker.getDate().getTime(),
(String) hoursTo.getSelectedItem(), (String) minutesTo.getSelectedItem())) return true;
return false;
}
public void setEditable(boolean b) {
dateFromPicker.setEditable(b);
hoursFrom.setEnabled(b);
minutesFrom.setEnabled(b);
dateToPicker.setEditable(b);
hoursTo.setEnabled(b);
minutesTo.setEnabled(b);
descriptionText.setEditable(b);
}
}
|
package com.example.demo.utility.exceptions.UserExceptions;
import com.example.demo.utility.exceptions.TechnoMarketException;
public class UserNotFoundException extends TechnoMarketException {
public UserNotFoundException() {
super("User with this credentials does not exists!");
}
}
|
/*
* frmSDEmpty.java
*
* Created on 27 Ekim 2007 Cumartesi, 17:27
*/
package askan;
import askan.systems.*;
import askan.steelyard.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
/**
*
* @author Kerem
*/
public class frmSDEmpty extends javax.swing.JFrame {
public SalesProcess salesProcess;
private boolean isSaved;
/** Creates new form frmSDEmpty */
public frmSDEmpty() {
initComponents();
ActionMap am;
InputMap im;
KeyStroke ks;
Action plateActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnPlateActionPerformed(actionEvent);
}
};
am = btnPlate.getActionMap();
im = btnPlate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
im.put(ks, "plate");
am.put("plate", plateActionListener);
Action weighActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnWeighActionPerformed(actionEvent);
}
};
am = btnWeigh.getActionMap();
im = btnWeigh.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
im.put(ks, "weigh");
am.put("weigh", weighActionListener);
Action saveActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnSaveActionPerformed(actionEvent);
}
};
am = btnSave.getActionMap();
im = btnSave.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0);
im.put(ks, "save");
am.put("save", saveActionListener);
Action closeActionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
btnCloseActionPerformed(actionEvent);
}
};
am = btnClose.getActionMap();
im = btnClose.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0);
im.put(ks, "close");
am.put("close", closeActionListener);
Action printActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnPrint1ActionPerformed(actionEvent);
}
};
am = btnPrint1.getActionMap();
im = btnPrint1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0);
im.put(ks, "print");
am.put("print", printActionListener);
setStatus("Lütfen çekici / dorse plakasını girip SORGULA düğmesine basın");
txtWeightEmpty.setEditable(Main.config.intParam.manualWeight);
txtVrkme.setEditable(Main.config.intParam.manualWeight);
isSaved = false;
}
public void setStatus(String Status)
{
lblStatus.setText(Status);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtPlate1 = new javax.swing.JTextField();
btnPlate = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txtPlate2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtWeightEmpty = new javax.swing.JTextField();
txtVrkme = new javax.swing.JTextField();
btnWeigh = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
txtCustomer = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtMaterial = new javax.swing.JTextField();
lblStatus = new javax.swing.JLabel();
btnSave = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
txtNote = new javax.swing.JTextField();
btnPrint1 = new javax.swing.JButton();
chkInspect = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Boş Tartım");
setResizable(false);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel1.setText("Çekici Plakası");
txtPlate1.setFont(new java.awt.Font("Tahoma", 0, 14));
txtPlate1.setNextFocusableComponent(txtPlate2);
btnPlate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/add_16.gif"))); // NOI18N
btnPlate.setText("F1 - Seç");
btnPlate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPlateActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel2.setText("Dorse Plakası");
txtPlate2.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel3.setText("Boş Ağırlık");
txtWeightEmpty.setEditable(false);
txtWeightEmpty.setFont(new java.awt.Font("Tahoma", 0, 14));
txtVrkme.setEditable(false);
txtVrkme.setFont(new java.awt.Font("Tahoma", 0, 14));
btnWeigh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/applications_16.gif"))); // NOI18N
btnWeigh.setText("F5 - Tart");
btnWeigh.setEnabled(false);
btnWeigh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnWeighActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel4.setText("Müşteri");
txtCustomer.setEditable(false);
txtCustomer.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel5.setText("Malzeme");
txtMaterial.setEditable(false);
txtMaterial.setFont(new java.awt.Font("Tahoma", 0, 14));
lblStatus.setText("...");
lblStatus.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/save_16.gif"))); // NOI18N
btnSave.setText("F11 - Kaydet");
btnSave.setEnabled(false);
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/delete_16.gif"))); // NOI18N
btnClose.setText("F12 - Kapat");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel6.setText("Notlar");
txtNote.setEditable(false);
txtNote.setFont(new java.awt.Font("Tahoma", 0, 14));
btnPrint1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/S_B_PRNT.gif"))); // NOI18N
btnPrint1.setText("F10");
btnPrint1.setEnabled(false);
btnPrint1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrint1ActionPerformed(evt);
}
});
chkInspect.setText("İncelensin");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPlate2)
.addComponent(txtPlate1, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnPlate, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCustomer, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
.addComponent(txtMaterial, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)))))
.addComponent(lblStatus, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtWeightEmpty, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtVrkme, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnWeigh, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnPrint1, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnClose, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(txtNote, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chkInspect)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtPlate1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPlate2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7))
.addGroup(layout.createSequentialGroup()
.addComponent(btnPlate, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMaterial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnWeigh)
.addComponent(txtVrkme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtWeightEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(chkInspect)
.addComponent(txtNote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClose)
.addComponent(btnSave)
.addComponent(btnPrint1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblStatus))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
boolean canDispose = true;
if (!isSaved) canDispose = askan.systems.Util.confirmStep(this, "Giriş henüz kaydedilmedi! \nKapatmak istiyor musunuz?");
if (canDispose) this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
private void btnWeighActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWeighActionPerformed
TwoWaySerialComm.truckStatus = TwoWaySerialComm.TRUCK_STATUS.EMPTY;
if (Main.config.intParam.manualWeight)
{
try
{
salesProcess.emptyWeight = new Weight();
salesProcess.emptyWeight.setWeight(txtWeightEmpty.getText(), txtVrkme.getText());
}
catch(Exception ex)
{
Main.appendLog("Ağırlık hatası: " + ex.toString());
setStatus("Lütfen ağırlıkları kontrol edin");
return;
}
}
else
{
salesProcess.emptyWeight = Main.steelYard.getLastWeight();
}
if (salesProcess.emptyWeight.getWeight() == 0)
{
setStatus("Tartım hatası");
}
else
{
truckWeighted();
}
}//GEN-LAST:event_btnWeighActionPerformed
private void transferFormToObjectPreSave()
{
salesProcess.trmtyp2 = Util.formatPlate(txtPlate2.getText());
salesProcess.emptyNote = txtNote.getText();
salesProcess.inspect = chkInspect.isSelected();
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
btnSave.setEnabled(false);
try
{
transferFormToObjectPreSave();
salesProcess.saveEmptyWeight();
setStatus("Boş ağırlık kaydedildi, kamyon mal almaya gidebilir");
btnWeigh.setEnabled(false);
txtNote.setEditable(false);
chkInspect.setEnabled(false);
isSaved = true;
}
catch(Exception ex)
{
setStatus("Boş ağırlık kaydedilirken bir hata oluştu");
Main.appendLog(salesProcess.trmtyp + " aracına ait boş ağırlık kaydedilirken bir hata oluştu: " + ex.toString());
btnSave.setEnabled(true);
}
}//GEN-LAST:event_btnSaveActionPerformed
private void btnPlateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlateActionPerformed
connectToSql();
// Ekranı kapat
setStatus("Araç sorgulanıyor...");
txtPlate1.setEditable(false);
txtPlate2.setEditable(false);
btnPlate.setEnabled(false);
// Process'i bul
try
{
salesProcess = new SalesProcess();
boolean b = salesProcess.fillFromPlate(txtPlate1.getText());
if (!b)
{
setStatus(txtPlate1.getText() + " plakalı araç henüz sevkiyat girişini yapmamış");
enableAfterPlateQuery();
return;
}
}
catch(Exception ex)
{
Main.appendLog("Plaka sorgusu sırasında hata: " + ex.toString());
enableAfterPlateQuery();
return;
}
if (salesProcess.passedEmpty)
{
if (askan.systems.Util.confirmStep(this, "Bu araç boş kantarda zaten tartılmış! \nTartımı tekrarlamak istiyor musunuz?"))
{
try
{
salesProcess.cancelEmptyWeight();
}
catch(Exception ex)
{
Main.appendLog("Boş tartım iptali sırasında hata: " + ex.toString());
setStatus("Boş tartım iptali sırasında bir hata oluştu");
enableAfterPlateQuery();
return;
}
}
else
{
setStatus(txtPlate1.getText() + " plakalı araç boş kantarda zaten tartılmış");
enableAfterPlateQuery();
return;
}
}
// Aktarım
txtCustomer.setText(salesProcess.getCustomerDisplayText());
txtMaterial.setText(salesProcess.material.getDisplayText());
txtNote.setEditable(true);
if (salesProcess.inspect)
{
chkInspect.setEnabled(false);
chkInspect.setSelected(true);
}
// Bizim araç ise ağırlık?
boolean mustWeight = false;
if (txtPlate2.getText().length() > 0)
{
try
{
Weight w1 = Vehicle.getWeight(txtPlate1.getText());
Weight w2 = Vehicle.getWeight(txtPlate2.getText());
mustWeight = (w1.getWeight() == 0 || w2.getWeight() == 0);
if (!mustWeight)
{
salesProcess.emptyWeight.setWeight(Material.toKG(w1) + Material.toKG(w2), Material.UNIT_OF_MEASURE.KG);
truckWeighted();
btnWeigh.setEnabled(true);
txtNote.setEditable(true);
}
}
catch(Exception ex)
{
mustWeight = true;
}
}
else
{
mustWeight = true;
}
if (mustWeight)
{
setStatus("Araç ağırlığı tespit edilemedi, lütfen kantarda tartın");
btnWeigh.setEnabled(true);
return;
}
}//GEN-LAST:event_btnPlateActionPerformed
private void btnPrint1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrint1ActionPerformed
btnPrint1.setEnabled(false);
if (!isSaved) transferFormToObjectPreSave();
this.setStatus("Kantar fişi yazdırılıyor, lütfen bekleyin");
salesProcess.printSevk();
setStatus("Kantar fişi yazdırıldı");
btnPrint1.setEnabled(true);
}//GEN-LAST:event_btnPrint1ActionPerformed
private void truckWeighted()
{
txtWeightEmpty.setText(salesProcess.emptyWeight.toString(false));
txtVrkme.setText(salesProcess.emptyWeight.getUOM());
setStatus("Boş ağırlık tespit edildi, yazdırıp kaydedebilirsiniz. Gerekiyorsa tekrar tartabilirsiniz.");
txtNote.setEditable(true);
btnSave.setEnabled(true);
btnPrint1.setEnabled(true);
}
private void enableAfterPlateQuery()
{
txtPlate1.setEditable(true);
txtPlate2.setEditable(true);
btnPlate.setEnabled(true);
}
private boolean connectToSql()
{
try
{
Main.sql.connect();
return true;
}
catch(Exception ex)
{
Main.appendLog("SQL bağlantı hatası: " + ex.toString());
setStatus("SQL bağlantı hatası");
return false;
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmSDEmpty().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnPlate;
private javax.swing.JButton btnPrint1;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnWeigh;
private javax.swing.JCheckBox chkInspect;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel lblStatus;
private javax.swing.JTextField txtCustomer;
private javax.swing.JTextField txtMaterial;
private javax.swing.JTextField txtNote;
private javax.swing.JTextField txtPlate1;
private javax.swing.JTextField txtPlate2;
private javax.swing.JTextField txtVrkme;
private javax.swing.JTextField txtWeightEmpty;
// End of variables declaration//GEN-END:variables
}
|
package interviews.amazon.oa1.tree;
import common.TreeNode;
public class LongestConsecutive {
private int max = 0;
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
helper(root, 0, root.val);
return max;
}
public void helper(TreeNode root, int cur, int target){
if(root == null) return;
cur = root.val == target ? cur + 1 : 1;
max = Math.max(cur, max);
helper(root.left, cur, root.val + 1);
helper(root.right, cur, root.val + 1);
}
public int longestConsecutive2(TreeNode root) {
if(root == null) return 0;
return Math.max(dfs(root.left, 1, root.val), dfs(root.right, 1, root.val));
}
public int dfs(TreeNode root, int count, int val){
if(root == null) return count;
count = (root.val - val == 1) ? count + 1 : 1;
int left = dfs(root.left, count, root.val);
int right = dfs(root.right, count, root.val);
return Math.max(Math.max(left, right), count);
}
}
|
package com.feng.demo;
import com.feng.fundation.init.TaskProducer;
import com.feng.fundation.mod.Task;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Feng
*/
@Component
public class TestTaskProducer implements TaskProducer {
@Override
public List<Task> getInitialJob() {
List<Task> jobs = new ArrayList();
Task testJob = new Task("test1","* * * ? * * *","0","test","测试任务1","com.feng.demo.TestWork");
jobs.add(testJob);
return jobs;
}
}
|
package br.com.acaosistemas.db.model;
import java.sql.Date;
import br.com.acaosistemas.db.enumeration.StatusPoboxXMLEnum;
/**
* Entidade representando tabela UBI_POBOX_XML_LOG
* <p>
* <b>Empresa:</b> Acao Sistemas de Informatica Ltda.
* <p>
* Alterações:
* <p>
* 2018.03.15 - ABS - Implementado metodo toString().
*
*
* @author Anderson Bestteti Santos
*
*/
public class UBIPoboxXmlLog {
private Long ubpxSeqReg;
private Long seqReg;
private Date dtMov;
private String mensagem;
private Long numErro;
private StatusPoboxXMLEnum status;
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
public Long getNumErro() {
return numErro;
}
public void setNumErro(Long numErro) {
this.numErro = numErro;
}
public StatusPoboxXMLEnum getStatus() {
return status;
}
public void setStatus(StatusPoboxXMLEnum status) {
this.status = status;
}
public Long getUbpxSeqReg() {
return ubpxSeqReg;
}
public void setUbpxSeqReg(Long ubpxSeqReg) {
this.ubpxSeqReg = ubpxSeqReg;
}
public Long getSeqReg() {
return seqReg;
}
public void setSeqReg(Long seqReg) {
this.seqReg = seqReg;
}
public Date getDtMov() {
return dtMov;
}
public void setDtMov(Date dtMov) {
this.dtMov = dtMov;
}
@Override
public String toString() {
return "UBIPoboxXmlLog [ubpxSeqReg=" + ubpxSeqReg + ", seqReg=" + seqReg + ", dtMov=" + dtMov + ", mensagem="
+ mensagem + ", numErro=" + numErro + ", status=" + status + "]";
}
}
|
/**
*
*/
package com.goodhealth.design.demo.BuilderPattern;
/**
* @author 24663
* @date 2018年10月21日
* @Description
*/
public class EnglishBuiler extends Builder {
English english=null;
/* (non-Javadoc)
* @see Builder.Builder#setPerson()
*/
@Override
public void setPerson(String nose, String eyes, String skin,String character){
this.english=new English();
this.english.setEyes(eyes);
this.english.setNose(nose);
this.english.setSkin(skin);
this.english.setCharacter(character);
}
/* (non-Javadoc)
* @see Builder.Builder#BuilderPerson()
*/
@Override
public Person BuilderPerson() throws Exception {
if (this.english==null) {
throw new Exception("请先构造Person");
}else{
return this.english;
}
}
}
|
package customViews;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;
import learn.kidsapp.learnmath.R;
public class StrokeTextView extends android.support.v7.widget.AppCompatTextView {
public int strokeColor;
public int strokeWidth;
public StrokeTextView(Context context) {
super(context);
}
public StrokeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView, 0, 0);
strokeColor = a.getColor(R.styleable.StrokeTextView_strokeColorVal, getResources().getColor(R.color.white, context.getTheme()) );
strokeWidth = a.getInt(R.styleable.StrokeTextView_strokeWidthVal, 10);
a.recycle();
}
public StrokeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void onDraw(Canvas canvas)
{
TextPaint paint = getPaint();
int textColor = getTextColors().getDefaultColor();
setTextColor(strokeColor);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Paint.Style.STROKE);
super.onDraw(canvas);
setTextColor(textColor);
paint.setStrokeWidth(0);
paint.setStyle(Paint.Style.FILL);
super.onDraw(canvas);
}
}
|
package com.kobotan.android.Vshkole.extendedElements;
import android.content.Context;
import android.graphics.Point;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
public class ExtendedViewPager extends ViewPager {
private static int sizeOfView;
public ExtendedViewPager(Context context) {
super(context);
}
public ExtendedViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public static void setSizeOfView(int sizeOfView) {
ExtendedViewPager.sizeOfView = sizeOfView;
}
@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof TouchImageView) {
return ((TouchImageView) v).canScrollHorizontallyFroyo(-dx);
} else {
return super.canScroll(v, checkV, dx, x, y);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height - sizeOfView, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
|
package com.tencent.mm.plugin.mall.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.tencent.mm.ab.l;
import com.tencent.mm.compatible.util.d;
import com.tencent.mm.g.a.nn;
import com.tencent.mm.model.q;
import com.tencent.mm.platformtools.y.a;
import com.tencent.mm.plugin.appbrand.n.e;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wallet_core.model.j;
import com.tencent.mm.plugin.wallet_core.model.mall.MallFunction;
import com.tencent.mm.plugin.wallet_core.model.mall.b;
import com.tencent.mm.plugin.wallet_core.model.o;
import com.tencent.mm.plugin.wxpay.a.c;
import com.tencent.mm.plugin.wxpay.a.f;
import com.tencent.mm.plugin.wxpay.a.g;
import com.tencent.mm.pluginsdk.k;
import com.tencent.mm.pluginsdk.wallet.i;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.mm.ui.ak;
import com.tencent.mm.ui.s;
import com.tencent.mm.ui.y;
import com.tencent.mm.wallet_core.ui.WalletBaseUI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
public abstract class MallIndexBaseUI extends WalletBaseUI implements a, j {
protected String fMk;
private String kUp = null;
private String kXX = null;
private ArrayList<MallFunction> kXY = null;
protected int kYc;
private TextView kZg = null;
protected ListView kZh = null;
private b kZi = null;
protected ImageView kZj = null;
protected ImageView kZk;
protected TextView kZl = null;
protected TextView kZm;
private int kZn = 0;
private boolean kZo = true;
private boolean kZp = false;
protected abstract void bbO();
protected abstract void bbP();
protected abstract void bbQ();
protected abstract boolean bbS();
protected abstract void bbW();
protected abstract void bbX();
protected abstract void bbZ();
protected abstract void bca();
protected abstract void cs(View view);
protected final int getLayoutId() {
return g.mall_index_ui;
}
public void onCreate(Bundle bundle) {
x.i("MicroMsg.MallIndexBaseUI", "onCreate");
super.onCreate(bundle);
if (!com.tencent.mm.kernel.g.Eg().Dx()) {
x.v("MicroMsg.MallIndexBaseUI", "MMCore is not ready");
finish();
}
com.tencent.mm.kernel.g.Ek();
int intValue = ((Integer) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sTs, Integer.valueOf(0))).intValue();
this.kYc = getIntent().getIntExtra("key_wallet_region", intValue);
this.fMk = getIntent().getStringExtra("key_uuid");
if (!bi.oW(this.fMk)) {
this.fMk = UUID.randomUUID().toString();
}
jr(495);
o.bPd();
com.tencent.mm.plugin.wallet_core.model.aa.a(this);
this.kXX = getIntent().getStringExtra("key_func_id");
x.i("MicroMsg.MallIndexBaseUI", "mFuncId:" + this.kXX + " wallet_region: " + this.kYc + " walletType: " + q.GM() + " default_region: " + intValue);
this.kUp = getIntent().getStringExtra("key_native_url");
x.i("MicroMsg.MallIndexBaseUI", "mNativeUrl:" + this.kUp);
if (!bbR()) {
if (getSupportActionBar() != null) {
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(c.mall_index_topbar_color));
}
if (d.fR(21)) {
getWindow().setStatusBarColor(getResources().getColor(c.wallet_mall_index_status_bar_color));
}
s.cqp();
ux(0);
x.i("MicroMsg.MallIndexBaseUI", "index Oncreate");
bbO();
initView();
com.tencent.mm.plugin.wallet_core.model.mall.c.bPN();
bbP();
x.i("MicroMsg.MallIndexBaseUI", "hy: use default controller for MallIndexUI");
bbQ();
if (q.GS()) {
x.e("MicroMsg.MallIndexBaseUI", "it is payu account ,not initFingerPrint");
} else {
k kVar = (k) com.tencent.mm.kernel.g.l(k.class);
if (kVar != null) {
x.i("MicroMsg.MallIndexBaseUI", "IFingerPrintMgr is not null, do showFingerPrintEntrance()");
kVar.dh(this);
} else {
x.e("MicroMsg.MallIndexBaseUI", "IFingerPrintMgr is not null");
}
}
com.tencent.mm.wallet_core.c.q.fu(1, 0);
h.mEJ.h(11850, new Object[]{Integer.valueOf(1), Integer.valueOf(0)});
if (VERSION.SDK_INT >= 16) {
getWindow().getDecorView().setSystemUiVisibility(1280);
}
lF(this.mController.tml.getResources().getColor(c.transparent));
}
}
public final boolean bbR() {
if (bi.oW(this.kXX) && bi.oW(this.kUp)) {
return false;
}
return true;
}
public void onResume() {
boolean z = true;
super.onResume();
i.Cx(1);
x.i("MicroMsg.MallIndexBaseUI", "index onResume");
if (!com.tencent.mm.kernel.g.Eg().Dx()) {
x.v("MicroMsg.MallIndexBaseUI", "MMCore is not ready");
finish();
}
if (bbR()) {
this.kXY = com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc);
if (this.kXY == null || this.kXY.size() <= 0) {
x.i("MicroMsg.MallIndexBaseUI", "mFunctionList == null");
try {
if (getIntent().getIntExtra("key_scene", 0) == 1 || !bi.oW(this.kUp)) {
a(new com.tencent.mm.plugin.mall.a.a(this.kYc, b.bPJ()), true, false);
return;
}
String stringExtra = getIntent().getStringExtra("key_url");
if (stringExtra == null) {
stringExtra = "";
}
a(new com.tencent.mm.plugin.mall.a.a(this.kYc, b.bPJ(), getIntent().getStringExtra("key_app_id"), this.kXX, stringExtra), true, false);
return;
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.MallIndexBaseUI", e, "", new Object[0]);
bbV();
return;
}
}
MallFunction bx = bx(this.kXY);
if (bx == null) {
bx = by(this.kXY);
}
a(bx, -1);
finish();
return;
}
bbS();
x.d("MicroMsg.MallIndexBaseUI", "initFunctionList");
if (com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc) == null) {
a(new com.tencent.mm.plugin.mall.a.a(this.kYc, b.bPJ()), true, false);
x.e("MicroMsg.MallIndexBaseUI", "funcitonlist invalid");
z = false;
} else {
a(new com.tencent.mm.plugin.mall.a.a(this.kYc, b.bPJ()), false, false);
this.kXY = com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc);
}
if (z) {
x.i("MicroMsg.MallIndexBaseUI", "has data");
aL();
}
}
private void bbT() {
boolean booleanExtra = getIntent().getBooleanExtra("key_wallet_has_red", false);
if (this.kZh.getChildCount() != 0) {
x.i("MicroMsg.MallIndexBaseUI", "initCheckNew %s fpos %s top %s", new Object[]{Boolean.valueOf(booleanExtra), Integer.valueOf(this.kZh.getFirstVisiblePosition()), Integer.valueOf(this.kZh.getChildAt(0).getTop())});
if (this.kZh.getFirstVisiblePosition() == 0 && r2 == 0 && booleanExtra && !this.kZp && this.kXY != null) {
this.kZp = true;
int headerViewsCount = this.kZh.getHeaderViewsCount() + this.kZi.getCount();
List list = this.kZi.kYB;
if (list != null) {
for (int size = list.size() - 1; size > 0; size--) {
Iterator it = ((ArrayList) list.get(size)).iterator();
while (it.hasNext()) {
b.c cVar = (b.c) it.next();
if (cVar != null && cVar.kZe != null && b.a(cVar.kZe)) {
x.i("MicroMsg.MallIndexBaseUI", "get listview show top %s bottom %s redPos: %d", new Object[]{Integer.valueOf(this.kZh.getFirstVisiblePosition()), Integer.valueOf(this.kZh.getLastVisiblePosition()), Integer.valueOf(headerViewsCount)});
if (headerViewsCount < this.kZh.getFirstVisiblePosition() || headerViewsCount > r1) {
size = a.bbM();
int bbL = (a.bbL() + (a.bbK() * (headerViewsCount + 1))) + size;
if (headerViewsCount > 2) {
bbL += size;
}
if (headerViewsCount > 3) {
bbL += size;
}
size = (bbL + (a.bbK() / 3)) - this.kZh.getScrollY();
bbL = ak.gu(this).y;
if (ak.gt(this)) {
bbL -= ak.gs(this);
}
if (getSupportActionBar() != null) {
bbL -= getSupportActionBar().getHeight();
}
this.kZh.smoothScrollBy(size - bbL, 1000);
return;
}
return;
}
}
headerViewsCount--;
}
}
}
}
}
public void a(MallFunction mallFunction, int i) {
int i2;
if (mallFunction != null && i >= 0) {
String str = "";
if (!(mallFunction.prU == null || bi.oW(mallFunction.prU.oqH))) {
str = mallFunction.prU.oqH;
}
int size = this.kXY == null ? 0 : this.kXY.size();
boolean a = b.a(mallFunction);
h hVar = h.mEJ;
Object[] objArr = new Object[6];
objArr[0] = mallFunction.moy;
objArr[1] = Integer.valueOf(size);
objArr[2] = Integer.valueOf(0);
objArr[3] = Integer.valueOf(i);
objArr[4] = str;
if (a) {
i2 = 2;
} else {
i2 = 1;
}
objArr[5] = Integer.valueOf(i2);
hVar.h(10881, objArr);
}
if (mallFunction == null || bi.oW(mallFunction.ceR) || !((e) com.tencent.mm.kernel.g.l(e.class)).uo(mallFunction.ceR)) {
if (mallFunction != null) {
com.tencent.mm.plugin.wallet_core.model.mall.c.bPK().Pf(mallFunction.moy);
com.tencent.mm.plugin.wallet_core.model.mall.d.bPO().Pf(mallFunction.moy);
if (mallFunction.prU != null) {
com.tencent.mm.plugin.wallet_core.model.mall.c.bPK();
com.tencent.mm.plugin.wallet_core.model.mall.c.c(mallFunction);
}
if ("wxpay://bizmall/mobile_recharge".equals(mallFunction.ceR)) {
i2 = 0;
} else if ("wxpay://bizmall/weixin_hongbao".equals(mallFunction.ceR)) {
i2 = 4;
} else if ("wxpay://bizmall/weixin_scan_qrcode".equals(mallFunction.ceR)) {
i2 = 8;
} else if ("wxpay://bizmall/weixin_transfer".equals(mallFunction.ceR)) {
i2 = 5;
} else if ("wxpay://bizmall/weixin_offline_pay".equals(mallFunction.ceR)) {
i2 = 6;
} else if ("wxpay://bizmall/old_mobile_recharge".equals(mallFunction.ceR)) {
i2 = 7;
} else if (!bi.oW(mallFunction.kck)) {
i2 = 1;
} else if ("wxpay://bizmall/f2f_hongbao".equals(mallFunction.ceR)) {
i2 = 9;
} else {
x.w("MicroMsg.MallIndexUIHelper", "doSelectFunction no jump");
i2 = 2;
}
} else {
i2 = 3;
}
x.i("MicroMsg.MallIndexBaseUI", "functionType : " + i2);
Intent intent;
switch (i2) {
case 0:
intent = new Intent();
if (bbR()) {
intent.putExtra("key_is_hide_progress", true);
}
intent.putExtra("key_func_info", mallFunction);
com.tencent.mm.bg.d.b(this, "recharge", ".ui.PhoneRechargeUI", intent);
com.tencent.mm.wallet_core.c.q.fu(15, 0);
return;
case 1:
com.tencent.mm.kernel.g.Ek();
this.kYc = ((Integer) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sTs, Integer.valueOf(0))).intValue();
intent = new Intent();
intent.putExtra("rawUrl", mallFunction.kck);
intent.putExtra("geta8key_username", q.GF());
intent.putExtra("pay_channel", 1);
intent.putExtra("KPublisherId", "pay_wallet");
intent.putExtra("key_download_restrict", mallFunction.prW);
intent.putExtra("key_wallet_region", this.kYc);
intent.putExtra("key_function_id", mallFunction.moy);
intent.putExtra("geta8key_scene", 46);
com.tencent.mm.bg.d.b(this, "webview", "com.tencent.mm.plugin.webview.ui.tools.WebViewUI", intent);
return;
case 2:
x.w("MicroMsg.MallIndexBaseUI", "doSelectFunction no jump");
return;
case 3:
x.w("MicroMsg.MallIndexBaseUI", "doSelectFunction do nothing");
com.tencent.mm.ui.base.s.makeText(this, "fuction list error", 1).show();
return;
case 4:
h.mEJ.h(11701, new Object[]{Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(1)});
intent = new Intent();
intent.putExtra("pay_channel", 1);
com.tencent.mm.bg.d.b(this, "luckymoney", ".ui.LuckyMoneyIndexUI", intent);
com.tencent.mm.wallet_core.c.q.fu(13, 0);
h.mEJ.h(11850, new Object[]{Integer.valueOf(4), Integer.valueOf(0)});
return;
case 5:
h.mEJ.h(11458, new Object[]{Integer.valueOf(1)});
if (q.GS()) {
List linkedList = new LinkedList();
List linkedList2 = new LinkedList();
linkedList.add(getString(com.tencent.mm.plugin.wxpay.a.i.remittance_title));
linkedList2.add(Integer.valueOf(0));
linkedList.add(getString(com.tencent.mm.plugin.wxpay.a.i.collect_title));
linkedList2.add(Integer.valueOf(1));
com.tencent.mm.ui.base.h.a((Context) this, getString(com.tencent.mm.plugin.wxpay.a.i.remittance_collect_title), linkedList, linkedList2, null, true, new 4(this));
} else {
com.tencent.mm.kernel.g.Ek();
if (((Boolean) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sPD, Boolean.valueOf(false))).booleanValue()) {
bbY();
} else {
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sPD, Boolean.valueOf(true));
com.tencent.mm.ui.base.h.a((Context) this, getString(com.tencent.mm.plugin.wxpay.a.i.wallet_index_ui_ftf_notice), "", new 5(this));
}
}
com.tencent.mm.wallet_core.c.q.fu(14, 0);
h.mEJ.h(11850, new Object[]{Integer.valueOf(3), Integer.valueOf(0)});
return;
case 6:
intent = new Intent();
intent.putExtra("key_from_scene", 1);
com.tencent.mm.bg.d.b(this.mController.tml, "offline", ".ui.WalletOfflineEntranceUI", intent);
com.tencent.mm.wallet_core.c.q.fu(9, 0);
h.mEJ.h(11850, new Object[]{Integer.valueOf(5), Integer.valueOf(0)});
return;
case 7:
intent = new Intent();
if (bbR()) {
intent.putExtra("key_is_hide_progress", true);
}
intent.putExtra("key_func_info", mallFunction);
com.tencent.mm.bg.d.b(this, "recharge", ".ui.RechargeUI", intent);
return;
case 8:
intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 1);
com.tencent.mm.bg.d.b(this.mController.tml, "scanner", ".ui.BaseScanUI", intent);
return;
case 9:
com.tencent.mm.bg.d.A(this.mController.tml, "luckymoney", ".f2f.ui.LuckyMoneyF2FQRCodeUI");
return;
default:
return;
}
}
x.i("MicroMsg.MallIndexBaseUI", "handleFunction, intercept by AppBrandNativeLink, nativeUrl = %s", new Object[]{mallFunction.ceR});
com.tencent.mm.plugin.wallet_core.model.mall.c.bPK().Pf(mallFunction.moy);
com.tencent.mm.plugin.wallet_core.model.mall.d.bPO().Pf(mallFunction.moy);
if (mallFunction.prU != null) {
com.tencent.mm.plugin.wallet_core.model.mall.c.bPK();
com.tencent.mm.plugin.wallet_core.model.mall.c.c(mallFunction);
}
}
public void onDestroy() {
js(495);
o.bPd();
com.tencent.mm.plugin.wallet_core.model.aa.b(this);
super.onDestroy();
}
public boolean d(int i, int i2, String str, l lVar) {
x.d("MicroMsg.MallIndexBaseUI", "onOtherSceneEnd");
if (lVar instanceof com.tencent.mm.plugin.wallet_core.c.b.a) {
x.d("MicroMsg.MallIndexBaseUI", "hy: query bound scene end");
if (i != 0 || i2 != 0) {
finish();
return true;
} else if (this.kZo) {
this.kZo = false;
if (o.bOS().bPU().bPp()) {
com.tencent.mm.wallet_core.a.b(this, "PayUOpenProcess", null);
return true;
}
}
}
switch (lVar.getType()) {
case 495:
com.tencent.mm.plugin.mall.a.a aVar = (com.tencent.mm.plugin.mall.a.a) lVar;
if (aVar.kYc != this.kYc) {
x.i("MicroMsg.MallIndexBaseUI", "pass wallet local: %d cgi: %d", new Object[]{Integer.valueOf(this.kYc), Integer.valueOf(aVar.kYc)});
}
if (bbR()) {
x.d("MicroMsg.MallIndexBaseUI", "errorType:%d | errCode:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
if (i != 0 || i2 != 0 || aVar.kXY == null || aVar.kXY.size() <= 0) {
bbV();
return true;
}
MallFunction bx;
if (getIntent().getIntExtra("key_scene", 0) == 1) {
bx = bx(aVar.kXY);
if (bx != null) {
a(bx, -1);
}
} else if (!bi.oW(this.kUp)) {
x.d("MicroMsg.MallIndexBaseUI", "NativeUrl: %s", new Object[]{this.kUp});
bx = by(aVar.kXY);
if (bx != null) {
a(bx, -1);
} else {
bbV();
return true;
}
} else if (aVar.kXY != null && aVar.kXY.size() > 0) {
x.i("MicroMsg.MallIndexBaseUI", "functionScene.mFunctionList != null");
a(bx(aVar.kXY), -1);
} else if (com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc) == null || com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc).size() <= 0) {
x.e("MicroMsg.MallIndexBaseUI", "SubCoreMall.getCore().getFunctionList() == null");
} else {
x.i("MicroMsg.MallIndexBaseUI", "SubCoreMall.getCore().getFunctionList() != null");
a(bx(com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc)), -1);
}
setResult(-1);
finish();
return true;
}
if (i == 0 && i2 == 0 && com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc) != null && aVar.kXY != null && aVar.kXY.size() > 0) {
this.kXY = com.tencent.mm.plugin.mall.a.d.bbJ().sr(this.kYc);
x.i("MicroMsg.MallIndexBaseUI", "get from server now! " + this.kYc + " " + this.kXY.size());
com.tencent.mm.plugin.wallet_core.model.mall.c.bPK().Q(this.kXY);
}
aL();
bbT();
return true;
default:
return false;
}
}
private MallFunction bx(List<MallFunction> list) {
if (list == null || list.size() == 0 || TextUtils.isEmpty(this.kXX)) {
return null;
}
int i = 0;
while (true) {
int i2 = i;
if (i2 >= list.size()) {
return null;
}
MallFunction mallFunction = (MallFunction) list.get(i2);
if (mallFunction != null && this.kXX.equals(mallFunction.moy)) {
return mallFunction;
}
i = i2 + 1;
}
}
private MallFunction by(List<MallFunction> list) {
if (list == null || list.size() == 0 || TextUtils.isEmpty(this.kUp)) {
return null;
}
int i = 0;
while (true) {
int i2 = i;
if (i2 >= list.size()) {
return null;
}
MallFunction mallFunction = (MallFunction) list.get(i2);
if (mallFunction != null && this.kUp.equals(mallFunction.ceR)) {
return mallFunction;
}
i = i2 + 1;
}
}
protected final boolean aWj() {
if (!bbR()) {
aL();
}
return true;
}
public final boolean bbU() {
return false;
}
public final void m(String str, Bitmap bitmap) {
}
private void bbV() {
setResult(0);
finish();
}
public final void aL() {
showOptionMenu(true);
b bVar = this.kZi;
ArrayList arrayList = this.kXY;
bVar.kYB.clear();
if (arrayList != null) {
int i;
int i2;
int i3 = 0;
while (i3 < arrayList.size()) {
ArrayList arrayList2 = new ArrayList();
i = 0;
while (i < 3 && i3 + i < arrayList.size()) {
int i4 = i3 + i;
if (i > 0) {
i2 = (i3 + i) - 1;
if (i2 >= 0 && ((MallFunction) arrayList.get(i2)).type != ((MallFunction) arrayList.get(i4)).type) {
break;
}
}
b.c cVar = new b.c(bVar);
cVar.kZf = i3 + i;
cVar.kZe = (MallFunction) arrayList.get(i3 + i);
arrayList2.add(cVar);
i++;
}
if (arrayList2.size() > 0) {
bVar.kYB.add(arrayList2);
}
i3 += i;
}
bVar.kYE = 0;
bVar.kYF = 0;
i = -1;
for (ArrayList arrayList3 : bVar.kYB) {
if (arrayList3.size() > 0) {
if (i != -1 && i != ((b.c) arrayList3.get(0)).kZe.type) {
break;
}
bVar.kYE += arrayList3.size();
bVar.kYF++;
i2 = ((b.c) arrayList3.get(0)).kZe.type;
} else {
i2 = i;
}
i = i2;
}
bVar.kYF--;
}
bVar.kYb = com.tencent.mm.plugin.mall.a.d.bbJ().sq(bVar.kYc).kYb;
bVar.kYG = bVar.bbN();
x.i("MicroMsg.FunctionListAdapter", "hasMoreNewAtFirstSectionBottom: %s", new Object[]{Boolean.valueOf(bVar.kYG)});
bVar.notifyDataSetChanged();
bbX();
bbZ();
if (this.kZg != null) {
this.kZg.setVisibility(8);
}
bca();
}
public void onStop() {
super.onStop();
}
public final void initView() {
x.d("MicroMsg.MallIndexBaseUI", "index initView");
setBackBtn(new 1(this));
a.f(this);
this.kZh = (ListView) findViewById(f.mall_index_function_list);
View inflate = y.gq(this).inflate(g.mall_index_stub_with_bankcard, null);
this.kZh.addHeaderView(inflate);
LayoutParams layoutParams = (AbsListView.LayoutParams) inflate.getLayoutParams();
if (layoutParams == null) {
layoutParams = new AbsListView.LayoutParams(-1, -2);
}
layoutParams.height = a.bbL();
inflate.setLayoutParams(layoutParams);
this.kZi = new b(this, this.kYc);
this.kZh.setAdapter(this.kZi);
this.kZi.kYC = new 2(this);
cs(inflate);
this.kZm = (TextView) findViewById(f.banner_tips);
bbW();
this.kZh.setOnScrollListener(new 3(this));
}
private void bbY() {
if (q.GS()) {
com.tencent.mm.wallet_core.a.b(this.mController.tml, "PayURemittanceProcess", null);
return;
}
Bundle bundle = new Bundle();
bundle.putInt("pay_channel", 1);
com.tencent.mm.wallet_core.a.b(this.mController.tml, "RemittanceProcess", bundle);
}
public void finish() {
super.finish();
}
protected final int getForceOrientation() {
return 1;
}
public final void ss(int i) {
if (i == 12 && this.kZl != null) {
bbX();
}
}
protected void onActivityResult(int i, int i2, Intent intent) {
if (i == 1) {
com.tencent.mm.kernel.g.Ek();
this.kYc = ((Integer) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sTs, Integer.valueOf(0))).intValue();
if (i2 != -1) {
return;
}
if (q.GT()) {
finish();
return;
}
finish();
nn nnVar = new nn();
nnVar.bYA.context = this.mController.tml;
com.tencent.mm.sdk.b.a.sFg.m(nnVar);
}
}
protected final void bcb() {
com.tencent.mm.bg.d.c(this, "wallet_core", ".ui.WalletSwitchWalletCurrencyUI", 1);
}
protected static void u(Activity activity) {
if (o.bOW().bPw().bPn()) {
Intent intent = new Intent();
intent.putExtra("rawUrl", "https://wx.tenpay.com/userroll/readtemplate?t=userroll/index_tmpl");
com.tencent.mm.bg.d.b(activity, "webview", ".ui.tools.WebViewUI", intent);
} else {
com.tencent.mm.wallet_core.a.b(activity, "ShowOrdersInfoProcess", null);
}
com.tencent.mm.wallet_core.ui.e.He(20);
}
}
|
package hugbo;
import java.util.ArrayList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.PartialResultException;
public class Calculator {
public static int add(String text) throws Exception
{
if (text.contains("-"))
{
lessThanZero(text);
}
if(text.startsWith("//"))
{
if(text.charAt(3) == '[')
{
return sum(multiDelimeter(text));
}
else
{
return sum(delimeter(text));
}
}
else if(text.equals(""))
{
return 0;
}
else if(text.contains(",") || text.contains("\n"))
{
return sum(splitNumbers(text));
}
else
{
return Integer.parseInt(text);
}
}
public static String[] multiDelimeter(String numbers)
{
int end = numbers.indexOf(']');
int first = numbers.indexOf('[') + 1;
String longDelimert = numbers.substring(first, end);
String finalDelimeter = longDelimert.valueOf(longDelimert.charAt(0));
System.out.println(finalDelimeter);
return numbers.split(finalDelimeter);
}
private static String[] delimeter(String numbers)
{
Matcher regex = Pattern.compile("//(.*)\n(.*)").matcher(numbers);
regex.matches();
String delimeter = regex.group(1);
String textToInts = regex.group(2);
return textToInts.split(delimeter);
}
private static String[] splitNumbers (String numbers)
{
return numbers.split(",|\n");
}
private static void lessThanZero(String numbers) throws Exception
{
String negatives = null;
for(int i = 0; i < numbers.length(); i++)
{
if(numbers.charAt(i) == '-')
{
negatives += numbers.charAt(i);
negatives += numbers.charAt(i+1);
i+=1;
}
}
throw new Exception("ERROR! NO NEGATIVE NUMBERS: " + negatives);
}
private static int sum(String[] numbers)
{
int total = 0;
for(String number : numbers)
{
if(Integer.parseInt(number) <= 1000)
{
total += Integer.parseInt(number);
}
}
return total;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.multiDelimeter("//[***]\n1***2***3");
}
}
|
package com.hellofresh.challenge1;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SelectBrowserType {
public static WebDriver driver;
public static WebDriverWait wait;
public String existingUserEmail = "mflsqe@naic.org";
public String existingUserPassword = "mflsqe1234";
public WebDriver initializeDriver() throws IOException
{
Properties prop=new Properties();
FileInputStream fis=new FileInputStream("C:\\Users\\GeethuKarthu\\web-test-naic\\src\\main\\java\\com\\hellofresh\\challenge1\\InputData.properties");
prop.load(fis);
String browserType = prop.getProperty("Browser");
System.out.println(browserType);
if(browserType.equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\GeethuKarthu\\web-test-naic\\src\\test\\java\\resources\\chromedriver.exe");
driver= new ChromeDriver();
}
else if(browserType.equals("Firefox"))
{
System.out.println("Initialization of FireFox Browser code goes here...");
driver=new FirefoxDriver();
}
else if(browserType.equals("InternetExplorer"))
{
System.out.println("Initialization of InternetExplorer Browser code goes here...");
driver=new InternetExplorerDriver();
}
else
{
System.out.println("Incorrect Browser selection...");
}
wait = new WebDriverWait(driver, 10, 50);
return driver;
}
} |
package com.dmp.beans;
public class Traitement {
public Traitement() {
super();
}
public Traitement(int idTraitement, String nomsMedicament, String posologie, String voieAdministration,
String conditionAdministration, String observation) {
super();
this.idTraitement = idTraitement;
this.nomsMedicament = nomsMedicament;
this.posologie = posologie;
this.voieAdministration = voieAdministration;
this.conditionAdministration = conditionAdministration;
this.observation = observation;
}
private int idTraitement;
private String nomsMedicament;
private String posologie;
private String voieAdministration;
private String conditionAdministration;
private String observation;
public int getIdTraitement() {
return idTraitement;
}
public void setIdTraitement(int idTraitement) {
this.idTraitement = idTraitement;
}
public String getNomsMedicament() {
return nomsMedicament;
}
public void setNomsMedicament(String nomsMedicament) {
this.nomsMedicament = nomsMedicament;
}
public String getPosologie() {
return posologie;
}
public void setPosologie(String posologie) {
this.posologie = posologie;
}
public String getVoieAdministration() {
return voieAdministration;
}
public void setVoieAdministration(String voieAdministration) {
this.voieAdministration = voieAdministration;
}
public String getConditionAdministration() {
return conditionAdministration;
}
public void setConditionAdministration(String conditionAdministration) {
this.conditionAdministration = conditionAdministration;
}
public String getObservation() {
return observation;
}
public void setObservation(String observation) {
this.observation = observation;
}
} |
package org.rhokk.hh.sealand.http;
public class ServerResponse {
private final int _responseCode;
private ServerResponse ( final int responseCode ) {
super();
_responseCode = responseCode;
}
public static ServerResponse create(int statusCode) {
return new ServerResponse( statusCode );
}
public int getResponseCode() {
return _responseCode;
}
public static ServerResponse createError() {
return new ServerResponse( -1 );
}
public boolean isSuccess() {
return _responseCode >= 200 && _responseCode < 400;
}
}
|
package dot.empire.counter;
/**
* Preference flags. Created by siD on 23 Jan 2018.
*
* @author Matthew Van der Bijl
*/
public enum Preferences {
FLAG,
ACTIVE,
BG_COLOUR,
BUTTON_COLOUR,
TEXT_COLOUR;
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* JbpmToken generated by hbm2java
*/
public class JbpmToken implements java.io.Serializable {
private BigDecimal id;
private JbpmNode jbpmNode;
private JbpmProcessinstance jbpmProcessinstanceBySubprocessinstance;
private JbpmProcessinstance jbpmProcessinstanceByProcessinstance;
private JbpmToken jbpmToken;
private long version;
private String name;
private Date start;
private Date end;
private Date nodeenter;
private Long nextlogindex;
private Boolean isabletoreactivateparent;
private Boolean isterminationimplicit;
private Boolean issuspended;
private Set jbpmProcessinstancesForSuperprocesstoken = new HashSet(0);
private Set jbpmProcessinstancesForRoottoken = new HashSet(0);
private Set jbpmTimers = new HashSet(0);
private Set jbpmMessages = new HashSet(0);
private Set jbpmTaskinstances = new HashSet(0);
private Set jbpmVariableinstances = new HashSet(0);
private Set jbpmLogsForChild = new HashSet(0);
private Set jbpmLogsForToken = new HashSet(0);
private Set jbpmTokenvariablemaps = new HashSet(0);
private Set jbpmComments = new HashSet(0);
private Set jbpmTokens = new HashSet(0);
public JbpmToken() {
}
public JbpmToken(BigDecimal id, long version) {
this.id = id;
this.version = version;
}
public JbpmToken(BigDecimal id, JbpmNode jbpmNode, JbpmProcessinstance jbpmProcessinstanceBySubprocessinstance,
JbpmProcessinstance jbpmProcessinstanceByProcessinstance, JbpmToken jbpmToken, long version, String name,
Date start, Date end, Date nodeenter, Long nextlogindex, Boolean isabletoreactivateparent,
Boolean isterminationimplicit, Boolean issuspended, Set jbpmProcessinstancesForSuperprocesstoken,
Set jbpmProcessinstancesForRoottoken, Set jbpmTimers, Set jbpmMessages, Set jbpmTaskinstances,
Set jbpmVariableinstances, Set jbpmLogsForChild, Set jbpmLogsForToken, Set jbpmTokenvariablemaps,
Set jbpmComments, Set jbpmTokens) {
this.id = id;
this.jbpmNode = jbpmNode;
this.jbpmProcessinstanceBySubprocessinstance = jbpmProcessinstanceBySubprocessinstance;
this.jbpmProcessinstanceByProcessinstance = jbpmProcessinstanceByProcessinstance;
this.jbpmToken = jbpmToken;
this.version = version;
this.name = name;
this.start = start;
this.end = end;
this.nodeenter = nodeenter;
this.nextlogindex = nextlogindex;
this.isabletoreactivateparent = isabletoreactivateparent;
this.isterminationimplicit = isterminationimplicit;
this.issuspended = issuspended;
this.jbpmProcessinstancesForSuperprocesstoken = jbpmProcessinstancesForSuperprocesstoken;
this.jbpmProcessinstancesForRoottoken = jbpmProcessinstancesForRoottoken;
this.jbpmTimers = jbpmTimers;
this.jbpmMessages = jbpmMessages;
this.jbpmTaskinstances = jbpmTaskinstances;
this.jbpmVariableinstances = jbpmVariableinstances;
this.jbpmLogsForChild = jbpmLogsForChild;
this.jbpmLogsForToken = jbpmLogsForToken;
this.jbpmTokenvariablemaps = jbpmTokenvariablemaps;
this.jbpmComments = jbpmComments;
this.jbpmTokens = jbpmTokens;
}
public BigDecimal getId() {
return this.id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public JbpmNode getJbpmNode() {
return this.jbpmNode;
}
public void setJbpmNode(JbpmNode jbpmNode) {
this.jbpmNode = jbpmNode;
}
public JbpmProcessinstance getJbpmProcessinstanceBySubprocessinstance() {
return this.jbpmProcessinstanceBySubprocessinstance;
}
public void setJbpmProcessinstanceBySubprocessinstance(
JbpmProcessinstance jbpmProcessinstanceBySubprocessinstance) {
this.jbpmProcessinstanceBySubprocessinstance = jbpmProcessinstanceBySubprocessinstance;
}
public JbpmProcessinstance getJbpmProcessinstanceByProcessinstance() {
return this.jbpmProcessinstanceByProcessinstance;
}
public void setJbpmProcessinstanceByProcessinstance(JbpmProcessinstance jbpmProcessinstanceByProcessinstance) {
this.jbpmProcessinstanceByProcessinstance = jbpmProcessinstanceByProcessinstance;
}
public JbpmToken getJbpmToken() {
return this.jbpmToken;
}
public void setJbpmToken(JbpmToken jbpmToken) {
this.jbpmToken = jbpmToken;
}
public long getVersion() {
return this.version;
}
public void setVersion(long version) {
this.version = version;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Date getStart() {
return this.start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return this.end;
}
public void setEnd(Date end) {
this.end = end;
}
public Date getNodeenter() {
return this.nodeenter;
}
public void setNodeenter(Date nodeenter) {
this.nodeenter = nodeenter;
}
public Long getNextlogindex() {
return this.nextlogindex;
}
public void setNextlogindex(Long nextlogindex) {
this.nextlogindex = nextlogindex;
}
public Boolean getIsabletoreactivateparent() {
return this.isabletoreactivateparent;
}
public void setIsabletoreactivateparent(Boolean isabletoreactivateparent) {
this.isabletoreactivateparent = isabletoreactivateparent;
}
public Boolean getIsterminationimplicit() {
return this.isterminationimplicit;
}
public void setIsterminationimplicit(Boolean isterminationimplicit) {
this.isterminationimplicit = isterminationimplicit;
}
public Boolean getIssuspended() {
return this.issuspended;
}
public void setIssuspended(Boolean issuspended) {
this.issuspended = issuspended;
}
public Set getJbpmProcessinstancesForSuperprocesstoken() {
return this.jbpmProcessinstancesForSuperprocesstoken;
}
public void setJbpmProcessinstancesForSuperprocesstoken(Set jbpmProcessinstancesForSuperprocesstoken) {
this.jbpmProcessinstancesForSuperprocesstoken = jbpmProcessinstancesForSuperprocesstoken;
}
public Set getJbpmProcessinstancesForRoottoken() {
return this.jbpmProcessinstancesForRoottoken;
}
public void setJbpmProcessinstancesForRoottoken(Set jbpmProcessinstancesForRoottoken) {
this.jbpmProcessinstancesForRoottoken = jbpmProcessinstancesForRoottoken;
}
public Set getJbpmTimers() {
return this.jbpmTimers;
}
public void setJbpmTimers(Set jbpmTimers) {
this.jbpmTimers = jbpmTimers;
}
public Set getJbpmMessages() {
return this.jbpmMessages;
}
public void setJbpmMessages(Set jbpmMessages) {
this.jbpmMessages = jbpmMessages;
}
public Set getJbpmTaskinstances() {
return this.jbpmTaskinstances;
}
public void setJbpmTaskinstances(Set jbpmTaskinstances) {
this.jbpmTaskinstances = jbpmTaskinstances;
}
public Set getJbpmVariableinstances() {
return this.jbpmVariableinstances;
}
public void setJbpmVariableinstances(Set jbpmVariableinstances) {
this.jbpmVariableinstances = jbpmVariableinstances;
}
public Set getJbpmLogsForChild() {
return this.jbpmLogsForChild;
}
public void setJbpmLogsForChild(Set jbpmLogsForChild) {
this.jbpmLogsForChild = jbpmLogsForChild;
}
public Set getJbpmLogsForToken() {
return this.jbpmLogsForToken;
}
public void setJbpmLogsForToken(Set jbpmLogsForToken) {
this.jbpmLogsForToken = jbpmLogsForToken;
}
public Set getJbpmTokenvariablemaps() {
return this.jbpmTokenvariablemaps;
}
public void setJbpmTokenvariablemaps(Set jbpmTokenvariablemaps) {
this.jbpmTokenvariablemaps = jbpmTokenvariablemaps;
}
public Set getJbpmComments() {
return this.jbpmComments;
}
public void setJbpmComments(Set jbpmComments) {
this.jbpmComments = jbpmComments;
}
public Set getJbpmTokens() {
return this.jbpmTokens;
}
public void setJbpmTokens(Set jbpmTokens) {
this.jbpmTokens = jbpmTokens;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.