text
stringlengths 10
2.72M
|
|---|
/*
* Copyright (C) 2012~2016 dinstone<dinstone@163.com>
*
* 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.dinstone.beanstalkc;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author guojf
* @version 1.0.0.2013-12-31
*/
public abstract class StatsInfo {
public static AtomicInteger sendCount = new AtomicInteger();
public static AtomicInteger sendError = new AtomicInteger();
public static AtomicLong sendTimes = new AtomicLong();
public static AtomicInteger receiveCount = new AtomicInteger();
public static AtomicInteger receiveError = new AtomicInteger();
public static String getView() {
return "Send[" + sendCount.get() + ":" + sendTimes.get() + ":" + sendError.get() + "]; Receive["
+ receiveCount.get() + ":" + receiveError.get() + "]";
}
}
|
package test;
public enum SUIT {
SPADES, DIAMONDS, CLUBS, HEARTS
}
|
package leader.view.component;
import leader.view.ViewUtil;
import javax.swing.*;
public class TitleLabel extends JLabel {
public TitleLabel(String text){
super(text);
setFont(ViewUtil.TITLE_FONT);
}
}
|
package com.example.demo.pay.service.impl;
import com.example.demo.pay.model.WxTrade;
import com.example.demo.pay.model.WxpayParam;
import com.example.demo.pay.service.WxPayService;
import com.example.demo.pay.service.WxTradeService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* @author Smart
* @title: WxPayServiceImpl
* @projectName demo
* @description: TODO
* @date 2020/1/1511:11
*/
@Service
public class WxPayServiceImpl implements WxPayService {
@Autowired
private WxTradeService wxTradeService;
@Autowired
private WxPayConfig wxPayConfig;
@Override
public String payBack(String notifyData) {
String xmlBack = "";
Map<String, String> notifyMap = null;
try {
WXPay wxpay = new WXPay(wxPayConfig);
notifyMap = WXPayUtil.xmlToMap(notifyData); // 转换成map
if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
// 签名正确
// 进行处理。
// 注意特殊情况:订单已经退款,但收到了支付结果成功的通知,不应把商户侧订单状态从退款改成支付成功
String return_code = notifyMap.get("return_code");//状态
String out_trade_no = notifyMap.get("out_trade_no");//订单号
if (out_trade_no == null) {
xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
return xmlBack;
}
wxTradeService.updateWxTradeStatus(out_trade_no);
WxTrade wxTrade = wxTradeService.selectByTradeNo(out_trade_no);
if (wxTrade!=null) {//微信支付
//this.updateSometings(wxTrade.getUserId(), wxTrade.getMemberId(), "1");
//业务处理
xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[SUCCESS]]></return_msg>" + "</xml> ";
return xmlBack;
}
} else {
xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
return xmlBack;
}
} catch (Exception e) {
e.printStackTrace();
xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
return xmlBack;
}
@Override
public Map<String, String> creatOrder(WxTrade wxTrade) throws Exception {
WxpayParam wxpayParam = new WxpayParam();
wxTradeService.insert(wxTrade);
BigDecimal totalPrice = new BigDecimal(wxTrade.getTotalFee()); //此时的单位是元
String Fee = totalPrice.multiply(new BigDecimal(100)).toBigInteger().toString();//分
wxpayParam.setTotalFee(Fee);
WxPayConfig ourWxPayConfig = new WxPayConfig();
WXPay wxPay = new WXPay(ourWxPayConfig);
//根据微信支付api来设置
Map<String, String> data = new HashMap<>();
data.put("appid", ourWxPayConfig.getAppID());
data.put("mch_id", ourWxPayConfig.getMchID()); //商户号
data.put("trade_type", "APP"); //支付场景 APP 微信app支付 JSAPI 公众号支付 NATIVE 扫码支付
data.put("notify_url", ourWxPayConfig.getNotifyUrl()); //回调地址
data.put("spbill_create_ip", "127.0.0.1"); //终端ip
data.put("total_fee", wxpayParam.getTotalFee()); //订单总金额wxpayParam.getTotalFee()
data.put("fee_type", "CNY"); //默认人民币
data.put("out_trade_no", wxTrade.getTradeNo()); //交易号wxpayParam.getOutTradeNo()
data.put("body", wxpayParam.getBody());
data.put("nonce_str", "bfrhncjkfdkfd"); // 随机字符串小于32位
String s = WXPayUtil.generateSignature(data, ourWxPayConfig.getKey()); //签名
data.put("sign", s);
/** wxPay.unifiedOrder 这个方法中调用微信统一下单接口 */
Map<String, String> respData = wxPay.unifiedOrder(data);
if (respData.get("return_code").equals("SUCCESS")) {
try {
//返回给APP端的参数,APP端再调起支付接口
Map<String, String> repData = new HashMap<>();
repData.put("appid", ourWxPayConfig.getAppID());
repData.put("mch_id", ourWxPayConfig.getMchID());
repData.put("prepayid", respData.get("prepay_id"));
repData.put("package", "WXPay");
repData.put("noncestr", respData.get("nonce_str"));
repData.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
String sign = WXPayUtil.generateSignature(repData, ourWxPayConfig.getKey()); //签名
respData.put("sign", sign);
respData.put("timestamp", repData.get("timestamp"));
respData.put("package", "WXPay");
} catch (Exception e) {
e.printStackTrace();
throw new Exception(respData.get("err_code_des"));
}
return respData;
}
throw new Exception(respData.get("err_code_des"));
}
@Override
public String payNotify(HttpServletRequest request, HttpServletResponse response) {
String resXml = "";
try {
InputStream is = request.getInputStream();
//将InputStream转换成String
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
is.close();
}
resXml = sb.toString();
return this.payBack(resXml);
} catch (Exception e) {
e.printStackTrace();
return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
}
}
|
package solution.step04;
public class Sulfuras implements Item {
private int quality;
private int daysRemaining;
@Override
public void initialize(int quality, int daysRemaining) {
this.quality = quality;
this.daysRemaining = daysRemaining;
}
@Override
public int getQuality() {
return quality;
}
@Override
public int getDaysRemaining() {
return daysRemaining;
}
@Override
public void tick() {
}
}
|
package com.encdata.corn.niblet.domain;
/**
* @Author: jinsi
* @Date: 2019/7/17 09:21
* @Description: 客户列
*/
public class Customer {
private Long id;
private String username;
private Integer deposit;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getDeposit() {
return deposit;
}
public void setDeposit(Integer deposit) {
this.deposit = deposit;
}
}
|
package com.example.myresumeapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.edu:
Intent iedu=new Intent(MainActivity.this,education.class);
startActivity(iedu);
return true;
case R.id.obj:
Intent iobj=new Intent("objective1");
startActivity(iobj);
return true;
case R.id.cont:
Intent icont=new Intent("contact1");
startActivity(icont);
return true;
case R.id.per:
Intent iper=new Intent("personal1");
startActivity(iper);
return true;
case R.id.ref:
Intent iref=new Intent("reference1");
startActivity(iref);
return true;
default:
return super.onOptionsItemSelected(item);
}
}}
/* tv1=(TextView)findViewById(R.id.tv1);
String htmlText = "\t\t\t\tHello,My Self<font color=Red> Pankaj Dhanaji Mohite</font>,from<font color=red> Mumbai.</font>I am pursuing my bachelor degree third year of Computer Engineering in </font><font color=red>Terna Engineering College</font>,Nerul(Navi Mumbai).My strengths are hard working,self-motivated,always ready to learn something new.<p>\t\t\tMy weakness is nothing,but I will be find overcome it soon.My hobby is surfing internet related to my interest.My family concerns 5 members including me.";
tv1.setText(Html.fromHtml(htmlText));
*/
|
public class PostIt {
public PostIt(String backgroundColor, String text, String textcolor){
}
public static void main(String[] args) {
PostIt exampleOne = new PostIt("Orange", "Idea 1","blue");
PostIt exampleTwo = new PostIt("Pink", "Awesome","black");
PostIt exampleThree = new PostIt("Yellow", "Superb!","green");
}
}
|
package ru.alexside.mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.converter.builtin.PassThroughConverter;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.Type;
import ru.alexside.dto.ContactFull;
import ru.alexside.dto.RpoHeaderFull;
import ru.alexside.model.Contact;
import ru.alexside.model.GpoHeader;
import ru.alexside.model.RpoHeader;
import java.time.Instant;
import java.util.UUID;
/**
* Created by Alex on 25.03.2018.
*/
public class JPAToDTOConverter {
public static final MapperFacade FACADE;
static {
// https://github.com/orika-mapper/orika/issues/62
MapperFactory mapperFactory = new DefaultMapperFactory
.Builder()
.dumpStateOnException(true)
.compilerStrategy(new OrikaClassloader())
.useAutoMapping(true)
.build();
mapperFactory.getConverterFactory().registerConverter(new PassThroughConverter(Instant.class));
mapperFactory.getConverterFactory().registerConverter(new StringToUUIDConverter());
mapperFactory.classMap(GpoHeader.class, GpoHeader.class)
.byDefault()
.register();
mapperFactory.classMap(RpoHeader.class, RpoHeaderFull.class)
.exclude("gpoHeader")
.byDefault()
.register();
mapperFactory.classMap(Contact.class, ContactFull.class)
.field("details", "contacts")
.byDefault()
.register();
FACADE = mapperFactory.getMapperFacade();
}
private static class StringToUUIDConverter extends BidirectionalConverter<String, UUID> {
@Override
public UUID convertTo(String source, Type<UUID> destinationType, MappingContext mappingContext) {
try {
return UUID.fromString(source);
} catch (Exception e) {
return null;
}
}
@Override
public String convertFrom(UUID source, Type<String> destinationType, MappingContext mappingContext) {
try {
return source.toString();
} catch (Exception e) {
return null;
}
}
}
}
|
package cn.hassan.spi;
/**
* Created with idea
* Author: hss
* Date: 2019/7/17 8:45
* Description:
*/
public interface Printer {
void print();
}
|
package com.fxn.stash;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Set;
/**
* Created by akshay on 01/03/18.
*/
public class Stash {
private static Stash stash;
private static Context instance;
private SharedPreferences sp;
public static void init(Context context) {
stash = new Stash();
instance = context;
if (stash.sp == null) {
stash.sp = PreferenceManager.getDefaultSharedPreferences(context);
}
}
private static void checkfornull() {
if (stash == null)
throw new NullPointerException("Call init() method in application class");
}
//putString
public static void put(String key, String value) {
checkfornull();
try {
stash.sp.edit().putString(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putStringSet
public static void put(String key, Set<String> value) {
checkfornull();
try {
stash.sp.edit().putStringSet(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putInt
public static void put(String key, int value) {
checkfornull();
try {
stash.sp.edit().putInt(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putLong
public static void put(String key, long value) {
checkfornull();
try {
stash.sp.edit().putLong(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putFloat
public static void put(String key, float value) {
checkfornull();
try {
stash.sp.edit().putFloat(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putBoolean
public static void put(String key, boolean value) {
checkfornull();
try {
stash.sp.edit().putBoolean(key, value).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//putObject or arrayList
public static void put(String key, Object value) {
checkfornull();
try {
Gson gson = new GsonBuilder().create();
stash.sp.edit().putString(key, gson.toJson(value).toString()).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//getString
public static String getString(String key, String defaultvalue) {
checkfornull();
try {
return stash.sp.getString(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static String getString(String key) {
return getString(key, "");
}
//getStringSet
public static Set<String> getStringSet(String key, Set<String> defaultvalue) {
checkfornull();
try {
return stash.sp.getStringSet(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static Set<String> getStringSet(String key) {
return getStringSet(key, null);
}
//getInt
public static int getInt(String key, int defaultvalue) {
checkfornull();
try {
return stash.sp.getInt(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static int getInt(String key) {
return getInt(key, 0);
}
//getLong
public static long getLong(String key, long defaultvalue) {
checkfornull();
try {
return stash.sp.getLong(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static long getLong(String key) {
return getLong(key, (long) 0);
}
//getFloat
public static float getFloat(String key, float defaultvalue) {
checkfornull();
try {
return stash.sp.getFloat(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static float getFloat(String key) {
return getFloat(key, 0.0f);
}
//getBoolean
public static boolean getBoolean(String key, boolean defaultvalue) {
checkfornull();
try {
return stash.sp.getBoolean(key, defaultvalue);
} catch (Exception e) {
e.printStackTrace();
return defaultvalue;
}
}
public static boolean getBoolean(String key) {
return getBoolean(key, false);
}
//getObject
public static <T> Object getObject(String key, Class<?> tClass) {
checkfornull();
try {
Gson gson = new GsonBuilder().create();
return gson.fromJson(stash.sp.getString(key, ""), tClass);
} catch (Exception e) {
Log.e("gson", e.getMessage());
return "";
}
}
//getArrayList
public static <T> ArrayList<T> getArrayList(String key, Class<?> tClass) {
Log.e("_+_++__+_+", "" + tClass.getName());
Gson gson = new Gson();
String data = stash.sp.getString(key, "");
if (!data.trim().isEmpty()) {
Type type = new GenericType(tClass);
return (ArrayList<T>) gson.fromJson(data, type);
}
return new ArrayList<T>();
}
//clear single value
public static void clear(String key) {
checkfornull();
try {
stash.sp.edit().remove(key).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
//clear all preference
public static void clearAll() {
checkfornull();
try {
stash.sp.edit().clear().apply();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addListener(StashListener listener){
checkfornull();
stash.sp.registerOnSharedPreferenceChangeListener(listener);
}
public static void removeListener(StashListener listener){
checkfornull();
stash.sp.unregisterOnSharedPreferenceChangeListener(listener);
}
private static class GenericType implements ParameterizedType {
private Type type;
GenericType(Type type) {
this.type = type;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[]{type};
}
@Override
public Type getRawType() {
return ArrayList.class;
}
@Override
public Type getOwnerType() {
return null;
}
// implement equals method too! (as per javadoc)
}
public interface StashListener extends SharedPreferences.OnSharedPreferenceChangeListener {
}
}
|
package mx.infotec.inflector.web;
/**
* Wrapper for the result of processing with Inflector
* @author Roberto Villarejo Mart�nez <roberto.villarejo@infotec.mx>
*
*/
public class Response {
/**
* The analyzed word itself
*/
private String word = "";
/**
* Language in which word was analyzed
*/
private String lang = "";
/**
* Word was found on dictionary or not
*/
private boolean found = false;
/**
* Results for the analysis
*/
private String result = "";
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public boolean isFound() {
return found;
}
public void isFound(boolean found) {
this.found = found;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Response (String word, String lang) {
this.word = word;
this.lang = lang;
}
@Override
public String toString() {
return "Word: " + this.word + " Lang: " + this.lang + ", Found: " + this.found + " ,Results: " + this.result;
}
}
|
class Solution {
public int repeatedNTimes(int[] A) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<A.length;i++){
if(map.containsKey(A[i])){
int v=map.get(A[i])+1;
map.put(A[i],v);
}else{
map.put(A[i],1);
}
}
int n=A.length/2;
for(int key:map.keySet()){
if(map.get(key)> 1){
return key;
}
}
return -1;
}
}
|
package util;
import java.util.ArrayList;
import java.util.List;
public class Chart {
private List<List<String>> rows;
public Chart() {
rows = new ArrayList<>();
}
public Chart(String s) {
this();
fromString(s);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (List<String> row : rows) {
for (String word : row) {
sb.append(word);
sb.append("; ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append("\n");
}
return sb.toString();
}
public void fromString(String s) {
String lines[] = s.split("\\r?\\n");
for (int i = 0; i < lines.length; ++i) {
String[] words = lines[i].split(";");
List<String> l = new ArrayList<>();
for (int j = 0; j < words.length; j++)
l.add(words[j].trim());
rows.add(l);
}
}
public List<List<String>> getRows() {
return rows;
}
}
|
/*
* EduVersionDaoImplJDBC.java
*
* Created on 2008Äê3ÔÂ5ÈÕ, ÏÂÎç2:43
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package tot.dao.jdbc;
import tot.dao.AbstractDao;
import tot.dao.DaoFactory;
import tot.db.DBUtils;
import tot.util.StringUtils;
import tot.bean.*;
import tot.exception.ObjectNotFoundException;
import tot.exception.DatabaseException;
import java.sql.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Administrator
*/
public class EduDownloadDaoImplJDBC extends AbstractDao{
private static Log log = LogFactory.getLog(EduDownloadDaoImplJDBC.class);
/**
* Creates a new instance of EduVersionDaoImplJDBC
*/
public EduDownloadDaoImplJDBC() {
}
/*
* get last id
*/
public int getLastId(){
DataField df=null;
int returnValue=0;
String sql=null;
sql="select id from t_edu_download order by id desc";
Collection lists =this.getDataList_Limit_Normal(sql,"id",1,0);
Iterator iter = lists.iterator();
if (iter.hasNext()) {
df= (DataField)iter.next();
}
if(df!=null){
returnValue=Integer.parseInt(df.getFieldValue("id"))+1;
}else{
returnValue=1;
}
return returnValue;
}
/** add Keywords */
public boolean add(String title,String viewimg,int categoryid,int versionid,int gradeid,int subjectid,int infotype,
float money,String content,String vtype,String vurl,Timestamp moditime,int isfree,String author,String filelen,String fcontent,int isdownload,int pubserverid,int ischeck,String userid,int isguestpub){
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue=true;
int ParentId=DaoFactory.getCategoryDAO().getParentId(categoryid);
String sql="insert into t_edu_download(Title,ViewImg,CategoryId,VersionId,GradeId,SubjectId,InfoType,NeedMoney,Fdesc,Vtype,Vurl,ModiTime,IsFree,Author,FileLen,ParentId,Fcontent,IsDownload,PubServerId,IsCheck,UserId,IsGuestPub) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
conn = DBUtils.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1,title);
ps.setString(2,viewimg);
ps.setInt(3,categoryid);
ps.setInt(4,versionid);
ps.setInt(5,gradeid);
ps.setInt(6,subjectid);
ps.setInt(7,infotype);
ps.setFloat(8,money);
ps.setString(9,content);
ps.setString(10,vtype);
ps.setString(11,vurl);
ps.setTimestamp(12,moditime);
ps.setInt(13,isfree);
ps.setString(14,author);
ps.setString(15,filelen);
ps.setInt(16,ParentId);
ps.setString(17,fcontent);
ps.setInt(18,isdownload);
ps.setInt(19,pubserverid);
ps.setInt(20,ischeck);
ps.setString(21,userid);
ps.setInt(22,isguestpub);
if(ps.executeUpdate()!=1) returnValue=false;
} catch(SQLException e){
log.error("add edu download error",e);
} finally{
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
/*
* mod Keywords
*/
public boolean mod(int id,String title,String viewimg,int categoryid,int versionid,int gradeid,int subjectid,int infotype,
float money,String content,String vtype,String vurl,Timestamp moditime,int isfree,String author,String filelen,String fcontent,int isdownload,int pubserverid,int ischeck,String userid){
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue=true;
int ParentId=DaoFactory.getCategoryDAO().getParentId(categoryid);
String sql="update t_edu_download set Title=?,ViewImg=?,CategoryId=?,VersionId=?,GradeId=?,SubjectId=?,InfoType=?,NeedMoney=?,Fdesc=?,Vtype=?,Vurl=?,ModiTime=?,IsFree=?,Author=?,FileLen=?,ParentId=?,Fcontent=?,IsDownload=?,PubServerId=?,IsCheck=?,UserId=? where id=?";
try{
conn = DBUtils.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1,title);
ps.setString(2,viewimg);
ps.setInt(3,categoryid);
ps.setInt(4,versionid);
ps.setInt(5,gradeid);
ps.setInt(6,subjectid);
ps.setInt(7,infotype);
ps.setFloat(8,money);
ps.setString(9,content);
ps.setString(10,vtype);
ps.setString(11,vurl);
ps.setTimestamp(12,moditime);
ps.setInt(13,isfree);
ps.setString(14,author);
ps.setString(15,filelen);
ps.setInt(16,ParentId);
ps.setString(17,fcontent);
ps.setInt(18,isdownload);
ps.setInt(19,pubserverid);
ps.setInt(20,ischeck);
ps.setString(21,userid);
ps.setInt(22,id);
if(ps.executeUpdate()!=1) returnValue=false;
} catch(SQLException e){
log.error("mod edu download error",e);
} finally{
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
public boolean del(int id) throws ObjectNotFoundException,DatabaseException{
return exe("delete from t_edu_download where id="+id);
}
public void upHits(int id) throws ObjectNotFoundException,DatabaseException{
exe("update t_edu_download set Hits=Hits+1 where id="+id);
}
public Collection getList_Limit(int categoryid,int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,String key,int orderby,int ischeck,String userid,int isguestpub,int currentpage,int pagesize){
String ord="id";
if(orderby==1) ord="Hits";
if(orderby==2) ord="JoinNum";
if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){
StringBuffer sql=new StringBuffer(512);
sql.append("SELECT t_edu_download.id as eid,t_edu_download.Title as etitle,t_edu_download.Hits,t_edu_download.ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType," +
"t_category.Title as ctitle,t_edu_version.Title as vtitle,t_edu_grade.Title as gtitle,t_edu_subject.Title as stitle " +
"FROM t_edu_download,t_category,t_edu_version,t_edu_grade,t_edu_subject where t_edu_download.CategoryId=t_category.id " +
"and t_edu_download.VersionId=t_edu_version.id and t_edu_download.GradeId=t_edu_grade.id and t_edu_download.SubjectId=t_edu_subject.id ");
if(categoryid>0) sql.append(" and t_edu_download.CategoryId="+categoryid);
if(versionid>0) sql.append(" and t_edu_download.VersionId="+versionid);
if(gradeid>0) sql.append(" and t_edu_download.GradeId="+gradeid);
if(subjectid>0) sql.append(" and t_edu_download.SubjectId="+subjectid);
if(infotype>=0) sql.append(" and t_edu_download.InfoType="+infotype);
if(isfree>=0) sql.append(" and t_edu_download.IsFree="+isfree);
if(isrecommend>0) sql.append(" and t_edu_download.IsRecommend="+isrecommend);
if(key!=null) sql.append(" and t_edu_download.Title like '%"+key+"%'");
if(ischeck>=0) sql.append(" and t_edu_download.IsCheck="+ischeck);
if(userid!=null) sql.append(" and t_edu_download.UserId like '%"+userid+"%'");
if(isguestpub>=0) sql.append(" and t_edu_download.IsGuestPub="+isguestpub);
sql.append(" order by t_edu_download."+ord+" desc");
//System.out.println(sql.toString());
return getDataList_mysqlLimit(sql.toString(),"id,Title,Hits,ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType,CategoryTitle,VersionTitle,GradeTitle,SubjectTitle",pagesize,(currentpage-1)*pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
StringBuffer sql=new StringBuffer(512);
sql.append("SELECT TOP ");
sql.append(pagesize);
sql.append(" id,Title FROM t_edu_download WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP ");
sql.append((currentpage-1)*pagesize+1);
sql.append(" id FROM t_edu_download");
sql.append(" ORDER BY id DESC) AS t))");
sql.append(" ORDER BY id DESC");
return getData(sql.toString(),"id,Title");
} else{
StringBuffer sql=new StringBuffer(512);
sql.append("select id,Title from t_edu_download");
return getDataList_Limit_Normal(sql.toString(),"id,Title",pagesize,(currentpage-1)*pagesize);
}
}
public Collection getList(int categoryid,int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,String key,int orderby,int getchilds,int currentpage,int pagesize){
String ord="id";
if(orderby==1) ord="Hits";
if(orderby==2) ord="JoinNum";
if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){
StringBuffer sql=new StringBuffer(512);
sql.append("SELECT t_edu_download.id as eid,t_edu_download.Title as etitle,t_edu_download.Hits,ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType,t_edu_download.ModiTime as emodtime," +
"t_category.Title as ctitle FROM t_edu_download,t_category where t_edu_download.IsCheck=1 and t_edu_download.CategoryId=t_category.id ");
if(categoryid>0) {
if(getchilds==0)
sql.append(" and t_edu_download.CategoryId="+categoryid);
else
sql.append(" and (t_edu_download.CategoryId="+categoryid+" or t_edu_download.ParentId="+categoryid+")");
}
if(versionid>0) sql.append(" and t_edu_download.VersionId="+versionid);
if(gradeid>0) sql.append(" and t_edu_download.GradeId="+gradeid);
if(subjectid>0) sql.append(" and t_edu_download.SubjectId="+subjectid);
if(infotype>=0) sql.append(" and t_edu_download.InfoType="+infotype);
if(isfree>=0) sql.append(" and t_edu_download.IsFree="+isfree);
if(isrecommend>0) sql.append(" and t_edu_download.IsRecommend="+isrecommend);
if(key!=null) sql.append(" and t_edu_download.Title like '%"+key+"%'");
sql.append(" order by t_edu_download."+ord+" desc");
//System.out.println(sql.toString());
return getDataList_mysqlLimit(sql.toString(),"id,Title,Hits,ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType,ModiTime,CategoryTitle",pagesize,(currentpage-1)*pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
StringBuffer sql=new StringBuffer(512);
sql.append("SELECT TOP ");
sql.append(pagesize);
sql.append(" id,Title FROM t_edu_download WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP ");
sql.append((currentpage-1)*pagesize+1);
sql.append(" id FROM t_edu_download");
sql.append(" ORDER BY id DESC) AS t))");
sql.append(" ORDER BY id DESC");
return getData(sql.toString(),"id,Title");
} else{
StringBuffer sql=new StringBuffer(512);
sql.append("select id,Title from t_edu_download");
return getDataList_Limit_Normal(sql.toString(),"id,Title",pagesize,(currentpage-1)*pagesize);
}
}
public DataField get(int id){
String fields="Title,ViewImg,CategoryId,VersionId,GradeId,SubjectId,InfoType,NeedMoney,Fdesc,Vtype,Vurl,ModiTime,IsFree,Hits,Author,FileLen,JoinNum,Fcontent,IsDownload,PubServerId,IsCheck,UserId,IsGuestPub";
return getFirstData("select "+fields+" from t_edu_download where id="+id,fields);
}
public DataField getShow(int id){
String fields="Title,ViewImg,Author,FileLen,NeedMoney,Fdesc,InfoType,Vtype,Vurl,ModiTime,IsFree,Hits,JoinNum,Fcontent,IsDownload,IsGuestPub,CategoryId,CatalogId,VersionId,GradeId,SubjectId";
StringBuffer sql=new StringBuffer();
sql.append("SELECT t_edu_download.Title as etitle,t_edu_download.ViewImg,Author,FileLen,NeedMoney,Fdesc,InfoType,Vtype,Vurl,t_edu_download.ModiTime as emoditime,t_edu_download.IsFree,Hits,JoinNum,Fcontent,IsDownload,IsGuestPub,t_category.Title as ctitle,t_category.id as cid,t_edu_version.Title as vtitle,t_edu_grade.Title as gtitle,t_edu_subject.Title as stitle FROM t_edu_download,t_category,t_edu_version,t_edu_grade,t_edu_subject where t_edu_download.CategoryId=t_category.id and t_edu_download.VersionId=t_edu_version.id and t_edu_download.GradeId=t_edu_grade.id and t_edu_download.SubjectId=t_edu_subject.id and t_edu_download.id="+id);
return getFirstData(sql.toString(),fields);
}
public int getTotalCount(int categoryid,int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,String key,int ischeck,String userid,int isguestpub){
StringBuffer sql=new StringBuffer(512);
/*sql.append("SELECT count(*) FROM t_edu_download,t_category,t_edu_version,t_edu_grade,t_edu_subject where t_edu_download.CategoryId=t_category.id " +
"and t_edu_download.VersionId=t_edu_version.id and t_edu_download.GradeId=t_edu_grade.id and t_edu_download.SubjectId=t_edu_subject.id ");
* */
sql.append("SELECT count(*) FROM t_edu_download,t_category where t_edu_download.CategoryId=t_category.id");
if(categoryid>0) sql.append(" and t_edu_download.CategoryId="+categoryid);
if(versionid>0) sql.append(" and t_edu_download.VersionId="+versionid);
if(gradeid>0) sql.append(" and t_edu_download.GradeId="+gradeid);
if(subjectid>0) sql.append(" and t_edu_download.SubjectId="+subjectid);
if(infotype>=0) sql.append(" and t_edu_download.InfoType="+infotype);
if(isfree>=0) sql.append(" and t_edu_download.IsFree="+isfree);
if(isrecommend>0) sql.append(" and t_edu_download.IsRecommend="+isrecommend);
if(key!=null) sql.append(" and t_edu_download.Title like '%"+key+"%'");
if(ischeck>=0) sql.append(" and t_edu_download.IsCheck="+ischeck);
if(userid!=null) sql.append(" and t_edu_download.UserId like '%"+userid+"%'");
if(isguestpub>=0) sql.append(" and t_edu_download.IsGuestPub="+isguestpub);
return(this.getDataCount(sql.toString()));
}
public void batDel(String[] s){
this.bat("delete from t_edu_download where id=?",s);
}
public void batRecommend(String[] s,int val){
this.bat("update t_edu_download set IsRecommend="+val+" where id=?",s);
}
public void batDownload(String[] s,int val){
this.bat("update t_edu_download set IsDownload="+val+" where id=?",s);
}
public void remove(String[] s,int categoryid){
int ParentId=DaoFactory.getCategoryDAO().getParentId(categoryid);
this.bat("update t_edu_download set CategoryId="+categoryid+",ParentId="+ParentId+" where id=?",s);
}
public String getLabelList(int rowsNum,int charMax,String titlePrefix,int categoryid,
int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,int sort,int showtime,int getchilds){
StringBuffer sb=new StringBuffer(512);
String lurl="edu";
if(infotype==2) lurl="game";
ArrayList list=(ArrayList)getList(categoryid,versionid,gradeid,subjectid,infotype,isfree,isrecommend,null,sort,getchilds,1,rowsNum);
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
DataField df=(DataField)iter.next();
int itype=Integer.parseInt(df.getFieldValue("InfoType"));
sb.append("<li>");
if (showtime == 1) {
sb.append("<span class=\"col_right\">");
sb.append(df.getFieldValue("ModiTime").substring(5, 10));
sb.append("</span>");
}
sb.append(titlePrefix);
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append(StringUtils.getTopic(df.getFieldValue("Title"),charMax));
sb.append("</a>");
if(itype==1){
sb.append(" <img src=\"/images/media.gif\" align=\"baseline\" />");
}
sb.append("</li>\n");
}
return sb.toString();
}
public String getImgLabelList(int imgw,int imgh,int showtitle,int rowsNum,int charMax,String titlePrefix,int categoryid,
int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,int getchilds){
StringBuffer sb=new StringBuffer(512);
String lurl="edu";
if(infotype==2) lurl="game";
ArrayList list=(ArrayList)getList(categoryid,versionid,gradeid,subjectid,infotype,isfree,isrecommend,null,0,getchilds,1,rowsNum);
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
DataField df=(DataField)iter.next();
sb.append("<li>");
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append("<img src=\"").append(df.getFieldValue("ViewImg")).append("\"");
sb.append(" width=\""+imgw+"\"");
sb.append(" height=\""+imgh+"\" border=\"0\" /></a>");
if(showtitle==1){
sb.append("<h6>");
sb.append(titlePrefix);
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append(StringUtils.getTopic(df.getFieldValue("Title"),charMax));
sb.append("</a>");
sb.append("</h6>");
}
sb.append("</li>\n");
}
return sb.toString();
}
public String getImgLabelListDesc(int imgw,int imgh,int showtitle,int rowsNum,int charMax,String titlePrefix,int categoryid,
int versionid,int gradeid,int subjectid,int infotype,int isfree,int isrecommend,int getchilds){
StringBuffer sql=new StringBuffer(512);
String lurl="edu";
if(infotype==2) lurl="game";
sql.append("SELECT t_edu_download.id as eid,t_edu_download.Title as etitle,t_edu_download.Hits,ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType," +
"t_category.Title as ctitle FROM t_edu_download,t_category where t_edu_download.CategoryId=t_category.id ");
if(categoryid>0) {
if(getchilds==0)
sql.append(" and t_edu_download.CategoryId="+categoryid);
else
sql.append(" and t_edu_download.ParentId="+categoryid);
}
if(versionid>0) sql.append(" and t_edu_download.VersionId="+versionid);
if(gradeid>0) sql.append(" and t_edu_download.GradeId="+gradeid);
if(subjectid>0) sql.append(" and t_edu_download.SubjectId="+subjectid);
if(infotype>=0) sql.append(" and t_edu_download.InfoType="+infotype);
if(isfree>=0) sql.append(" and t_edu_download.IsFree="+isfree);
if(isrecommend>0) sql.append(" and t_edu_download.IsRecommend="+isrecommend);
sql.append(" order by t_edu_download.id desc");
ArrayList list=(ArrayList) getDataList_mysqlLimit(sql.toString(),"id,Title,Hits,ViewImg,Author,FileLen,IsRecommend,JoinNum,InfoType,CategoryTitle",rowsNum,0);
StringBuffer sb=new StringBuffer(512);
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
DataField df=(DataField)iter.next();
sb.append("<li>");
sb.append("<span>");
if(showtitle==1){
sb.append("<h6>");
sb.append(titlePrefix);
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append(df.getFieldValue("Title"));
sb.append("</a>");
sb.append("</h6>");
}
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append(StringUtils.getTopic(df.getFieldValue("Fdesc"),charMax));
sb.append("</a>");
sb.append("</span>");
sb.append("<a href=\"/"+lurl+"/show.jsp?id=");
sb.append(df.getFieldValue("id"));
sb.append("\">");
sb.append("<img src=\"").append(df.getFieldValue("ViewImg")).append("\"");
sb.append(" width=\""+imgw+"\"");
sb.append(" height=\""+imgh+"\" border=\"0\" /></a>");
sb.append("</li>\n");
}
return sb.toString();
}
}
|
package com.zd.christopher.dao;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Repository;
import com.zd.christopher.bean.Faculty;
@Repository
public class FacultyDAO extends EntityDAO<Faculty> implements IFacultyDAO
{
@PostConstruct
public void init()
{
entityClass = Faculty.class;
}
public Faculty findByNaturalId(String id)
{
return null;
}
public List<Faculty> findByNaturalIds(String[] ids)
{
return null;
}
public List<Faculty> findByNaturalIdsByPage(String[] ids, Integer count, Integer page)
{
return null;
}
public List<Faculty> findByNaturalName(String name)
{
return null;
}
public List<Faculty> findByNaturalNameByPage(String name, Integer count, Integer page)
{
return null;
}
public List<Faculty> findByNaturalNames(String[] name)
{
return null;
}
public List<Faculty> findByNaturalNamesByPage(String[] name, Integer count, Integer page)
{
return null;
}
}
|
package kr.or.ddit.user.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import kr.or.ddit.common.model.PageVo;
import kr.or.ddit.user.model.UserVo;
import kr.or.ddit.user.respository.UserDao;
import kr.or.ddit.user.respository.UserDaoI;
import kr.or.ddit.user.service.UserService;
import kr.or.ddit.user.service.UserServiceI;
public class UserDaoTest {
private UserDaoI userDao;
//테스트에 사용할 신규 사용자 추가
// 모든 테스트 코드 실행 전에 테스트에 참여할 수 있는 임의의 사용자를 입력
@Before
public void setup() {
userDao = new UserDao();
UserVo userVo = new UserVo("test","대덕인재","test", new Date(),
"개발원 m", "대전시 중구 중앙로76","4층 대덕인재개발원","34940","brown.png","uuid-generated-filename.png");
userDao.registerUser(userVo);
// 신규 입력 테스트를 위해 테스트 과정에서 입력된 데이터를 삭제
// "ddit_n"이라는 사용자는 무조건 삭제를 한다
userDao.deleteUser("ddit_n");
}
@After
public void teadDown() {
userDao.deleteUser("test");
}
// 전체 사용자 조회 테스트
@Test
public void test() {
/*** Given ***/
// UserDaoI userDao = new UserDao();
/*** When ***/
List<UserVo> userList = userDao.selectAllUser();
/*** Then ***/
assertEquals(16, userList.size());
}
//cf) JPA : find by id
//사용자 아이디를 이용하여 특정 사용자 정보 조회
//test메소드는 항상 public - 반환타입 void 이여야 한다
@Test
public void selectUserTest() {
/***Given***/
String userid = "brown";
/***When***/
UserVo user = userDao.selectUser(userid);
/***Then***/
assertNotNull(user);
assertEquals("브라운", user.getUsernm());
}
// 사용자 페이징 조회 테스트
@Test
public void selectPaging() {
/***Given***/
UserServiceI userService = new UserService();
PageVo pageVo = new PageVo(2, 5);
/***When***/
Map<String, Object> map = userService.selectPagingUser(pageVo);
List<UserVo> pageList = (List<UserVo>)map.get("pageList");
int userCnt = (int)map.get("userCnt");
/***Then***/
assertEquals(5, pageList.size());
assertEquals(16, userCnt);
}
@Test
public void selectAllUserCnt() {
int userCnt = userDao.selectAllUserCnt();
assertEquals(16, userCnt);
}
@Test
public void modifyUserTest() {
/*** Given ***/
// UserDaoI userDao = new UserDao();
//userid, usernm, pass, reg_dt, alias, addr1, addr2, zipcode
UserVo userVo = new UserVo("ddit","대덕인재","dditpass", new Date(),
"개발원 m", "대전시 중구 중앙로76","4층 대덕인재개발원","34940","brown.png","uuid-generated-filename.png");
/*** When ***/
int updateCnt = userDao.modifyUser(userVo);
/*** Then ***/
assertEquals(1, updateCnt);
}
// 삭제 테스트
@Test
public void deleteUserTest() {
/***Given***/
// 해당 테스트가 실행 될 때는 testUser 라는 사용자가 before 메소드에 의해 등록이 된 상태
String userid = "test";
/***When***/
int delteCnt = userDao.deleteUser(userid);
/***Then***/
assertEquals(1, delteCnt);
}
}
|
package com.stk123.model.bo;
import com.stk123.common.util.JdbcUtils.Column;
import java.io.Serializable;
import com.stk123.common.util.JdbcUtils.Table;
@SuppressWarnings("serial")
@Table(name="STK_DICTIONARY")
public class StkDictionary implements Serializable {
@Column(name="TYPE")
private Integer type;
@Column(name="KEY")
private String key;
@Column(name="TEXT")
private String text;
@Column(name="REMARK")
private String remark;
@Column(name="PARAM")
private String param;
@Column(name="PARAM_2")
private String param2;
@Column(name="PARAM_3")
private String param3;
@Column(name="PARAM_4")
private String param4;
@Column(name="PARAM_5")
private String param5;
public Integer getType(){
return this.type;
}
public void setType(Integer type){
this.type = type;
}
public String getKey(){
return this.key;
}
public void setKey(String key){
this.key = key;
}
public String getText(){
return this.text;
}
public void setText(String text){
this.text = text;
}
public String getRemark(){
return this.remark;
}
public void setRemark(String remark){
this.remark = remark;
}
public String getParam(){
return this.param;
}
public void setParam(String param){
this.param = param;
}
public String getParam2(){
return this.param2;
}
public void setParam2(String param2){
this.param2 = param2;
}
public String getParam3(){
return this.param3;
}
public void setParam3(String param3){
this.param3 = param3;
}
public String getParam4(){
return this.param4;
}
public void setParam4(String param4){
this.param4 = param4;
}
public String getParam5(){
return this.param5;
}
public void setParam5(String param5){
this.param5 = param5;
}
public String toString(){
return "type="+type+",key="+key+",text="+text+",remark="+remark+",param="+param+",param2="+param2+",param3="+param3+",param4="+param4+",param5="+param5;
}
}
|
/*
* 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 interfazGrafica;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.text.InternationalFormatter;
import logico.*;
/**
*
* @author Oscar
* Esta clase se encarga de gestionar la venta del vendedor
*/
public class MenuVenta extends Ventana {
private JTextField nombreProducto, codigoProducto;
private JFormattedTextField cantidadProductos;
private JButton botonVender, botonCancelar, botonBuscarProductos;
private JLabel textoEncabezado, textoNombreProducto, textoCodigo, textoCantidad;
private final SIVU sivu;
private String nombreVendedor;
/**
* El constructor inicializa la ventana del menú venta y recibe el objeto SIVU y el nombre del vendedor.
*
* @param sivu
* @param nombreVendedor
*/
public MenuVenta(SIVU sivu, String nombreVendedor) {
super("SIVU", 500, 400);
this.sivu = sivu;
this.nombreVendedor = nombreVendedor;
generarElementosVentana();
}
private void generarElementosVentana() {
generarBotones();
generarCamposTexto();
generarLabels();
repaint();
}
private void generarBotones() {
this.botonVender = super.generarBoton("Vender", 300, 320, 150, 20);
this.add(this.botonVender);
this.botonVender.addActionListener(this);
this.botonCancelar = super.generarBoton("Cancelar", 50, 320, 150, 20);
this.add(this.botonCancelar);
this.botonCancelar.addActionListener(this);
this.botonBuscarProductos = super.generarBoton("Buscar productos", 100, 100, 200, 20);
this.add(this.botonBuscarProductos);
this.botonBuscarProductos.addActionListener(this);
}
private void generarCamposTexto() {
InternationalFormatter formato = super.generarFormato(1);
this.cantidadProductos = super.generarJFormattedTextField(formato, 250, 230, 150, 20);
this.add(this.cantidadProductos);
this.codigoProducto = super.generarJTextField(250, 180, 150, 20);
this.add(codigoProducto);
}
private void generarLabels() {
super.generarJLabelEncabezado(this.textoEncabezado, "Venta", 20, 20, 250, 20);
super.generarJLabel(this.textoCodigo, "Codigo producto:", 20, 180, 200, 20);
super.generarJLabel(this.textoCantidad, "Cantidad:", 20, 230, 200, 20);
}
/**
* Este método gestiona los eventos de la ventana
*/
private void generarMostrarInventario() {
ArrayList<Categoria> categorias = sivu.getCategorias();
String[] nombreCategorias = new String[categorias.size()];
for (int i = 0; i < categorias.size(); i++) {
nombreCategorias[i] = categorias.get(i).getNombre();
}
Object opcion = JOptionPane.showInputDialog(null, "Selecciona una categoría a mostrar", "Elegir", JOptionPane.QUESTION_MESSAGE, null, nombreCategorias, nombreCategorias[0]);
String opcionCategoria = opcion.toString();
String[][] inventario = sivu.retornarCategoria(opcionCategoria);
String[] nombresColumnas = {"Código", "Nombre", "Stock", "Stock crítico", "Precio unitario"};
MenuTabla tabla = new MenuTabla(inventario, nombresColumnas);
}
private void generarVenta() {
if (this.cantidadProductos.getText().length() == 0 || this.codigoProducto.getText().length() == 0) {
JOptionPane.showMessageDialog(this, "Ingrese todos los datos");
} else {
try {
String codigoProducto = this.codigoProducto.getText();
int cantidadProductos = Integer.parseInt(this.cantidadProductos.getText());
Vendedor vendedor = sivu.buscarVendedor(this.nombreVendedor);
ArrayList<Producto> productos = sivu.getProductos();
boolean condicionVenta = vendedor.vender(codigoProducto, cantidadProductos, productos);
if (condicionVenta == true) {
JOptionPane.showMessageDialog(this, "Venta realizada exitosamente");
MenuVendedor menu = new MenuVendedor(this.sivu, this.nombreVendedor);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "Intentelo nuevamente, hubo un error");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Datos erroneos");
}
}
}
/**
* Este método gestiona los eventos de la ventana
*
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.botonBuscarProductos) {
generarMostrarInventario();
}
if (e.getSource() == this.botonVender) {
generarVenta();
}
if (e.getSource() == this.botonCancelar) {
MenuVendedor menu = new MenuVendedor(this.sivu, this.nombreVendedor);
this.dispose();
}
}
}
|
package com.getkhaki.api.bff.web;
import com.getkhaki.api.bff.domain.models.PersonDm;
import com.getkhaki.api.bff.domain.services.PersonService;
import com.getkhaki.api.bff.web.models.PersonDto;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RequestMapping("/persons")
@RestController
@CrossOrigin(origins = "*")
public class PersonController {
private final PersonService personService;
private final ModelMapper modelMapper;
@Autowired
public PersonController(PersonService personService, ModelMapper modelMapper) {
this.personService = personService;
this.modelMapper = modelMapper;
}
@GetMapping("/{email}")
public PersonDto getPerson(@PathVariable String email) {
return this.modelMapper.map(
personService.getPerson(email), PersonDto.class
);
}
@PostMapping
public PersonDto updatePerson(@RequestBody PersonDto personDto) {
return this.modelMapper.map(
this.personService.updatePerson(
this.modelMapper.map(personDto, PersonDm.class)
), PersonDto.class
);
}
@GetMapping("/id/{id}")
public PersonDto getPersonById(@PathVariable String id) {
UUID personUUID = new UUID(0L, 0L);
if (id != null && !id.trim().isEmpty()){
personUUID = UUID.fromString(id);
}
return this.modelMapper.map(
personService.getPersonById(personUUID), PersonDto.class
);
}
}
|
package chapter_one.arrays_and_strings;
/**
* Date 20/05/20.
*
* 1.5 Implement a method to perform basic string compression using the counts of repeated characters.
* For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not
* become smaller than the original string, your method should return the original string.
*/
public class StringCompressionAlternateBookSolution {
public static void main(String[] args){
String original = "aabcccccaaa";
System.out.println(compressAlternate(original));
}
public static String compressAlternate(String str){
int size = countCompression(str);
if(size >= str.length()) {
return str;
}
char[] array = new char[size];
int index = 0;
char last = str.charAt(0);
int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == last) {
count++;
}else {
index = setChar(array, last, index, count);
last = str.charAt(i);
count = 1;
}
}
/*Update string with the last set of repeated characters*/
index = setChar(array, last, index, count);
return String.valueOf(array);
}
public static int setChar(char[] array, char c, int index, int count) {
array[index] = c;
index++;
/*Convert the count to a string, then to an array of chars*/
char[] cnt = String.valueOf(count).toCharArray();
/*Copy characters from biggest digit to smallest*/
for (char x : cnt) {
array[index] = x;
index++;
}
return index;
}
public static int countCompression(String str){
if (str == null | str.isEmpty()) {
return 0;
}
char last = str.charAt(0);
int size = 0;
int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == last) {
count++;
}else {
last = str.charAt(i);
size += 1 + String.valueOf(count).length();
count = 1;
}
}
size += 1 + String.valueOf(count).length();
return size;
}
}
|
package com.pelephone_mobile.songwaiting.ui.fragments;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.pelephone_mobile.R;
import com.pelephone_mobile.songwaiting.global.SWGlobal;
import com.pelephone_mobile.songwaiting.service.SWService;
import com.pelephone_mobile.songwaiting.service.interfaces.ISWServiceResponceListener;
import com.pelephone_mobile.songwaiting.service.interfaces.ISWShareSongFacebookListener;
import com.pelephone_mobile.songwaiting.service.pojos.Pojo;
import com.pelephone_mobile.songwaiting.service.pojos.Song;
import com.pelephone_mobile.songwaiting.service.pojos.Songs;
import com.pelephone_mobile.songwaiting.ui.adapters.DropDownAdapter;
import com.pelephone_mobile.songwaiting.ui.adapters.SWEndlessSearchAdapter;
import com.pelephone_mobile.songwaiting.ui.adapters.SWSongSearchAdapter;
import com.pelephone_mobile.songwaiting.utils.SWLogger;
import com.pelephone_mobile.songwaiting.utils.SWMediaPlayer;
import com.facebook.Session;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.ObjectAnimator;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* @author Galit.Feller
*
*/
public class SearchFragment extends SWBaseFragment{
private ListView mLvSongList;
private EditText mSearchText;
private static final String tag = "SearchFragment";
private LinearLayout mDropDownLayout;
private boolean mIsDropOpen = false;
private TextView mTxtSort;
private int mSort =1;
private ImageButton ibSearch;
private View mContentView;
private ProgressBar mLoadingSearch;
private TextView mTxtNoResults;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mContentView = inflater.inflate(R.layout.search_layout, container,
false);
if (mContentView != null) {
mLvSongList = (ListView) mContentView.findViewById(R.id.lvSongs);
mLoadingSearch = (ProgressBar)mContentView.findViewById(R.id.loadingSearch);
mLoadingSearch.setVisibility(View.INVISIBLE);
mSearchText = (EditText) mContentView.findViewById(R.id.etSearch);
mSearchText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
try {
mLoadingSearch.setVisibility(View.VISIBLE);
mTxtNoResults.setVisibility(View.INVISIBLE);
mLvSongList.setAdapter(null);
SWMediaPlayer.getInstance().killMediaPlayer();
SearchSongList(URLEncoder.encode(mSearchText.getText().toString(), "utf-8"),mSort);
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
});
ImageButton ibBack = (ImageButton)mContentView.findViewById(R.id.ibBack);
ibBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SWMediaPlayer.getInstance().killMediaPlayer();
getActivity().getSupportFragmentManager().popBackStack();
}
});
ImageButton ibDropDown = (ImageButton)mContentView.findViewById(R.id.ibDropDown);
mDropDownLayout = (LinearLayout)mContentView.findViewById(R.id.dropDownLinear);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
mDropDownLayout.setAlpha(0);
}
else
{
mDropDownLayout.setVisibility(View.INVISIBLE);
}
mTxtSort = (TextView)mContentView.findViewById(R.id.txtSort);
ibDropDown.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
if(mIsDropOpen == true)
{
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
ObjectAnimator objetc = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 1,0);
objetc.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation) {
mDropDownLayout.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
objetc.start();
}
else
{
mDropDownLayout.setVisibility(View.INVISIBLE);
}
mIsDropOpen = false;
}
else
{
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
ObjectAnimator objetct = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 0,1);
objetct.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
mDropDownLayout.setVisibility(View.VISIBLE);
mDropDownLayout.setAlpha(0);
}
@Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
objetct.start();
}
else
{
mDropDownLayout.setVisibility(View.VISIBLE);
}
mIsDropOpen = true;
}
}
});
final String options[] = new String[] {
getResources().getString(R.string.sort_general),
getResources().getString(R.string.sort_popular),
getResources().getString(R.string.sort_artist_name) };
mTxtSort.setText(options[0]);
Typeface font = Typeface.createFromAsset(SWGlobal.getAppResources().getAssets(), "arialbd.ttf");
mTxtSort.setTypeface(font);
mSearchText.setTypeface(font);
mTxtNoResults = (TextView)mContentView.findViewById(R.id.txtNoResults);
mTxtNoResults.setTypeface(font);
TextView txtTitle = (TextView)mContentView.findViewById(R.id.txtTitlePage);
txtTitle.setTypeface(font);
ListView listDropDown = (ListView)mContentView.findViewById(R.id.listSortOptions);
if(getActivity()!= null)
{
listDropDown.setAdapter(new DropDownAdapter(getActivity(), options));
listDropDown.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
ObjectAnimator objetc = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 1,0);
objetc.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation) {
mDropDownLayout.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
objetc.start();
}
else
{
mDropDownLayout.setVisibility(View.INVISIBLE);
}
mIsDropOpen = false;
mTxtSort.setText(options[position]);
try {
mLvSongList.setAdapter(null);
mLoadingSearch.setVisibility(View.VISIBLE);
mTxtNoResults.setVisibility(View.INVISIBLE);
SearchSongList(URLEncoder.encode(mSearchText.getText().toString(), "utf-8"),position+1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSort = position +1;
}
});
}
return mContentView;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onServiceConnected(SWService service) {
super.onServiceConnected(service);
}
private void SearchSongList( final String search,int sort){
if(hasInternetConnection())
{
if(mSWService != null){
mSWService.getSongsController().getSongsBySearchString(new ISWServiceResponceListener() {
@Override
public void onResponce(Pojo data) {
// TODO Auto-generated method stub
if (data instanceof Songs) {
for (Song s : ((Songs) data).allSongs) {
SWLogger.print(tag, "Song id : " + s.songId
+ ", Song name : " + s.songName
+ ", picture : " + s.picture);
}
final List<Pojo> list = new ArrayList<Pojo>();
list.addAll(((Songs) data).allSongs);
if(getActivity()!= null)
{
SWSongSearchAdapter songAdapter = new SWSongSearchAdapter(getActivity(),list,search,1,mSWService,new ISWShareSongFacebookListener() {
@Override
public void onShareSongFacebook(Song song)
{
Session session = Session.getActiveSession();
if(!session.isOpened())
{
mIsFirtTimePublish = true;
}
logInFacebook(song);
}
});
final SWEndlessSearchAdapter endlessAdapter = new SWEndlessSearchAdapter(getActivity(), songAdapter, mSWService.getSongsController());
getActivity()
.runOnUiThread(
new Runnable() {
@Override
public void run() {
if(list.size() == 0)
{
mTxtNoResults.setVisibility(View.VISIBLE);
}
mLoadingSearch.setVisibility(View.INVISIBLE);
mLvSongList.setAdapter(endlessAdapter);
}
});
}
}
}
@Override
public void onError(ErrorsTypes error) {
// TODO Auto-generated method stub
if (error != null) {
switch (error) {
case CONNECTION_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - CONNECTION_ERROR ");
break;
case DB_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - DB_ERROR ");
break;
case JSON_PARSE_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - JSON_PARSE_ERROR ");
break;
case IODATA_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - IODATA_ERROR ");
break;
default:
SWLogger.printError(tag,
" getSongsBySubCategory - UNKNOWN_ERROR ");
break;
}
} else {
SWLogger.printError(tag,
" getSongsBySubCategory - UNKNOWN_ERROR ");
}
}
}, search,sort);
}else{
}
}
else
{
mPopNoInternet.show();
}
}
@Override
public void onPause() {
SWMediaPlayer.getInstance().killMediaPlayer();
super.onPause();
}
}
|
package ru.steagle.datamodel;
import android.sax.Element;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;
import org.xml.sax.Attributes;
import java.util.StringTokenizer;
import ru.steagle.protocol.request.ChangeNotifyFlagCommand;
import ru.steagle.protocol.responce.BaseResult;
public class UserInfo extends BaseResult {
public static final String NOTIFY_PHONES_ATTRIB = "avphone";
public static final String NOTIFY_EMAILS_ATTRIB = "aemail";
public static final String NOTIFY_SMS_ATTRIB = "sms";
private String statusId;
private String notifyPhones;
private String notifySms;
private String notifyEmails;
private String userName;
private String balance;
private String currencyId;
private String timeZoneId;
private String tarifId;
private String account;
private String email;
private String phone;
private boolean phoneNotifyEnabled;
private boolean smsNotifyEnabled;
private boolean emailNotifyEnabled;
public UserInfo(String xml) {
parse(xml);
}
public String getEmail() {
return email;
}
public String getPhone() {
return phone;
}
public String getTarifId() {
return tarifId;
}
public String getCurrencyId() {
return currencyId;
}
public String getAccount() {
return account;
}
public boolean isPhoneNotifyEnabled() {
return phoneNotifyEnabled;
}
public boolean isSmsNotifyEnabled() {
return smsNotifyEnabled;
}
public boolean isEmailNotifyEnabled() {
return emailNotifyEnabled;
}
public String getUserName() {
return userName;
}
public String getBalance() {
return balance;
}
public String getStatusId() {
return statusId;
}
public String getNotifyPhones() {
return notifyPhones;
}
public String getNotifySms() {
return notifySms;
}
public String getNotifyEmails() {
return notifyEmails;
}
protected void parse(String xml) {
RootElement root = new RootElement("root");
Element tag = root.getChild("user");
tag.setStartElementListener(new StartElementListener() {
public void start(Attributes attrib) {
readBaseFields(attrib);
statusId = attrib.getValue("id_status");
notifyPhones = attrib.getValue(NOTIFY_PHONES_ATTRIB);
notifySms = attrib.getValue(NOTIFY_SMS_ATTRIB);
notifyEmails = attrib.getValue(NOTIFY_EMAILS_ATTRIB);
userName = attrib.getValue("name");
balance = attrib.getValue("balance");
account = attrib.getValue("account");
currencyId = attrib.getValue("id_currency");
timeZoneId = attrib.getValue("tz");
tarifId = attrib.getValue("id_tarif");
phone = attrib.getValue("phone");
email = attrib.getValue("mail");
String notifyFlags = attrib.getValue("flags_users");
parseNotifyFlags(notifyFlags);
}
});
try {
Xml.parse(xml, root.getContentHandler());
} catch (Exception e) {
setParsingError(e);
}
}
private void parseNotifyFlags(String notifyFlags) {
phoneNotifyEnabled = true;
smsNotifyEnabled = true;
emailNotifyEnabled = true;
if (notifyFlags != null) {
StringTokenizer st = new StringTokenizer(notifyFlags, ",");
while (st.hasMoreTokens()) {
String flag = st.nextToken();
if (flag != null) {
switch (flag) {
case ChangeNotifyFlagCommand.SMS:
smsNotifyEnabled = false;
break;
case ChangeNotifyFlagCommand.EMAIL:
emailNotifyEnabled = false;
break;
case ChangeNotifyFlagCommand.PHONE:
phoneNotifyEnabled = false;
break;
}
}
}
}
}
public String getTimeZoneId() {
return timeZoneId;
}
}
|
package com.barnettwong.view_library.util;
import android.content.res.ColorStateList;
/**
* Generate thumb and background color state list use tintColor
*/
public class ColorUtils {
private static final int ENABLE_ATTR = android.R.attr.state_enabled;
private static final int CHECKED_ATTR = android.R.attr.state_checked;
private static final int PRESSED_ATTR = android.R.attr.state_pressed;
public static ColorStateList generateThumbColorWithTintColor(final int tintColor) {
int[][] states = new int[][] {
{ -ENABLE_ATTR, CHECKED_ATTR},
{ -ENABLE_ATTR},
{PRESSED_ATTR, -CHECKED_ATTR},
{PRESSED_ATTR, CHECKED_ATTR},
{CHECKED_ATTR},
{ -CHECKED_ATTR}
};
int[] colors = new int[] {
tintColor - 0xAA000000,
0xFFBABABA,
tintColor - 0x99000000,
tintColor - 0x99000000,
tintColor | 0xFF000000,
0xFFEEEEEE
};
return new ColorStateList(states, colors);
}
public static ColorStateList generateBackColorWithTintColor(final int tintColor) {
int[][] states = new int[][] {
{ -ENABLE_ATTR, CHECKED_ATTR},
{ -ENABLE_ATTR},
{CHECKED_ATTR, PRESSED_ATTR},
{ -CHECKED_ATTR, PRESSED_ATTR},
{CHECKED_ATTR},
{ -CHECKED_ATTR}
};
int[] colors = new int[] {
tintColor - 0xE1000000,
0x10000000,
tintColor - 0xD0000000,
0x20000000,
tintColor - 0xD0000000,
0x20000000
};
return new ColorStateList(states, colors);
}
}
|
package presentation.webmanager.view;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import presentation.webmanager.MainAPP;
import util.CustomerType;
import vo.CustomerVO;
import vo.ManagerVO;
/**
* Created by 曹利航 on 2016/11/26 12:23.
*/
public class CustomerInfoModifyController {
private MainAPP mainAPP;
private ManagerVO webManagerVO;
private CustomerVO customerVO;
@FXML
private TextField actualNameField;
@FXML
private Label idtentifyLabel;
@FXML
private TextField idtentifyContextField;
@FXML
private TextField contactField;
public void setWebManagerVO(ManagerVO webManagerVO){
this.webManagerVO=webManagerVO;
}
public void setMainAPP(MainAPP mainAPP){
this.mainAPP=mainAPP;
}
public void setCustomerVO(CustomerVO customerVO){
this.customerVO=customerVO;
setIdtentifyField();
}
@FXML
private void setIdtentifyField(){
if(customerVO.getCustomerType().equals(CustomerType.PERSONAL))
idtentifyLabel.setText("生日");
else
idtentifyLabel.setText("企业名");
}
@FXML
private void confirm(){
if(actualNameField.getText()!=null)
customerVO.setCustomerName(actualNameField.getText());
if(idtentifyContextField.getText()!=null)
customerVO.setUniqueInformation(idtentifyContextField.getText());
if(contactField.getText()!=null)
customerVO.setPhoneNumber(contactField.getText());
mainAPP.informationAlert("修改成功");
}
}
|
package revolt.backend.dto;
import lombok.*;
import lombok.experimental.FieldDefaults;
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class SignInFormDto {
String login;
String password;
}
|
package com.testFileUpload.common.error.client;
import com.testFileUpload.common.error.common.ErrorCode;
import org.springframework.http.HttpStatus;
/**
* 集成ErrorCode,定性为客户端校验性异常
* @author CAIFUCHENG3
*/
public interface ClientError extends ErrorCode {
@Override
default HttpStatus httpStatus() {
return HttpStatus.BAD_REQUEST;
}
}
|
package com.redsun.platf.web.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 2012/7/24
* Time: 下午 3:56
* To change this template use File | Settings | File Templates.
*
* javax.servlet.jsp.tagext.
* package which provide default implementation
*
* TagSupport
BodyTagSupport
* setPageContext(PageContext pc)
* setParent(Tag parent)
* getParent()
* doStartTag()
* doEndTag()
* release()
*
*/
public class FirstTag implements Tag, Serializable {
private PageContext pc = null;
private Tag parent = null;
private String name = null;
public void setPageContext(PageContext p) {
pc = p; //save the reference to PageContext object in the private variable
}
public void setParent(Tag t) {
parent = t;
}
/**
* save the reference to parent Tag object in the private variable
* @return
*/
public Tag getParent() {
return parent;
}
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
/**
* doStartMethod() will be called with the start of the tag
* @return
* @throws javax.servlet.jsp.JspException
*/
public int doStartTag() throws JspException {
try {
if(name != null) {
pc.getOut().write("Hello " + name + "!");
} else {
pc.getOut().write("You didn't enter your name");
pc.getOut().write(", what are you afraid of ?");
}
} catch(IOException e) {
throw new JspTagException("An IOException occurred.");
}
return SKIP_BODY; // there is no body content in this tag
}
/**
* called when end of the tag is reached.
* @return
* @throws javax.servlet.jsp.JspException
*/
public int doEndTag() throws JspException {
return EVAL_PAGE; //rest of the page is read by the socket
}
/**
* This method is called by the JSP page when all
* the methods of the tag class have been called
* and it is time to free resources.
*/
public void release() {
pc = null;
parent = null;
name = null;
}
}
|
package crushstudio.crush_studio.repository;
import crushstudio.crush_studio.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
Optional<User> findByEmail(String Email);
Optional<User> findByNickname(String nickName);
Optional<User> findByLocalDate(LocalDate localDate);
}
|
package com.memory.platform.web.web.controller;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.memory.platform.core.annotation.Log;
import com.memory.platform.core.constants.Globals;
import com.memory.platform.core.constants.WebConstants;
import com.memory.platform.core.service.IBaseService;
import com.memory.platform.core.web.ajax.AjaxReturn;
import com.memory.platform.core.web.ajax.ExceptionReturn;
import com.memory.platform.modules.system.base.model.SystemUser;
import com.memory.platform.modules.system.base.service.ISystemLogService;
import com.memory.platform.modules.system.base.service.ISystemUserService;
import com.memory.platform.web.session.SessionInfo;
import com.utils.redis.command.CommandHashOperation;
/**
* 用户登录相关
*
* @author
* @date 2014-6-5 上午11:45:00
*/
@Controller
@RequestMapping("/system/loginController")
public class LoginController {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
@Autowired
@Qualifier("baseServiceImpl")
private IBaseService baseService;
@Autowired
@Qualifier("systemLogServiceImpl")
private ISystemLogService systemLogService;
@Autowired
@Qualifier("systemUserServiceImpl")
private ISystemUserService systemUserService;
/** 限制时间 */
/* @Value("${limit.millis:3600000}") */
private Long millis;
@Autowired
private MessageSource messageSource;
@Autowired
private CommandHashOperation commandHashOperation;
/**
* 退出登录
*/
@RequestMapping("/logout")
@ResponseBody
@Log(operationType="退出操作",operationName="用户退出系统", logLevel=Globals.Log_Type_EXIT)
public Object logout(HttpSession session, Locale locale) {
try {
session.removeAttribute(WebConstants.CURRENT_USER);
session.invalidate();
return new AjaxReturn(true, "退出系统成功!");
// return new AjaxReturn(true,
// messageSource.getMessage("common.login", null, locale));
// return new AjaxReturn(true,
// messageSource.getMessage("common.logout", new
// Object[]{"超级管理员","成功!"}, locale));
} catch (Exception e) {
LOGGER.error("Exception: ", e);
return new ExceptionReturn(e);
}
}
/**
* 用户登录
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
@Log(operationType="登录操作",operationName="用户登录系统", logLevel=Globals.Log_Type_LOGIN)
public Object login(@RequestParam(value = "loginName", required = true) String loginName,
@RequestParam(value = "password", required = true) String password, HttpSession session,
HttpServletRequest request) {
try {
if (StringUtils.isBlank(loginName)) {
return new AjaxReturn(false, "帐号不能为空!");
}
if (StringUtils.isBlank(password)) {
return new AjaxReturn(false, "密码不能为空!");
}
String md5Pwd = DigestUtils.md5Hex(password);
List<SystemUser> userList = systemUserService.findUsers(loginName, md5Pwd);
if (userList != null && userList.size() > 0) {
SystemUser user = userList.get(0);
systemUserService.saveClientInfo(user, request, session.getId());
/*HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
Map<String, Object> m = BeanToMapUtil.convertBean(user);
hashOps.putAll("userinfo" + user.getId(), m);
logger.info("用户信息:", hashOps.entries("userinfo").toString());
Map<String, Object> userMap = hashOps.entries("userinfo" + user.getId());
SystemUser u = new SystemUser();
BeanToMapUtil.convertMap(userMap, u);*/
/*HashMapper<SystemUser, String, String> mapper = new DecoratingStringHashMapper<SystemUser>(new BeanUtilsHashMapper2<SystemUser>(SystemUser.class));
Map m = mapper.toHash(user);
commandHashOperation.HMSET("userinfo" + user.getId(), m);
logger.info("用户信息:", commandHashOperation.HGETALL("userinfo" + user.getId()).toString());
Map userMap = commandHashOperation.HGETALL("userinfo" + user.getId());
SystemUser u = mapper.fromHash(userMap);
logger.info("用户信息u:", u.toString());*/
SessionInfo sessinoInfo = new SessionInfo();
sessinoInfo.setUser(user);
session.setAttribute(WebConstants.CURRENT_USER, sessinoInfo);
LOGGER.info("[{}]登陆成功", sessinoInfo.getUser().getName());
return new AjaxReturn(true, "登陆成功");
}
return new AjaxReturn(false, "用户名或密码错误!");
} catch (Exception e) {
LOGGER.error("Exception: ", e);
return new ExceptionReturn(e);
}
}
/**
* 转到找回用户密码页面
*/
@RequestMapping(value = "/findpwd", method = RequestMethod.GET)
public String findpwd() {
return "user/findpwd";
}
}
|
package com.example.mealprep;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class HomeScreenActivity extends Activity implements OnFragmentInteractionListener{
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Drawer drawer = new Drawer(HomeScreenActivity.this);
drawer.createDrawer();
//this forces portrait orientation
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
drawer.bringFragmentToFront("Home");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_screen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.color_schemes:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onColorSchemeMenuClick(Menu menu) {
//Inflate the color scheme menu... hopefully this works
getMenuInflater().inflate(R.menu.color_schemes_menu, menu);
}
public void changeColorScheme(String colorScheme){
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
|
package com.example.snake;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class Board {
final int rowCount, colCount;
private List<List<Cell>> cells;
public Board(int rowCount, int colCount) {
this.rowCount = rowCount;
this.colCount = colCount;
cells = new ArrayList<>();
initializeBoard(rowCount, colCount);
}
private void initializeBoard(int rowCount, int colCount) {
IntStream.range(0, rowCount)
.forEach(
i -> {
cells.add(new ArrayList<>());
});
IntStream.range(0, rowCount)
.forEach(
i ->
IntStream.range(0, colCount)
.forEach(
j -> {
cells.get(i).add(j, new Cell(i, j));
}));
}
public long calculateScore() {
long score =
cells.stream()
.flatMap(List::stream)
.filter(cell -> cell.getCellType() == CellType.SNAKE)
.count();
return score - 1;
}
public void printGameBoard() {
cells.stream()
.forEach(
rowValues -> {
rowValues.stream()
.forEach(
columnValues -> {
System.out.print("|");
System.out.print(
columnValues.getCellType() == CellType.SNAKE
? "S"
: columnValues.getCellType() == CellType.FOOD ? "F" : ".");
});
System.out.println("|");
});
}
public int getRowCount() {
return rowCount;
}
public int getColCount() {
return colCount;
}
public List<List<Cell>> getCells() {
return cells;
}
public boolean isAllCellOccupiedBySnake() {
return !cells.stream()
.flatMap(List::stream)
.anyMatch(cell -> cell.getCellType() != CellType.SNAKE);
}
public void generateFood() {
if (isAllCellOccupiedBySnake()) {
return;
}
try {
IntStream.iterate(0, i -> i + 1)
.forEach(
i -> {
int row = (int) (Math.random() * rowCount);
int col = (int) (Math.random() * colCount);
if (cells.get(row).get(col).getCellType() != CellType.SNAKE) {
cells.get(row).get(col).setCellType(CellType.FOOD);
throw new RuntimeException();
}
});
} catch (RuntimeException e) {
}
}
}
|
package com.cninnovatel.ev.db;
import android.database.sqlite.SQLiteDatabase;
import java.util.Map;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;
import com.cninnovatel.ev.db.RestMeeting_;
import com.cninnovatel.ev.db.RestUser_;
import com.cninnovatel.ev.db.RestContact_;
import com.cninnovatel.ev.db.RestEndpoint_;
import com.cninnovatel.ev.db.MeetingContact_;
import com.cninnovatel.ev.db.MeetingUser_;
import com.cninnovatel.ev.db.MeetingEndpoint_;
import com.cninnovatel.ev.db.RestCallRecord_;
import com.cninnovatel.ev.db.RestCallRow_;
import com.cninnovatel.ev.db.RestMeeting_Dao;
import com.cninnovatel.ev.db.RestUser_Dao;
import com.cninnovatel.ev.db.RestContact_Dao;
import com.cninnovatel.ev.db.RestEndpoint_Dao;
import com.cninnovatel.ev.db.MeetingContact_Dao;
import com.cninnovatel.ev.db.MeetingUser_Dao;
import com.cninnovatel.ev.db.MeetingEndpoint_Dao;
import com.cninnovatel.ev.db.RestCallRecord_Dao;
import com.cninnovatel.ev.db.RestCallRow_Dao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see de.greenrobot.dao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig restMeeting_DaoConfig;
private final DaoConfig restUser_DaoConfig;
private final DaoConfig restContact_DaoConfig;
private final DaoConfig restEndpoint_DaoConfig;
private final DaoConfig meetingContact_DaoConfig;
private final DaoConfig meetingUser_DaoConfig;
private final DaoConfig meetingEndpoint_DaoConfig;
private final DaoConfig restCallRecord_DaoConfig;
private final DaoConfig restCallRow_DaoConfig;
private final RestMeeting_Dao restMeeting_Dao;
private final RestUser_Dao restUser_Dao;
private final RestContact_Dao restContact_Dao;
private final RestEndpoint_Dao restEndpoint_Dao;
private final MeetingContact_Dao meetingContact_Dao;
private final MeetingUser_Dao meetingUser_Dao;
private final MeetingEndpoint_Dao meetingEndpoint_Dao;
private final RestCallRecord_Dao restCallRecord_Dao;
private final RestCallRow_Dao restCallRow_Dao;
public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
restMeeting_DaoConfig = daoConfigMap.get(RestMeeting_Dao.class).clone();
restMeeting_DaoConfig.initIdentityScope(type);
restUser_DaoConfig = daoConfigMap.get(RestUser_Dao.class).clone();
restUser_DaoConfig.initIdentityScope(type);
restContact_DaoConfig = daoConfigMap.get(RestContact_Dao.class).clone();
restContact_DaoConfig.initIdentityScope(type);
restEndpoint_DaoConfig = daoConfigMap.get(RestEndpoint_Dao.class).clone();
restEndpoint_DaoConfig.initIdentityScope(type);
meetingContact_DaoConfig = daoConfigMap.get(MeetingContact_Dao.class).clone();
meetingContact_DaoConfig.initIdentityScope(type);
meetingUser_DaoConfig = daoConfigMap.get(MeetingUser_Dao.class).clone();
meetingUser_DaoConfig.initIdentityScope(type);
meetingEndpoint_DaoConfig = daoConfigMap.get(MeetingEndpoint_Dao.class).clone();
meetingEndpoint_DaoConfig.initIdentityScope(type);
restCallRecord_DaoConfig = daoConfigMap.get(RestCallRecord_Dao.class).clone();
restCallRecord_DaoConfig.initIdentityScope(type);
restCallRow_DaoConfig = daoConfigMap.get(RestCallRow_Dao.class).clone();
restCallRow_DaoConfig.initIdentityScope(type);
restMeeting_Dao = new RestMeeting_Dao(restMeeting_DaoConfig, this);
restUser_Dao = new RestUser_Dao(restUser_DaoConfig, this);
restContact_Dao = new RestContact_Dao(restContact_DaoConfig, this);
restEndpoint_Dao = new RestEndpoint_Dao(restEndpoint_DaoConfig, this);
meetingContact_Dao = new MeetingContact_Dao(meetingContact_DaoConfig, this);
meetingUser_Dao = new MeetingUser_Dao(meetingUser_DaoConfig, this);
meetingEndpoint_Dao = new MeetingEndpoint_Dao(meetingEndpoint_DaoConfig, this);
restCallRecord_Dao = new RestCallRecord_Dao(restCallRecord_DaoConfig, this);
restCallRow_Dao = new RestCallRow_Dao(restCallRow_DaoConfig, this);
registerDao(RestMeeting_.class, restMeeting_Dao);
registerDao(RestUser_.class, restUser_Dao);
registerDao(RestContact_.class, restContact_Dao);
registerDao(RestEndpoint_.class, restEndpoint_Dao);
registerDao(MeetingContact_.class, meetingContact_Dao);
registerDao(MeetingUser_.class, meetingUser_Dao);
registerDao(MeetingEndpoint_.class, meetingEndpoint_Dao);
registerDao(RestCallRecord_.class, restCallRecord_Dao);
registerDao(RestCallRow_.class, restCallRow_Dao);
}
public void clear() {
restMeeting_DaoConfig.getIdentityScope().clear();
restUser_DaoConfig.getIdentityScope().clear();
restContact_DaoConfig.getIdentityScope().clear();
restEndpoint_DaoConfig.getIdentityScope().clear();
meetingContact_DaoConfig.getIdentityScope().clear();
meetingUser_DaoConfig.getIdentityScope().clear();
meetingEndpoint_DaoConfig.getIdentityScope().clear();
restCallRecord_DaoConfig.getIdentityScope().clear();
restCallRow_DaoConfig.getIdentityScope().clear();
}
public RestMeeting_Dao getRestMeeting_Dao() {
return restMeeting_Dao;
}
public RestUser_Dao getRestUser_Dao() {
return restUser_Dao;
}
public RestContact_Dao getRestContact_Dao() {
return restContact_Dao;
}
public RestEndpoint_Dao getRestEndpoint_Dao() {
return restEndpoint_Dao;
}
public MeetingContact_Dao getMeetingContact_Dao() {
return meetingContact_Dao;
}
public MeetingUser_Dao getMeetingUser_Dao() {
return meetingUser_Dao;
}
public MeetingEndpoint_Dao getMeetingEndpoint_Dao() {
return meetingEndpoint_Dao;
}
public RestCallRecord_Dao getRestCallRecord_Dao() {
return restCallRecord_Dao;
}
public RestCallRow_Dao getRestCallRow_Dao() {
return restCallRow_Dao;
}
}
|
package com.qac.nbg_app.services;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import com.qac.nbg_app.entities.Basket;
import com.qac.nbg_app.managers.BasketManager;
@Stateless
public class BasketService {
@Inject
private BasketManager basketManager;
public List<Basket> findAll(){
return basketManager.findAll();
}
}
|
package com.inventorystock.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Implementation class for Enterprise Inventory Stock management using DAO
*
* @author (M1035775) Kotra Thirumala
*
*/
public class InventoryStockImpl {
/**
* Scanner class for getting inputs from the user
*/
Scanner scanner = new Scanner(System.in);
/**
* Creating an ArrayList
*/
List<InventoryStockDao> listInventory = new ArrayList<InventoryStockDao>();
private static int PRODUCTID = 100;
/**
* Method for displaying the menu options for the user
*/
private void displayMenu() {
System.out.println("User menu options: ");
System.out.println("1 - to add to inventory" + "\n" + "2 - to display inventory" + "\n" + "3 - to make purchase"
+ "\n" + "4 - exit from the program");
}
/**
* Method for getting input from the user
*/
private void getUserInput() {
System.out.println("Please choose your option: ");
int option = scanner.nextInt();
scanner.nextLine();
switch (option) {
case 1:
// Add to inventory case
System.out.println("Add items to the inventory.");
addInventoryMenu();
break;
case 2:
// Display the inventory case
System.out.println("Display the inventory stock: ");
displayInventory();
break;
case 3:
// Purchase an item case
makePurchase();
break;
case 4:
// Exit from the program case
exitFromProgram();
break;
default:
System.out.println("Please enter the valid option.");
break;
}
}
/**
* Method for getting inventory item details and store them in the ArrayList
*/
private void addInventoryMenu() {
System.out.println("Enter the Product name: ");
String productName = scanner.nextLine();
System.out.println("Enter the Make and Model: ");
String makeAndModelName = scanner.nextLine();
System.out.println("Enter the Number of items: ");
int numberOfItems = scanner.nextInt();
System.out.println("Enter the Item Price: ");
double itemPrice = scanner.nextDouble();
// Adding the inventory items to the ArrayList
listInventory.add(new InventoryStockDao(PRODUCTID, productName, makeAndModelName, numberOfItems, itemPrice));
PRODUCTID = PRODUCTID + 1;
displayMenu();
getUserInput();
}
/**
* Method for getting all product inventory details and inventory list
*
* @return listInventory
*/
private List<InventoryStockDao> getAllProducts() {
return listInventory;
}
/**
* Method for display the Inventory stock items in the list
*/
private void displayInventory() {
for (InventoryStockDao inventoryStockDao : getAllProducts()) {
System.out.println(inventoryStockDao.getProductId() + " | " + inventoryStockDao.getProductName() + " | "
+ inventoryStockDao.getMakeAndModelName() + " | " + inventoryStockDao.getNumberOfItems() + " | "
+ inventoryStockDao.getItemPrice() + "\n");
}
displayMenu();
getUserInput();
}
/**
* Method for display the available products with product id during the purchase
*/
private void displayProductOnPuchase() {
for (InventoryStockDao inventoryStockDao : getAllProducts()) {
System.out.println(inventoryStockDao.getProductId() + " | " + inventoryStockDao.getProductName() + " | "
+ inventoryStockDao.getMakeAndModelName() + "\n");
}
}
/**
* Method for make purchase an item
*/
private void makePurchase() {
displayProductOnPuchase();
System.out.println("Select the Item by entering the product id.");
int item = scanner.nextInt();
for (InventoryStockDao inventoryStockDao : getAllProducts()) {
if (inventoryStockDao.getProductId() == item) {
System.out.println(inventoryStockDao.getProductId() + " " + inventoryStockDao.getProductName()
+ " item is selected for purchase.");
System.out.println("Enter the number of items: ");
int requiredItems = scanner.nextInt();
if (requiredItems <= inventoryStockDao.getNumberOfItems() && requiredItems != 0) {
double totalPrice = requiredItems * inventoryStockDao.getItemPrice();
generateBill(inventoryStockDao.getProductId(), inventoryStockDao.getProductName(),
inventoryStockDao.getMakeAndModelName(), requiredItems, inventoryStockDao.getItemPrice(),
totalPrice);
int remainingItems = (inventoryStockDao.getNumberOfItems() - requiredItems);
inventoryStockDao.setNumberOfItems(remainingItems);
} else {
System.out.println("Inventory: Out of stock.");
}
}
}
displayMenu();
getUserInput();
}
/**
* Method for generating the bill for the purchased items
*
* @param pid
* @param pName
* @param mam
* @param noi
* @param pr
* @param tpr
*/
private void generateBill(int pid, String pName, String mam, int noi, double pr, double tpr) {
System.out.println("*************************************Purchased Bill*************************************");
System.out
.println("| Product Id | Product Name | Make and Model | Number of Items | Item price | Total Price |");
System.out.println("| " + pid + " | " + pName + " | " + mam + " | " + noi + " | " + pr + " | " + tpr + " |");
}
/**
* Method for exit from the program
*/
private void exitFromProgram() {
System.out.println("Exited from the program.");
scanner.close();
System.exit(0);
}
/**
* Main method for the InventoryStockImpl class
*/
public static void main(String[] args) {
// Creating the class object
InventoryStockImpl inventoryStockObj = new InventoryStockImpl();
inventoryStockObj.displayMenu();
inventoryStockObj.getUserInput();
}
}
|
/*
* 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 org.exolin.sudoku.solver;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
/**
*
* @author Thomas
*/
public class Block<T> implements Iterable<T>
{
private final List<T> block = new ArrayList<>(9);
public Block(Function<Position, T> supplier)
{
for(int row=0;row<3;++row)
for(int col=0;col<3;++col)
block.add(supplier.apply(new Position(row, col)));
}
public T get(Position position)
{
return block.get(position.getIndex());
}
@Override
public Iterator<T> iterator()
{
return block.iterator();
}
public List<T> getRow(int rowIndex)
{
return block.subList(rowIndex*3, (rowIndex+1)*3);
}
public List<T> getColumn(int columnIndex)
{
return new AbstractList<T>() {
@Override
public T get(int rowIndex)
{
return Block.this.get(new Position(rowIndex, columnIndex));
}
@Override
public int size()
{
return 3;
}
};
}
}
|
// https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/solution/
class Solution {
public boolean isValidSerialization(String preorder) {
int slots = 1;
int n = preorder.length();
for(int i = 0; i < n; ++i) {
if (preorder.charAt(i) == ',') {
--slots;
if (slots < 0) return false;
if (preorder.charAt(i - 1) != '#') slots += 2;
}
}
slots = (preorder.charAt(n - 1) == '#') ? slots - 1 : slots + 1;
return slots == 0;
}
}
|
package cn.mccreefei.zhihu.service.vo;
import lombok.Data;
/**
* @author MccreeFei
* @create 2018-01-22 9:46
*/
@Data
public class TextVo {
private Integer articleId;
private Integer questionId;
private Integer answerId;
private String content;
private Integer textType;
}
|
package com.sshfortress.common.model;
public class DstListByAssetId {
private Long dstId;
private String dstName;
private String dstPassword;
public Long getDstId() {
return dstId;
}
public void setDstId(Long dstId) {
this.dstId = dstId;
}
public String getDstName() {
return dstName;
}
public void setDstName(String dstName) {
this.dstName = dstName;
}
public String getDstPassword() {
return dstPassword;
}
public void setDstPassword(String dstPassword) {
this.dstPassword = dstPassword;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.shinchan.hql_sample_app;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
*
* @author mnagdev
*/
public class PutEmpData {
public static void main(String args[]){
List<Integer>list=new ArrayList<Integer>();
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();
Emp e=new Emp();
e.setName("Mayur");
e.setSalary(50);
Emp e1=new Emp();
e1.setName("Ruwa");
e1.setSalary(60);
Emp e2=new Emp();
e2.setName("Sonam");
e2.setSalary(80);
Emp e3=new Emp();
e3.setName("Vinil");
e3.setSalary(90);
s.save(e);
s.save(e1);
s.save(e2);
s.save(e3);
t.commit();
s.close();
System.out.println("data has been saved!");
}//main
}//class
|
package pers.mine.scratchpad.base.generics;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@TestAnn("test")
public class AnnotationValueEdit {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnn {
String value();
}
|
package com.grocery.codenicely.vegworld_new.sub_category.view;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.grocery.codenicely.vegworld_new.R;
import com.grocery.codenicely.vegworld_new.cart.view.CartFragment;
import com.grocery.codenicely.vegworld_new.helper.Keys;
import com.grocery.codenicely.vegworld_new.helper.NetworkUtils;
import com.grocery.codenicely.vegworld_new.helper.SharedPrefs;
import com.grocery.codenicely.vegworld_new.home.view.HomeActivity;
import com.grocery.codenicely.vegworld_new.no_internet_connection.view.NoInternetConnectionFragment;
import com.grocery.codenicely.vegworld_new.products.view.ProductsListFragment;
import com.grocery.codenicely.vegworld_new.sub_category.provider.RetrofitSubCategoryDetailsProvider;
import com.grocery.codenicely.vegworld_new.sub_category.model.SubCategoryData;
import com.grocery.codenicely.vegworld_new.sub_category.model.SubCategoryDetails;
import com.grocery.codenicely.vegworld_new.sub_category.presenter.SubCategoryPresenter;
import com.grocery.codenicely.vegworld_new.sub_category.presenter.SubCategoryPresenterImpl;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link SubCategoryFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link SubCategoryFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SubCategoryFragment extends Fragment implements SubCategoryView {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
@BindView(R.id.viewPager)
ViewPager viewPager;
@BindView(R.id.layout_not_available)
LinearLayout layout_not_available;
/* @BindView(R.id.imageProgressBar)
ProgressBar imageProgressBar;
*/
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tabLayout)
TabLayout tabLayout;
@BindView(R.id.progressBar)
ProgressBar progressBar;
/* @BindView(R.id.imageView)
ImageView imageView;
*/
/*@BindView(R.id.collapsingToolbar)
CollapsingToolbarLayout collapsingToolbarLayout;
*/
@BindView(R.id.coordinate_subcategory)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.checkout_layout)
LinearLayout checkout_layout;
@BindView(R.id.item_cart)
TextView cartTextView;
@BindView(R.id.cart_image)
ImageView cartImg;
@BindView(R.id.total_bill)
TextView total_bill;
@BindView(R.id.number_of_items)
TextView cart_count;
@BindView(R.id.cart)
ImageView cartImage;
int sub_category_id;
private SharedPrefs sharedPrefs;
private ViewPagerAdapter viewPagerAdapter;
private SubCategoryPresenter subCategoryPresenter;
private List<String> list = new ArrayList<>();
private List<SubCategoryDetails> subCategoryDetailsList;
// private ImageLoader imageLoader;
private Context context;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public SubCategoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SubCategoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static SubCategoryFragment newInstance(String param1, String param2) {
SubCategoryFragment fragment = new SubCategoryFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_sub_category, container, false);
context = getContext();
ButterKnife.bind(this, view);
if (!NetworkUtils.isNetworkAvailable(getContext())) {
((HomeActivity) getActivity()).addFragment(new NoInternetConnectionFragment(), "No Connection");
}
checkout_layout.setVisibility(View.GONE);
sharedPrefs = new SharedPrefs(getContext());
if (getActivity() instanceof HomeActivity) {
((HomeActivity) getContext()).getSupportActionBar().hide();
}
checkout_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cart_count.getText().length() != 0) {
if (cart_count.getText().charAt(0) == '0') {
Toast.makeText(getContext(), "No Products in cart", Toast.LENGTH_SHORT).show();
return;
}
}
if (getActivity() instanceof HomeActivity) {
((HomeActivity) getContext()).addFragment(new CartFragment(), "Cart");
((HomeActivity) getContext()).getSupportActionBar().hide();
}
}
});
// imageLoader = new GlideImageLoader(getContext());
subCategoryPresenter = new SubCategoryPresenterImpl(this, new RetrofitSubCategoryDetailsProvider());
toolbar.setTitleTextColor(ContextCompat.getColor(getContext(), R.color.white));
toolbar.setNavigationIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_arrow_back_white_24dp));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
Bundle bundle = this.getArguments();
int category_id = bundle.getInt(Keys.KEY_CATEGORY_ID);
final String category_name = bundle.getString(Keys.KEY_CATEGORY_NAME);
sub_category_id=bundle.getInt(Keys.KEY_SUBCATEGORY_ID);
toolbar.setTitle(category_name);
subCategoryPresenter.requestSubCategoryDetails(sharedPrefs.getAccessToken(), category_id);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
/// imageLoader.loadImage(list.get(tab.getPosition()), imageView, imageProgressBar);
// Log.i(TAG, "Image Changed :" + tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.appBarLayout);
assert appBarLayout != null;
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
toolbar.setTitle(category_name);
isShow = true;
} else if (isShow) {
toolbar.setTitle(category_name);
isShow = false;
}
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
/* if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
*/
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
if (subCategoryPresenter != null) {
subCategoryPresenter.onDestroy();
//Keys.sub_category_position=-1;
}
onDestroy();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public List<String> getData() {
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("a");
stringList.add("a");
stringList.add("a");
stringList.add("a");
stringList.add("a");
stringList.add("a");
return stringList;
}
@Override
public void showProgressBar(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.GONE);
viewPager.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
tabLayout.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.VISIBLE);
}
}
@Override
public void showMessage(String message) {
if (context != null) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
@Override
public void setTabs(SubCategoryData subCategoryData) {
if (subCategoryData.isSuccess()) {
if (subCategoryData.getSub_category_list().size() == 0) {
layout_not_available.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.GONE);
viewPager.setVisibility(View.GONE);
return;
} else {
layout_not_available.setVisibility(View.GONE);
tabLayout.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.VISIBLE);
}
}
// Log.i(TAG,"List"+subCategoryDetailsList.toString());
subCategoryDetailsList = new ArrayList<>();
subCategoryDetailsList = subCategoryData.getSub_category_list();
List<Fragment> fragmentList = new ArrayList<>();
List<String> titleList = new ArrayList<>();
for (int i = 0; i < subCategoryDetailsList.size(); i++) {
ProductsListFragment fragment = ProductsListFragment.newInstance(subCategoryDetailsList.get(i).getId()
,subCategoryDetailsList.get(i).getName());
fragmentList.add(fragment);
if(subCategoryDetailsList.get(i).getId()==sub_category_id){
viewPager.setCurrentItem(i);
}
titleList.add(subCategoryDetailsList.get(i).getName());
list.add(subCategoryDetailsList.get(i).getImage());
}
viewPagerAdapter.setTabData(fragmentList, titleList);
viewPagerAdapter.notifyDataSetChanged();
if (subCategoryData.getCart_count() > 0) {
checkout_layout.setVisibility(View.VISIBLE);
} else {
checkout_layout.setVisibility(View.GONE);
}
total_bill.setText("₹ ");
total_bill.append(String.valueOf(subCategoryData.getTotal_discounted()));
cart_count.setText(String.valueOf(subCategoryData.getCart_count()));
cart_count.append(" Items");
viewPager.setOffscreenPageLimit(subCategoryData.getSub_category_list().size());
if(Keys.sub_category_position!=-1&&Keys.product_id!=-1)
{
if(Keys.sub_category_id==sub_category_id){
Log.d("sub_id",String.valueOf(sub_category_id));
viewPager.setCurrentItem(Keys.sub_category_position);
}
/*new Handler().postDelayed(
new Runnable(){
@Override
public void run() {
tabLayout.setScrollPosition(Keys.sub_category_position,0f,true);
}
}, 100);*/
}
}
public void updateCartLayout(int cart_count, int total) {
if (cart_count > 0) {
checkout_layout.setVisibility(View.VISIBLE);
} else {
checkout_layout.setVisibility(View.GONE);
}
total_bill.setText("₹ ");
total_bill.append(String.valueOf(total));
this.cart_count.setText(String.valueOf(cart_count));
this.cart_count.append(" Items");
}
}
|
package cn.itcast.core.controller;
import cn.itcast.core.pojo.entity.EchrtsResult;
import cn.itcast.core.pojo.entity.PageResult;
import cn.itcast.core.pojo.entity.Result;
import cn.itcast.core.pojo.order.Order;
import cn.itcast.core.pojo.order.OrderItem;
import cn.itcast.core.service.ShopOrdersService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("order")
public class OrderController {
@Reference
private ShopOrdersService shopOrdersService;
/**
* 后端订单分页显示
*
* @param page 当前页码
* @param rows 显示数量
* @param order
* @return 返回分页订单数据
*/
@RequestMapping("search")
public PageResult search(Integer page, Integer rows, @RequestBody Order order) {
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
order.setSellerId(userName);
return shopOrdersService.findPage(page, rows, order);
}
@RequestMapping("updateStatus")
public Result updateStatus(Long[] ids, String status) {
try {
shopOrdersService.updateStatus(ids, status);
return new Result(true, "修改数据状态成功!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "修改数据状态失败!");
}
}
@RequestMapping("echarts")
public List<EchrtsResult> findech() {
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
return shopOrdersService.findech(userName);
}
@RequestMapping("echarts2")
public List<OrderItem> findechz() {
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
return shopOrdersService.findechz(userName);
}
}
|
/**
* project name:cdds
* file name:ExceptionHandle
* package name:com.cdkj.asset.common.exception
* date:2018/3/17 上午10:34
* author:bovine
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.common.exception;
import com.cdkj.common.constant.ResultCode;
import com.cdkj.util.Result;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* description: 全局异常处理 <br>
* date: 2018/3/17 上午10:34
*
* @author bovine
* @version 1.0
* @since JDK 1.8
*/
@RestControllerAdvice
public class ExceptionHandle {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof CustException) {
CustException courseException = (CustException) e;
logger.error("系统异常CustException>>>", e);
return Result.error(courseException.getErrCode(), courseException.getMessage());
}else if(e instanceof AuthorizationException){
logger.error("权限异常>>>", e);
return Result.error(ResultCode.FAIL,"无访问权限");
}
logger.error("系统异常>>>", e);
return Result.error(ResultCode.FAIL, e.getMessage());
}
}
|
package servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import model.User;
@WebServlet(urlPatterns = "/checkUsername")
public class CheckUsernameServlet extends HttpServlet{
private static final long serialVersionUID = 604791361161277461L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
username = username.replaceAll("\\s*", "");
UserDao userDao = new UserDaoImpl();
User user = userDao.findByUsername(username);
resp.setContentType("application/json;charset=utf-8");
Map<String,String> map = new HashMap<>();
if(user == null) {
map.put("msg", "SUCCESS");
}
resp.getWriter().write(JSON.toJSONString(map));
}
}
|
package com.globalmediasoft.android.http;
import java.net.URL;
import org.json.JSONException;
import com.globalmediasoft.android.parser.GMSParserJSON;
import android.graphics.Bitmap;
public class GMSHttpResponse {
protected String content;
protected Bitmap bm;
protected URL url;
public GMSHttpResponse() {
}
public GMSHttpResponse(String content) {
this.content = content;
}
public GMSHttpResponse(URL url) {
this.url = url;
}
public String getContent() {
return content.trim();
}
public Bitmap getBitmapContent() {
return this.bm;
}
public void setContent(String content) {
this.content = content;
}
public void setContent(Bitmap bm) {
this.bm = bm;
}
public GMSParserJSON getJSONContent() {
try {
return new GMSParserJSON(getContent());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String getRequestedUrl() {
return url.toString();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.multifuncional.diarioelectronico.formato;
/**
* TituloLogGeneral - 15/09/2008
* @author AA.Garcia
* Davivienda 2008
*/
public class TituloDiarioMultifuncionalGeneral {
public static String[] tituloHojaEfectivo;
static {
tituloHojaEfectivo = new String[2];
tituloHojaEfectivo[0] = "Multifuncional Efectivo ";
tituloHojaEfectivo[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
public static String[] tituloHojaCheque;
static {
tituloHojaCheque = new String[2];
tituloHojaCheque[0] = "Multifuncional Cheque ";
tituloHojaCheque[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
public static String[] tituloHojaHistoricoCargue;
static {
tituloHojaHistoricoCargue = new String[2];
tituloHojaHistoricoCargue[0] = "Multifuncional Historico Cargue ";
tituloHojaHistoricoCargue[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
public static String[] tituloHojaLogCajero;
static {
tituloHojaHistoricoCargue = new String[2];
tituloHojaHistoricoCargue[0] = "Log Cajero Multifuncional ";
tituloHojaHistoricoCargue[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
public static String[] tituloHojaReintegrosMultifuncional ;
static{
tituloHojaReintegrosMultifuncional = new String[2] ;
tituloHojaReintegrosMultifuncional[0] = "Informe Reintegros Multifuncional" ;
tituloHojaReintegrosMultifuncional[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
/**
* Titulos de las columnas
*/
public static String[] tituloColumnasEfectivo = {"TRANSACCION", "ESTADO", "CAJERO", "# CORTE", "TX CONSECUTIVO", "FECHA CIERRE", "FECHA CAJERO", "TIPO CUENTA", "NUMERO CUENTA",
"CUENTA HOMOLOGA", "VALOR", "# BILLETES ND", "# BILLETES 50.000", "# BILLETES 20.000", "# BILLETES 10.000",
"# BILLETES 5.000", "# BILLETES 2.000", "# BILLETES 1.000", "TOTAL BILLETES"
};
public static String[] tituloColumnasCheque = {"TRANSACCION", "CAJERO", "FECHA CAJERO", "# CORTE", "TX CONSECUTIVO", "FECHA CIERRE", "ESTADO", "CONSECUTIVO CHEQUE", "TIPO CUENTA", "NUMERO CUENTA",
"CUENTA HOMOLOGA", "CHEQUE PROPIO", "RUTA", "TRANSITO", "CUENTA", "SERIAL", "OFICINA", "VALOR CHEQUE",
"PLAZA", "FECHA ARCHIVO", "MONTO ARCHIVO", "CANTIDAD CHEQUES"
};
public static String[] tituloColumnasHistoricoCargue = {"CODIGO TRANSACCION", "CODIGO CAJERO", "FECHA CAJERO", "NUMERO CORTE", "CONSECUTIVO TRANSACION", "FECHA CIERRE", "ESTADO", "CONSECUTIVO CHEQUE", "TIPO CUENTA", "NUEMERO CUENTA",
"NUMERO CUENTA HOMOLOGA", "CHEQUE PROPIO", "RUTA", "TRANSITO", "CUENTA", "SERIAL", "OFICINA", "VALOR CHEQUE USUARIO",
"PLAZA", "FECHA ARCHIVO", "MONTO ARCHIVO", "CANTIDAD CHEQUES"
};
public static String[] tituloColumnasLogCajero = { "CAJERO", "FECHA", "ARCHIVO", "SECUENCIA", "DATOS"
};
public static String[] tituloColumnasReintegrosMultifuncional = {"FECHA HORA DISPENSADOR","BILLETAJE DISPENSADOR","TOTAL DISPENSADOR",
"TRANSACCION", "ESTADO", "CAJERO", "# CORTE", "TX CONSECUTIVO", "FECHA CIERRE", "FECHA CAJERO", "TIPO CUENTA", "NUMERO CUENTA",
"CUENTA HOMOLOGA", "VALOR", "# BILLETES ND", "# BILLETES 50.000", "# BILLETES 20.000", "# BILLETES 10.000",
"# BILLETES 5.000", "# BILLETES 2.000", "# BILLETES 1.000", "TOTAL BILLETES"
};
}
|
package com.example.ecommerce_application.controllers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.example.ecommerce_application.TestUtils;
import com.example.ecommerce_application.model.persistence.Cart;
import com.example.ecommerce_application.model.persistence.Item;
import com.example.ecommerce_application.model.persistence.User;
import com.example.ecommerce_application.model.persistence.repositories.CartRepository;
import com.example.ecommerce_application.model.persistence.repositories.ItemRepository;
import com.example.ecommerce_application.model.persistence.repositories.UserRepository;
import com.example.ecommerce_application.model.requests.ModifyCartRequest;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
public class CartControllerTest {
private CartController cartController;
private ModifyCartRequest modifyCartRequest;
private UserRepository userRepo = mock(UserRepository.class);
private CartRepository cartRepo = mock(CartRepository.class);
private ItemRepository itemRepo = mock(ItemRepository.class);
private User user = new User();
private Item item = new Item();
private Cart cart = new Cart();
@Before
public void setUp() throws Exception {
cartController = new CartController();
modifyCartRequest = new ModifyCartRequest();
TestUtils.injectObject(cartController, "cartRepository", cartRepo);
TestUtils.injectObject(cartController, "itemRepository", itemRepo);
TestUtils.injectObject(cartController, "userRepository", userRepo);
user.setUsername("test");
user.setPassword("123456789");
user.setId(1);
user.setCart(cart);
item.setId(1L);
item.setName("test item");
item.setPrice(BigDecimal.valueOf(5.78));
when(userRepo.findByUsername("test")).thenReturn(user);
when(itemRepo.findById(1L)).thenReturn(Optional.of(item));
}
@Test
public void addToCart_happy_path() {
modifyCartRequest.setUsername(user.getUsername());
modifyCartRequest.setItemId(1L);
modifyCartRequest.setQuantity(1);
final ResponseEntity<Cart> responseEntity = cartController.addTocart(modifyCartRequest);
assertEquals(200, responseEntity.getStatusCodeValue());
}
@Test
public void addToCart_with_no_item() {
modifyCartRequest.setUsername(user.getUsername());
modifyCartRequest.setQuantity(1);
final ResponseEntity<Cart> responseEntity = cartController.addTocart(modifyCartRequest);
assertEquals(404, responseEntity.getStatusCodeValue());
}
@Test
public void addToCart_with_no_user() {
modifyCartRequest.setUsername(null);
modifyCartRequest.setItemId(1L);
modifyCartRequest.setQuantity(1);
final ResponseEntity<Cart> responseEntity = cartController.addTocart(modifyCartRequest);
assertEquals(404, responseEntity.getStatusCodeValue());
}
@Test
public void removeFromCart_happy_path() {
modifyCartRequest.setUsername(user.getUsername());
modifyCartRequest.setItemId(1L);
modifyCartRequest.setQuantity(1);
ResponseEntity<Cart> responseEntity = cartController.addTocart(modifyCartRequest);
responseEntity = cartController.removeFromcart(modifyCartRequest);
assertEquals(200, responseEntity.getStatusCodeValue());
BigDecimal result = new BigDecimal("0.00");
assertEquals(result, responseEntity.getBody().getTotal());
}
}
|
package exercise3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class InvocationHandlerCalculator implements InvocationHandler {
private Object obj;
private Map<Integer, Integer> map = new HashMap<>();
public InvocationHandlerCalculator(CalculatorImpl calculator) {
this.obj = calculator;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Integer result = 0;
if (map.containsKey(objects[0])) {
result = map.get(objects[0]);
System.out.println("from cached (" + objects[0] + ")");
} else {
result = (Integer) method.invoke(obj, objects);
map.put((Integer) objects[0], result);
System.out.println("calculate (" + objects[0] + ")");
}
return result;
}
}
|
package com.openfarmanager.android.fragments;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.openfarmanager.android.App;
import com.openfarmanager.android.utils.SystemUtils;
/**
* Base Dialog Fragment.
*
* @author Vlad Namashko
*/
public class BaseDialog extends DialogFragment {
@Override
public void onStart() {
super.onStart();
adjustDialogSize();
}
/**
* Adjust dialog size. Actuall for old android version only (due to absence of Holo themes).
*/
private void adjustDialogSize() {
if (!SystemUtils.isHoneycombOrNever() && getDialog()!=null && getDialog().getWindow() != null) {
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.copyFrom(getDialog().getWindow().getAttributes());
params.width = (int) (metrics.widthPixels * 0.8f);
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
getDialog().getWindow().setAttributes(params);
}
}
/**
* getstring using Application instance instead of Activity, which throw exception.
*
* @param resId Resource id for the string
*/
public final String getSafeString(int resId) {
return App.sInstance.getString(resId);
}
/**
* getstring using Application instance instead of Activity, which throw exception.
*
* @param resId Resource id for the string
*/
public final String getSafeString(int resId, Object... formatArgs) {
return App.sInstance.getString(resId, formatArgs);
}
}
|
package com.fanfte.myannotation.test;
import com.fanfte.myannotation.annotation.UseCase;
/**
* Created by dell on 2018/5/22
**/
public class PasswordUtil {
@UseCase(id = 99, description = "password ")
public String encodePassword(String password) {
return new StringBuffer(password).toString();
}
@UseCase(id = 100, description = "new Username")
public String reNameUser(String username) {
return username + "rename";
}
}
|
package com.developworks.jvmcode;
/**
* <p>Title: invokedynamic</p>
* <p>Description: 调用动态方法</p>
* <p>Author: ouyp </p>
* <p>Date: 2018-05-19 23:15</p>
*/
public class invokedynamic {
public void invokedynamic(Object[] args) {
Runnable r = () -> {};
}
}
/**
* public void invokedynamic(java.lang.Object[]);
* Code:
* 0: invokedynamic #2, 0 // InvokeDynamic #0:run:()Ljava/lang/Runnable;
* 5: astore_2
* 6: return
*/
|
package com.cn.ouyjs.thread.modelTest;
/**
* @author ouyjs
* @date 2019/7/4 10:49
*/
public class ConsumerTest extends Thread{
private static final int SIZE = 20;
private Goods goods;
public ConsumerTest(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long)(Math.random()*500));
goods.removeGoods();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package br.com.douglastuiuiu.biometricengine.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* @author douglasg
* @since 10/03/2017
*/
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(localDateTime.toString());
}
}
|
package Articles;
import Attributes.Attribute;
import Attributes.WebpageTag;
import Utils.Data;
import java.util.ArrayList;
public class Webpage extends Article{
WebpageTag tag;
String url;
public Webpage(){super(new ArrayList<>());}
public Webpage(ArrayList<Attribute> a) {super(a);}
public Webpage(WebpageTag tag, String url){
super(new ArrayList<>());
this.tag=tag;
this.url=url;
attributes.add(tag);
}
public Webpage(String url){
super(new ArrayList<>());
this.url=url;
}
public Webpage(WebpageTag possTag){
super(new ArrayList<>());
for(Webpage cur: Data.webpages){
if(cur.tag.equalsTo(possTag)){
this.tag=cur.tag;
this.url=cur.url;
attributes.add(tag);
break;
}
}
}
public Webpage(String t, String u){
super(new ArrayList<>());
this.tag = new WebpageTag(t);
this.url=u;
attributes.add(tag);
}
public void setUrl(String u){url=u;}
public String getUrl(){return url;}
public String toString(){
if(url==null&&tag==null){
return "Webpage";
}
return tag+" "+url;}
}
|
package irix.measurement.service;
import irix.measurement.structure.Measurement;
public interface MeasurementsImp {
Measurement getMeasurement();
}
|
package aquarium.jellies;
public class Jelly {
}
|
package com.maxmind.geoip2.model;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.maxmind.db.MaxMindDbConstructor;
import com.maxmind.db.MaxMindDbParameter;
import com.maxmind.db.Network;
import com.maxmind.geoip2.NetworkDeserializer;
/**
* This class provides the GeoLite2 ASN model.
*/
public class AsnResponse extends AbstractResponse {
private final Long autonomousSystemNumber;
private final String autonomousSystemOrganization;
private final String ipAddress;
private final Network network;
@MaxMindDbConstructor
public AsnResponse(
@JsonProperty("autonomous_system_number")
@MaxMindDbParameter(name = "autonomous_system_number") Long autonomousSystemNumber,
@JsonProperty("autonomous_system_organization")
@MaxMindDbParameter(name = "autonomous_system_organization")
String autonomousSystemOrganization,
@JacksonInject("ip_address") @JsonProperty("ip_address")
@MaxMindDbParameter(name = "ip_address") String ipAddress,
@JacksonInject("network") @JsonProperty("network")
@JsonDeserialize(using = NetworkDeserializer.class) @MaxMindDbParameter(name = "network")
Network network
) {
this.autonomousSystemNumber = autonomousSystemNumber;
this.autonomousSystemOrganization = autonomousSystemOrganization;
this.ipAddress = ipAddress;
this.network = network;
}
public AsnResponse(
AsnResponse response,
String ipAddress,
Network network
) {
this(
response.getAutonomousSystemNumber(),
response.getAutonomousSystemOrganization(),
ipAddress,
network
);
}
/**
* @return The autonomous system number associated with the IP address.
*/
@JsonProperty("autonomous_system_number")
public Long getAutonomousSystemNumber() {
return this.autonomousSystemNumber;
}
/**
* @return The organization associated with the registered autonomous system
* number for the IP address
*/
@JsonProperty("autonomous_system_organization")
public String getAutonomousSystemOrganization() {
return this.autonomousSystemOrganization;
}
/**
* @return The IP address that the data in the model is for.
*/
@JsonProperty("ip_address")
public String getIpAddress() {
return this.ipAddress;
}
/**
* @return The network associated with the record. In particular, this is
* the largest network where all the fields besides IP address have the
* same value.
*/
@JsonProperty
@JsonSerialize(using = ToStringSerializer.class)
public Network getNetwork() {
return this.network;
}
}
|
package com.lsjr.zizisteward.activity.home.presenter;
import com.lsjr.zizisteward.http.callback.SubscriberCallBack;
import com.lsjr.net.DcodeService;
import com.lsjr.zizisteward.activity.home.view.IHomeView;
import com.ymz.baselibrary.mvp.BasePresenter;
import com.ymz.baselibrary.utils.L_;
import com.ymz.baselibrary.utils.T_;
import java.util.Map;
/**
* Created by admin on 2017/5/16.
*/
public class HomePresenter extends BasePresenter<IHomeView> {
public HomePresenter(IHomeView mvpView) {
super(mvpView);
}
/*环信登陆*/
public void easeLogin(Map<String,String> map){
addSubscription(DcodeService.getServiceData(map), new SubscriberCallBack() {
@Override
protected void onError(Exception e) {
T_.showToastReal("请求失败");
}
@Override
protected void onFailure(String response) {
}
@Override
protected void onSuccess(String response) {
mvpView.easeLoignSucceed(response);
}
});
}
public void getHomePager(Map map){
addSubscription(DcodeService.getServiceData(map), new SubscriberCallBack() {
@Override
protected void onSuccess(String response) {
L_.e("getHomePager"+response);
mvpView.getPageDataSucceed(response);
}
@Override
protected void onError(Exception e) {
L_.e("getHomePager Exception");
}
@Override
protected void onFailure(String response) {
L_.e("getHomePager"+response);
mvpView.getPageDataSucceed(response);
}
});
}
}
|
package com.pce.BookMeTutor.Repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.pce.BookMeTutor.Model.Dao.AddressEntity;
@Repository
public interface AddressRepo extends JpaRepository<AddressEntity, Long> {
}
|
package GUI.controller;
import java.io.IOException;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import negocios.PanelaFit;
import negocios.beans.Funcionario;
import javafx.scene.control.cell.PropertyValueFactory;
import javax.xml.bind.ValidationException;
import javafx.scene.input.MouseEvent;
import exceptions.FuncionarioJaExisteException;
import exceptions.FormatacaoInvalidaException;
import exceptions.FuncionarioNaoExisteException;
public class FuncionarioPaneController {
@FXML
private Label lblMensagem;
private PanelaFit panelaFit;
@FXML
Button butCadastrar;
@FXML
private TextField txtNomeFuncionario;
@FXML
private TextField txtCpfFuncionario;
@FXML
private TextField txtIdadeFuncionario;
@FXML
private TextField txtEnderecoFuncionario;
@FXML
private TextField txtTelefoneFuncionario;
@FXML
private TextField txtCodigoFuncionario;
@FXML
private ChoiceBox<Integer> cbNivel = new ChoiceBox<Integer>(FXCollections.observableArrayList(1, 2, 3, 4, 5, 6));
@FXML
private TableView<Funcionario> tabelaFuncionarios;
@FXML
TableColumn<Funcionario, String> colunaNome;
@FXML
TableColumn<Funcionario, String> colunaCpf;
@FXML
TableColumn<Funcionario, String> colunaIdade;
@FXML
TableColumn<Funcionario, String> colunaEndereco;
@FXML
TableColumn<Funcionario, String> colunaTelefone;
@FXML
TableColumn<Funcionario, String> colunaCodigo;
@FXML
TableColumn<Funcionario, String> colunaNivel;
private ObservableList<Funcionario> data;
public void sair(ActionEvent event) {
((Node) event.getSource()).getScene().getWindow().hide();
}
public void voltarMenuPrincipal(ActionEvent event) {
((Node) event.getSource()).getScene().getWindow().hide();
Parent parent;
try {
parent = FXMLLoader.load(getClass().getResource("/GUI/view/PanelaFit.fxml"));
Stage stage3 = new Stage();
Scene cena = new Scene(parent);
stage3.setScene(cena);
stage3.show();
} catch (IOException e) {
lblMensagem.setText(e.getMessage());
}
}
public void cadastrarFuncionario() throws ValidationException, IOException {
if (validateFields()) {
try {
String nome, cpf, endereco, telefone;
Integer idade = new Integer(txtIdadeFuncionario.getText());
Integer codigo = new Integer(txtCodigoFuncionario.getText());
Integer nivel = new Integer(cbNivel.getSelectionModel().getSelectedItem());
nome = txtNomeFuncionario.getText();
cpf = txtCpfFuncionario.getText();
endereco = txtEnderecoFuncionario.getText();
telefone = txtTelefoneFuncionario.getText();
System.out.println(cpf);
cpf = cpf.replace(".", "").replace("-", "");
System.out.println(cpf);
System.out.println(telefone);
telefone = telefone.replace("(", "").replace(")", "").replace("-", "");
System.out.println(telefone);
Funcionario aux = new Funcionario(nivel, codigo, nome, cpf, idade, endereco, telefone);
validateAttributes(aux);
panelaFit.cadastrarFuncionario(aux);
refreshTable();
limparForm();
lblMensagem.setText("Funcionario cadastrado");
} catch (FormatacaoInvalidaException e) {// funcionando
lblMensagem.setText(e.getMessage());
} catch (FuncionarioJaExisteException e) {
lblMensagem.setText(e.getMessage());
}
}
}
public void removerFuncionario() throws FormatacaoInvalidaException, IOException {
Funcionario funcionarioSelecionado = tabelaFuncionarios.getSelectionModel().getSelectedItem();
try {
if (funcionarioSelecionado != null) {
Integer codig = new Integer(funcionarioSelecionado.getCodigo());
if (panelaFit.existeFuncionario(codig)) {
panelaFit.removerFuncionario(funcionarioSelecionado);
tabelaFuncionarios.getItems().remove(tabelaFuncionarios.getSelectionModel().getSelectedIndex());
limparForm();
refreshTable();
lblMensagem.setText("Funcionario Removido");
}
} else {
Integer code = new Integer(txtCodigoFuncionario.getText());
if (panelaFit.existeFuncionario(code)) {
Funcionario aux = panelaFit.buscarFuncionario(code);
panelaFit.removerFuncionario(aux);
refreshTable();
limparForm();
lblMensagem.setText("Funcionario Removido");
}
}
} catch (FuncionarioNaoExisteException e) {
lblMensagem.setText(e.getMessage());
} catch (NumberFormatException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
}
}
public void alterarFuncionario()
throws FuncionarioNaoExisteException, FormatacaoInvalidaException, ValidationException, IOException {
if (validateFields()) {
try {
String nome, cpf, endereco, telefone;
Integer idade = new Integer(txtIdadeFuncionario.getText());
Integer codigo = new Integer(txtCodigoFuncionario.getText());
Integer nivel = new Integer(cbNivel.getSelectionModel().getSelectedItem());
nome = txtNomeFuncionario.getText();
cpf = txtCpfFuncionario.getText();
endereco = txtEnderecoFuncionario.getText();
telefone = txtTelefoneFuncionario.getText();
cpf = cpf.replace(".", "").replace("-", "");
telefone = telefone.replace("(", "").replace(")", "").replace("-", "");
Funcionario aux = new Funcionario(nivel, codigo, nome, cpf, idade, endereco, telefone);
validateAttributes(aux);
panelaFit.alterarFuncionario(aux);
refreshTable();
limparForm();
lblMensagem.setText("Funcionario aletrado");
} catch (FormatacaoInvalidaException e) {// funcionando
lblMensagem.setText(e.getMessage());
} catch (FuncionarioNaoExisteException e) {
lblMensagem.setText(e.getMessage());
}
}
}
public void setDados(ObservableList<Funcionario> dadosFuncionario) {
tabelaFuncionarios.setItems(dadosFuncionario);
}
@FXML
private void initialize() {
panelaFit = PanelaFit.getInstance();
colunaNome.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getNome()));
colunaCpf.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getCpf()));
colunaIdade.setCellValueFactory(new PropertyValueFactory<Funcionario, String>("idade"));
colunaEndereco.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getEndereco()));
colunaTelefone.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getTelefone()));
colunaCodigo.setCellValueFactory(new PropertyValueFactory<Funcionario, String>("codigo"));
colunaNivel.setCellValueFactory(new PropertyValueFactory<Funcionario, String>("nivel"));
cbNivel.getItems().addAll(1, 2, 3, 4, 5, 6);
data = FXCollections.observableArrayList();
data.addAll(panelaFit.listarFuncionarios());
tabelaFuncionarios.setItems(data);
}
@FXML
public void limparForm() {
txtNomeFuncionario.clear();
txtCpfFuncionario.clear();
txtIdadeFuncionario.clear();
txtEnderecoFuncionario.clear();
txtTelefoneFuncionario.clear();
txtCodigoFuncionario.clear();
txtCodigoFuncionario.editableProperty().set(true);
txtCodigoFuncionario.setStyle(null);
txtNomeFuncionario.setStyle(null);
cbNivel.setStyle(null);
cbNivel.getSelectionModel().clearSelection();
lblMensagem.setText(null);
tabelaFuncionarios.getSelectionModel().clearSelection();
}
private void validateAttributes(Funcionario funcionario) throws ValidationException {
String returnMs = "";
Integer idade = funcionario.getIdade();
Integer codigo = funcionario.getCodigo();
Integer nivel = funcionario.getNivel();
if (funcionario.getNome() == null || funcionario.getNome().isEmpty()) {
returnMs += "'Nome' ";
}
if (funcionario.getCpf() == null || funcionario.getCpf().isEmpty()) {
returnMs += "'CPF' ";
}
if (idade.toString() == null || idade.toString().isEmpty()) {
returnMs += "'Idade' ";
}
if (funcionario.getEndereco() == null || funcionario.getEndereco().isEmpty()) {
returnMs += "'Endereço' ";
}
if (funcionario.getTelefone() == null || funcionario.getTelefone().isEmpty()) {
returnMs += "'Telefone' ";
}
if (nivel.toString() == null || nivel.toString().isEmpty()) {
returnMs += "'Nivel' ";
}
if (codigo.toString() == null || codigo.toString().isEmpty()) {
returnMs += "'Codigo' ";
}
if (!returnMs.isEmpty()) {
throw new ValidationException(
String.format("Os argumento[%s] obrigatorios estao nulos ou com valores invalidos", returnMs));
}
}
private boolean validateFields() throws IOException {
boolean validate = false;
try {
if ((txtNomeFuncionario.getText().isEmpty() || !txtNomeFuncionario.getText().matches("[a-z A-Z]+"))
|| (txtCpfFuncionario.getText().isEmpty() || !txtCpfFuncionario.getText()
.matches("[0-9][0-9][0-9].[0-9][0-9][0-9].[0-9][0-9][0-9]-[0-9][0-9]"))
|| (txtTelefoneFuncionario.getText().isEmpty() || !txtTelefoneFuncionario.getText()
.matches("[(][0-9][0-9][)][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"))
|| (txtIdadeFuncionario.getText().isEmpty() || !txtIdadeFuncionario.getText().matches("[0-9][0-9]"))
|| txtEnderecoFuncionario.getText().isEmpty()
|| (txtCodigoFuncionario.getText().isEmpty()
|| !txtCodigoFuncionario.getText().matches("[0-9][0-9][0-9][0-9][0-9]"))
|| cbNivel.getSelectionModel().isEmpty()) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
if (txtNomeFuncionario.getText().isEmpty() || !txtNomeFuncionario.getText().matches("[a-z A-Z]+")) {
txtNomeFuncionario.setStyle("-fx-background-color: red;");
}
if (cbNivel.getSelectionModel().isEmpty()) {
cbNivel.setStyle("-fx-background-color: red;");
}
} else {
lblMensagem.setText("DEU");
validate = true;
}
} catch (NumberFormatException e) {
e.getMessage();
}
return validate;
}
@FXML
private void refreshTable() {
data = FXCollections.observableArrayList();
data.addAll(panelaFit.listarFuncionarios());
tabelaFuncionarios.setItems(data);
}
@FXML
public void selecionarFuncionario(MouseEvent arg0) {
if (!tabelaFuncionarios.getSelectionModel().isEmpty()) {
Funcionario f = tabelaFuncionarios.getSelectionModel().getSelectedItem();
Integer codigo = f.getCodigo();
Integer idade = f.getIdade();
Integer nivel = f.getNivel();
txtNomeFuncionario.setText(f.getNome());
txtCpfFuncionario.setText(f.getCpf());
txtEnderecoFuncionario.setText(f.getEndereco());
txtTelefoneFuncionario.setText(f.getTelefone());
txtCodigoFuncionario.setText(codigo.toString());
cbNivel.getSelectionModel().select(nivel);
txtIdadeFuncionario.setText(idade.toString());
char[] a = txtCpfFuncionario.getText().toCharArray();
String cpf = "";
for (int i = 0; i < a.length; i++) {
if (i == 2 || i == 5) {
cpf += a[i] + ".";
} else if (i == 8) {
cpf += a[i] + "-";
} else {
cpf += a[i];
}
}
txtCpfFuncionario.setText(cpf);
char[] b = txtTelefoneFuncionario.getText().toCharArray();
String telefone = "";
for (int i = 0; i < b.length; i++) {
if (i == 0) {
telefone += "(" + b[i];
} else if (i == 1) {
telefone += b[i] + ")";
} else if (i == 6) {
telefone += b[i] + "-";
} else {
telefone += b[i];
}
}
txtTelefoneFuncionario.setText(telefone);
txtCodigoFuncionario.editableProperty().set(false);
txtCodigoFuncionario.setStyle("-fx-background-color: grey;");
}
}
@FXML
public void buscarFuncionario() throws FuncionarioNaoExisteException, IOException {
Funcionario f;
try {
Integer code = new Integer(txtCodigoFuncionario.getText());
f = panelaFit.buscarFuncionario(code);
Integer codigo = f.getCodigo();
Integer nivel = f.getNivel();
Integer idade = f.getIdade();
txtNomeFuncionario.setText(f.getNome());
txtCpfFuncionario.setText(f.getCpf());
txtEnderecoFuncionario.setText(f.getEndereco());
txtTelefoneFuncionario.setText(f.getTelefone());
txtCodigoFuncionario.setText(codigo.toString());
cbNivel.getSelectionModel().select(nivel);
txtIdadeFuncionario.setText(idade.toString());
char[] a = txtCpfFuncionario.getText().toCharArray();
String cpf = "";
for (int i = 0; i < a.length; i++) {
if (i == 2 || i == 5) {
cpf += a[i] + ".";
} else if (i == 8) {
cpf += a[i] + "-";
} else {
cpf += a[i];
}
}
txtCpfFuncionario.setText(cpf);
char[] b = txtTelefoneFuncionario.getText().toCharArray();
String telefone = "";
for (int i = 0; i < b.length; i++) {
if (i == 0) {
telefone += "(" + b[i];
} else if (i == 1) {
telefone += b[i] + ")";
} else if (i == 6) {
telefone += b[i] + "-";
} else {
telefone += b[i];
}
}
txtTelefoneFuncionario.setText(telefone);
txtCodigoFuncionario.editableProperty().set(false);
txtCodigoFuncionario.setStyle("-fx-background-color: grey;");
} catch (NumberFormatException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
} catch (FuncionarioNaoExisteException e) {
lblMensagem.setText(e.getMessage());
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.correccion.Repository;
import com.example.correccion.Model.Empleado;
import org.springframework.data.jpa.repository.JpaRepository;
/**
*
* @author usuario
*/
public interface EmpleadoRepository extends JpaRepository<Empleado,Long>{
}
|
package framework;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tuples.generated.Tuple2;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
/**
* <p>Auto generated code.
* <p><strong>Do not modify!</strong>
* <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
* or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*
* <p>Generated with web3j version 3.2.0.
*/
public class TestContractOne extends Contract {
private static final String BINARY = "6060604052341561000f57600080fd5b6102dc8061001e6000396000f30060606040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663993a04b78114610050578063f5dce133146100e2575b600080fd5b341561005b57600080fd5b610063610137565b6040518080602001838152602001828103825284818151815260200191508051906020019080838360005b838110156100a657808201518382015260200161008e565b50505050905090810190601f1680156100d35780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b34156100ed57600080fd5b61013560046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965050933593506101e992505050565b005b61013f610203565b600080600154818054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101da5780601f106101af576101008083540402835291602001916101da565b820191906000526020600020905b8154815290600101906020018083116101bd57829003601f168201915b50505050509150915091509091565b60008280516101fc929160200190610215565b5060015550565b60206040519081016040526000815290565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061025657805160ff1916838001178555610283565b82800160010185558215610283579182015b82811115610283578251825591602001919060010190610268565b5061028f929150610293565b5090565b6102ad91905b8082111561028f5760008155600101610299565b905600a165627a7a7230582053c79e8692bf88a3e4d1f4328f7bd1cf03bfd6e41032816c60102e6f7f4f669d0029";
protected TestContractOne(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}
protected TestContractOne(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
public RemoteCall<Tuple2<String, BigInteger>> getter() {
final Function function = new Function("getter",
Arrays.<Type>asList(),
Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}, new TypeReference<Uint256>() {}));
return new RemoteCall<Tuple2<String, BigInteger>>(
new Callable<Tuple2<String, BigInteger>>() {
@Override
public Tuple2<String, BigInteger> call() throws Exception {
List<Type> results = executeCallMultipleValueReturn(function);;
return new Tuple2<String, BigInteger>(
(String) results.get(0).getValue(),
(BigInteger) results.get(1).getValue());
}
});
}
public RemoteCall<TransactionReceipt> setter(String _name, BigInteger _age) {
Function function = new Function(
"setter",
Arrays.<Type>asList(new Utf8String(_name),
new Uint256(_age)),
Collections.<TypeReference<?>>emptyList());
return executeRemoteCallTransaction(function);
}
public static RemoteCall<TestContractOne> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return deployRemoteCall(TestContractOne.class, web3j, credentials, gasPrice, gasLimit, BINARY, "");
}
public static RemoteCall<TestContractOne> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return deployRemoteCall(TestContractOne.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "");
}
public static TestContractOne load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return new TestContractOne(contractAddress, web3j, credentials, gasPrice, gasLimit);
}
public static TestContractOne load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return new TestContractOne(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
}
|
import java.util.Arrays;
/**
* AP CS MOOC Term 2 - Assignment 2, Part 1: Boxcar A class which represents a
* single car on a freight train.
*/
public class Boxcar {
// Variables that will be initialized in the Boxcar constructors.
private String cargo = "";
private int numUnits;
private boolean repair;
public static final String[] cargoType = { "gizmos", "gadgets", "widgets", "wadgets" };
/**
* Default constructor that sets the boxcar to "gizmos", 5, and false.
*/
public Boxcar()
{
this.cargo = "gizmos";
this.numUnits = 5;
this.repair = false;
}
/**
* This constructor sets the cargo variable to the parameter c, but only if c is
* "gizmos", "gadgets", "widgets", or "wadgets". The constructor ignores the
* case of the value in c. If c holds any value other than "gizmos", "gadgets",
* "widgets", or "wadgets", the constructor sets cargo to "gizmos". The numUnits
* variable is set to the parameter u. If u is less than 0 or higher than the
* maximum capacity of 10 units, numUnits is set to 0. The repair variable is
* set to the parameter r. If repair is true, numUnits is set to 0 no matter
* what value is stored in the u parameter.
*
* @param c cargo
* @param u unit
* @param r repair
*/
public Boxcar(String c, int u, boolean r)
{
this.setCargo(c);
this.repair = r;
this.numUnits = u <= 10 && u >= 0 && !r ? u : 0;
}
/**
* The toString method returns a String with the Boxcar in the format: 5 gizmos
* in service 10 widgets in service 0 gadgets in repair
*
* Notice there is one space in between the number of units and the cargo and a
* tab between the value for cargo and "in repair"/"in service"
*
* @return String
*/
@Override
public String toString()
{
return String.format("%d %s\tin %s", this.numUnits, this.cargo, this.repair ? "repair" : "service");
}
/**
* This method adds 1 to the number of units in the BoxCar. The maximum capacity
* of a boxcar is 10 units. If increasing the number of units would go beyond
* the maximum, keep numUnits at the max capacity. If the repair variable is
* true, then numUnits may only be set to 0.
*/
public void loadCargo()
{
if (this.numUnits == 10 || this.repair)
return;
this.numUnits += 1;
}
/**
* The getCargo method returns the cargo of the boxcar.
*
* @return String
*/
public String getCargo()
{
return this.cargo;
}
/**
* The setCargo method sets the cargo type of the boxcar. The cargo variable is
* set to c only if c is "gizmos", "gadgets", "widgets", or "wadgets". The
* method ignores the case of of the value in c. If c holds any value other than
* "gizmos", "gadgets", "widgets", or "wadgets" (ignoring case), the method sets
* cargo to "gizmos".
*
* @param c String cargo type
*/
public void setCargo(String c)
{
this.cargo = Arrays.asList(cargoType).contains(c.toLowerCase()) ? c.toLowerCase() : "gizmos";
}
/**
* The isFull method returns true if numUnits is equal to 10, false otherwise.
*
* @return boolean
*/
public boolean isFull()
{
return numUnits == 10;
}
/**
* The callForRepair method sets the variable repair to true, and numUnits to 0.
*/
public void callForRepair()
{
this.repair = true;
this.numUnits = 0;
}
}
|
package com.bnrc.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.HttpEntity;
/**
* 漏 2012 amsoft.cn
* 鍚嶇О锛欰bGzipDecompressingEntity.java
* 鎻忚堪锛欻ttp瑙e帇鍐呭
*
* @author 杩樺涓�姊︿腑
* @version v1.0
* @date锛�2014-06-17 涓婂崍10:19:52
*/
public class AbGzipDecompressingEntity extends HttpEntityWrapper{
public AbGzipDecompressingEntity(final HttpEntity entity){
super(entity);
}
public InputStream getContent() throws IOException, IllegalStateException{
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
public long getContentLength(){
return -1;
}
}
|
package pt.utl.ist.bw;
import java.util.ArrayList;
import pt.utl.ist.bw.utils.CaseReceiver;
import pt.utl.ist.bw.worklistmanager.WorklistManager;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.TabSheet.SelectedTabChangeListener;
import com.vaadin.ui.TabSheet.Tab;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Tree;
import com.vaadin.ui.Upload;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
@SuppressWarnings("serial")
public class ControlPanel extends Window {
private String procName = null;
private TextField processName = new TextField("Process Name");
private VerticalLayout loadSpecs = new VerticalLayout();
private VerticalLayout runProc = null;
private VerticalLayout runningProcs = null;
private Tree loadedCases = null;
private Button launchBtn = null;
//spec receivers
private CaseReceiver caseReceiver = new CaseReceiver(this);
public ControlPanel() {
this.setCaption("Admin Panel");
// create layout
HorizontalLayout layout = new HorizontalLayout();
layout.setWidth(null);
this.setWidth("450px");
// create accordion
Accordion acc = new Accordion();
acc.setWidth("400px");
acc.setHeight(null);
acc.addListener(new SelectedTabChangeListener() {
@Override
public void selectedTabChange(SelectedTabChangeEvent event) {
TabSheet tabSheet = event.getTabSheet();
Tab tab = tabSheet.getTab(tabSheet.getSelectedTab());
if(tab != null) {
String tabCaption = tab.getCaption();
if(tabCaption.equals("Load Specifications")) {
// load the "load specs" panel
fillLoadSpecs();
} else if(tabCaption.equals("Launch Case")) {
// load the "lauch case" panel
fillRunningProcesses();
} else if(tabCaption.equals("Running processes")) {
//TODO load the "running processes" panel
}
}
}
});
acc.addTab(loadSpecs, "Load Specifications", null);
// Launch cases:
this.runProc = new VerticalLayout();
acc.addTab(runProc, "Launch Case", null);
//TODO running processes:
this.runningProcs = new VerticalLayout();
acc.addTab(runningProcs, "Running processes", null);
layout.addComponent(acc);
addComponent(layout);
}
protected void fillLoadSpecs() {
loadSpecs.removeAllComponents();
// load specifications:
loadSpecs.setSpacing(true);
loadSpecs.setMargin(true);
// process name
processName.setRequired(true);
processName.setComponentError(null);
processName.setWidth("12em");
processName.setNullRepresentation("");
Button procNameBtn = new Button("Submit");
// add listener
procNameBtn.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if(!processName.isValid()) {
processName.setComponentError(new UserError("Please enter a valid name"));
return;
}
procName = (String) processName.getValue();
addUploads();
}
});
//add to the layout
loadSpecs.addComponent(processName);
loadSpecs.addComponent(procNameBtn);
}
protected void addUploads() {
loadSpecs.removeAllComponents();
// add title
Label title = new Label("<b>Upload the specifications for the <i>" + procName + "</i> case:</b>");
title.setContentMode(Label.CONTENT_XHTML);
loadSpecs.addComponent(title);
this.caseReceiver.initCase(procName);
// load activity specification (upload)
Upload uploadActivity = new Upload("Upload the activity specification here:", this.caseReceiver.getActivitySpecReceiver());
uploadActivity.setButtonCaption("Submit");
uploadActivity.addListener((Upload.SucceededListener) this.caseReceiver.getActivitySpecReceiver());
uploadActivity.addListener((Upload.FailedListener) this.caseReceiver.getActivitySpecReceiver());
// load goal specification (upload)
Upload uploadBW = new Upload("Upload the Blended Workflow specification here:", this.caseReceiver.getBWSpecReceiver());
uploadBW.setButtonCaption("Submit");
uploadBW.addListener((Upload.SucceededListener) this.caseReceiver.getBWSpecReceiver());
uploadBW.addListener((Upload.FailedListener) this.caseReceiver.getBWSpecReceiver());
loadSpecs.addComponent(uploadActivity);
loadSpecs.addComponent(uploadBW);
Button uploadBtn = new Button("Upload");
uploadBtn.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
String errors = caseReceiver.uploadSpec();
if(errors != null) {
getWindow().showNotification(errors, Notification.TYPE_ERROR_MESSAGE);
return;
}
getWindow().showNotification("Both specifications uploaded successfuly");
}
});
loadSpecs.addComponent(uploadBtn);
loadSpecs.setComponentAlignment(uploadBtn, Alignment.TOP_RIGHT);
}
protected void fillRunningProcesses() {
runProc.removeAllComponents();
this.loadedCases = new Tree("Loaded cases:");
this.runProc.addComponent(loadedCases);
loadedCases.setImmediate(true);
// get the loaded cases from the worklist manager
ArrayList<BWCase> cases = WorklistManager.get().getLoadedCases();
for (BWCase bwCase : cases) {
String caseName = bwCase.getCaseName();
// String yawlCaseName = bwCase.getYAWLSpecName();
// String bwCaseName = bwCase.getBWSpecName();
loadedCases.addItem(caseName);
loadedCases.setChildrenAllowed(caseName, false);
// loadedCases.addItem(yawlCaseName);
// loadedCases.addItem(bwCaseName);
// loadedCases.setParent(caseName, yawlCaseName);
// loadedCases.setParent(caseName, bwCaseName);
// loadedCases.setChildrenAllowed(bwCaseName, false);
// loadedCases.setChildrenAllowed(yawlCaseName, false);
}
loadedCases.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
if(event.getProperty().getValue() != null) {
if(loadedCases.getParent(event.getProperty().getValue()) == null) {
// it's a root item, enable the button
launchBtn.setEnabled(true);
} else {
launchBtn.setEnabled(false);
}
}
}
});
this.launchBtn = new Button("Launch case");
launchBtn.setEnabled(false);
runProc.addComponent(launchBtn);
runProc.setComponentAlignment(launchBtn, Alignment.TOP_RIGHT);
runProc.setMargin(true);
// add listener
this.launchBtn.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
// request Worklist Manager to launch a case
if(WorklistManager.get().launchCase((String)loadedCases.getValue())) {
getApplication().getMainWindow().showNotification("Case launched successfully");
ControlPanel.this.close();
} else {
getApplication().getMainWindow().showNotification("Could not launch the case", Notification.TYPE_ERROR_MESSAGE);
}
}
});
}
/////// FOR TESTING PURPOSES ///////
protected void setProcName(String name) {
this.procName = name;
}
}
|
import java.util.*; //Import all the classes in the java.util package was//
public class Main { //Defined Main class//
private static Scanner sc; //sc variable was created in the class to read the user.//
public static void main(String args[])
{
int k; //Generated in integer variables//
int i = 0;
int value=0;
int length=0;
int value1=0;
int value2;
int selection=0;
int[] number = new int [100]; //Generated in integer array//
int[] number1 = new int [100];
while(i!=5){ //The menu printed//
System.out.println("---------------------------------------");
System.out.println("1. Factorial");
System.out.println("2. Fibonacci");
System.out.println("3. Armstrong Numbers");
System.out.println("4. Sorting");
System.out.println("5. Exit");
System.out.println("---------------------------------------");
System.out.print("Selection:");
sc = new Scanner(System.in); //Asked for the number to be read from memory location//
i = sc.nextInt();//Read the user number//
switch (i){
case 1: //Selection is factorial//
System.out.println("...............Factorial...............");
System.out.print("Enter value:"); // The factorial of the number value will be asked to user//
sc= new Scanner(System.in);//Asked for the number to be read from memory location//
value = sc.nextInt();
if(value<0)
System.out.println("You entered a negative number. Please enter a positive number.."); //Gives an error message in incorrect values//
else
System.out.println("Factorial of " + value +" is:" + factorial(value)); //Factorial function and number was printed screen//
System.out.println(".......................................");
break;
case 2: //Selection is Fibonacci//
System.out.println("...............Fibonacci...............");
System.out.print("Enter legth of Fibonacci sequence:");//Total number written on the screen will be prompted//
sc = new Scanner(System.in); //Asked for the number to be read from memory location//
length = sc.nextInt();
if(length<0)
System.out.println("You entered a negative number. Please enter a positive number..");//Gives an error message in incorrect values//
else{
if(length==1)
System.out.println("0");
if(length==2)
System.out.println("0 1");
if(length>2){ //Find and print the fibonacci numbers//
int[] array = new int[length]; //Generated in integer array//
array[0]=0;
array[1]=1;
System.out.print("0 1 ");
for(k=0;k<length-2;k++){
array[k+2]=array[k] + array[k+1];
System.out.print(array[k+2] + " " );
}
System.out.println("");
System.out.println(".......................................");
}
}
break;
case 3: //Selection is Armstrong Numbers//
System.out.println("...........Armstrong Numbers...........");
System.out.print("Enter value:");
sc = new Scanner(System.in);//Asked for the number to be read from memory location//
value1 = sc.nextInt();
if(value1<0)
System.out.println("You entered a negative number. Please enter a positive number..");//Gives an error message in incorrect values//
else
{ //Functions are called//
armstrong(100,1000,value1);
armstrong1(1000,10000,value1);
armstrong2(10000,100000,value1);
armstrong3(100000,1000000,value1);
armstrong4(1000000,10000000,value1);
if(value1>10000000){ //In order to increase the operating speed of the program, if used condition.//
armstrong5(10000000,100000000,value1);
armstrong6(100000000,1000000000,value1);
}
System.out.println("");
System.out.println(".......................................");
}
break;
case 4: //Selection is Sorting//
System.out.println("................Sorting................");
System.out.println("1. Ascending order");
System.out.println("2. Descending order");
System.out.print("Enter sorting type:");
sc = new Scanner(System.in);//Asked for the number to be read from memory location//
selection = sc.nextInt();
switch(selection){
case 1: //Selection is Ascending order//
System.out.println("Ascending order was selected...");
System.out.println("Enter -1 to finish");
k=0;
value2=0;
while(value2!=-1){
System.out.print("Enter value:");
sc = new Scanner(System.in);//Asked for the number to be read from memory location//
value2 = sc.nextInt();
if(value2==-1){
System.out.println(".......................................");
break;
}
else
{
number[k]= value2; //Value obtained from the user is transfered to array//
k++;
sort(number,k); //Called ascending sorting function//
}
}
for(i=0;i<number.length;i++){ //Reset all the elements of the array//
number[i]=0;
}
break;
case 2: //Selection is Descending order//
System.out.println("Descending order was selected...");
System.out.println("Enter -1 to finish");
k=0;
value2=0;
while(value2!=-1){
System.out.print("Enter value:");
sc = new Scanner(System.in);//Asked for the number to be read from memory location//
value2 = sc.nextInt();
if(value2==-1) {
System.out.println("......................................");
break;
}
else{
number1[k]= value2;//Value obtained from the user is transfered to array//
k++;
sort1(number1,k); //Called descending function//
}
}
for(i=0;i<number1.length;i++){ //Reset all the elements of the array//
number1[i]=0;
}
break;
default:
{
System.out.println("You entered wrng charecter. Please enter 1 or 2.. ");//Gives an error message in incorrect values//
break;
}
}
break;
case 5: //Selection is Exit this prongram//
System.out.print("Terminated...");
break;
default:
System.out.println("Wrong command! Please select a number from the menu..");//Gives an error message in incorrect values//
break;
}
}
}
public static int factorial(int i){ //Defined function that calculates the factorial.//
long result=1;
if((i==1)&&(i==0))
result=1;
else
for(int j=2;j<=i;j++){
result = result*j;
}
return (int) result;
}
public static int power (int a, int b) //Defined function to find the powers of a number//
{
int result=1;
for(int i=0;i<b;i++){
result=result*a;
}
return result;
}
static void sort(int []array, int k)//Ascending sort function is defined//
{
int temp;
for(int pass=1;pass<k;pass++){
for(int i=0; i<k-1;i++){
if(array[i]>array[i+1]){
temp=array[i];
array[i]=array[i+1];
array[i+1]=temp;
}
}
}
for(int j=0; j<k;j++){
System.out.print(array[j] + " ");
}
System.out.println("");
}
static void sort1(int []array, int k) //Descending sort function is defined//
{
int temp;
for(int pass=1;pass<k;pass++){
for(int i=0; i<k-1;i++){
if(array[i]<array[i+1]){
temp=array[i];
array[i]=array[i+1];
array[i+1]=temp;
}
}
}
for(int j=0; j<k;j++){
System.out.print(array[j] + " ");
}
System.out.println("");
}
public static void armstrong(int n1, int n2,int value){ //Function finds the three-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,3);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong1(int n1, int n2, int value){//Function finds the four-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,4);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong2(int n1, int n2, int value){ //Function finds the five-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,5);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong3(int n1, int n2, int value){ //Function finds the six-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,6);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong4(int n1, int n2, int value){ //Function finds the seven-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,7);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong5(int n1, int n2, int value){ //Function finds the eight-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,8);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
public static void armstrong6(int n1, int n2, int value){ //Function finds the nine-digit armstrong numbers//
for(int i=n1+1; i<n2; ++i)
{
int temp=i;
int num=0;
int rem=1;
while(temp!=0)
{
rem=(temp%10);
num+=power(rem,9);
temp/=10;
}
if((i==num)&&(i<value))
{
System.out.print(i +" ");
}
}
}
}
|
package network.nerve.converter.model.txdata;
import network.nerve.converter.utils.ConverterUtil;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class WithdrawalTxDataTest {
WithdrawalTxData withdrawalTxData;
@Before
public void setUp() throws Exception {
withdrawalTxData = new WithdrawalTxData();
//withdrawalTxData.setChainId(3);
withdrawalTxData.setHeterogeneousAddress("0xfa27c84eC062b2fF89EB297C24aaEd366079c684");
}
@Test
public void serializeAndParse() throws Exception {
byte[] bytes = withdrawalTxData.serialize();
WithdrawalTxData newObj = ConverterUtil.getInstance(bytes, WithdrawalTxData.class);
assertNotNull(newObj);
//assertEquals(newObj.getChainId(), withdrawalTxData.getChainId());
assertEquals(newObj.getHeterogeneousAddress(), withdrawalTxData.getHeterogeneousAddress());
}
}
|
package logic;
public class Map {
private int width, height;
private Robot robot;
private GameObj target;
public Map(int width, int height) {
this.width = width;
this.height = height;
}
public void update() {
robot.update(this);
}
protected int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
protected int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Robot getRobot() {
return robot;
}
public void setRobot(Robot robot) {
this.robot = robot;
}
public GameObj getTarget() {
return target;
}
public void setTarget(GameObj target) {
this.target = target;
}
}
|
/*
* LcmsSeqObjectivesServiceImpl.java 1.00 2011-09-05
*
* Copyright (c) 2011 ???? Co. All Rights Reserved.
*
* This software is the confidential and proprietary information
* of um2m. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the license agreement
* you entered into with um2m.
*/
package egovframework.adm.lcms.cts.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.excel.EgovExcelService;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.adm.lcms.cts.service.LcmsSeqObjectivesService;
import egovframework.adm.lcms.cts.dao.LcmsSeqObjectivesDAO;
import egovframework.adm.lcms.cts.domain.LcmsSeqObjectives;
/**
* <pre>
* system :
* menu :
* source : LcmsSeqObjectivesServiceImpl.java
* description :
* </pre>
* @version
* <pre>
* 1.0 2011-09-05 created by ?
* 1.1
* </pre>
*/
@Service("lcmsSeqObjectivesService")
public class LcmsSeqObjectivesServiceImpl extends EgovAbstractServiceImpl implements LcmsSeqObjectivesService {
@Resource(name="lcmsSeqObjectivesDAO")
private LcmsSeqObjectivesDAO lcmsSeqObjectivesDAO;
public List selectLcmsSeqObjectivesPageList( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.selectLcmsSeqObjectivesPageList( commandMap);
}
public int selectLcmsSeqObjectivesPageListTotCnt( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.selectLcmsSeqObjectivesPageListTotCnt( commandMap);
}
public List selectLcmsSeqObjectivesList( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.selectLcmsSeqObjectivesList( commandMap);
}
public Object selectLcmsSeqObjectives( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.selectLcmsSeqObjectives( commandMap);
}
public Object insertLcmsSeqObjectives( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.insertLcmsSeqObjectives( commandMap);
}
public int updateLcmsSeqObjectives( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.updateLcmsSeqObjectives( commandMap);
}
public int updateFieldLcmsSeqObjectives( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.updateLcmsSeqObjectives( commandMap);
}
public int deleteLcmsSeqObjectives( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.deleteLcmsSeqObjectives( commandMap);
}
public int deleteLcmsSeqObjectivesAll( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.deleteLcmsSeqObjectivesAll( commandMap);
}
public Object existLcmsSeqObjectives( LcmsSeqObjectives lcmsSeqObjectives) throws Exception {
return lcmsSeqObjectivesDAO.existLcmsSeqObjectives( lcmsSeqObjectives);
}
public Map selectLcmsSeqObjectives01( Map<String, Object> commandMap) throws Exception {
return lcmsSeqObjectivesDAO.selectLcmsSeqObjectives01( commandMap);
}
}
|
package com.github.mistertea.html5animator.service;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import com.github.mistertea.html5animator.thrift.UserSession;
import com.github.mistertea.zombiedb.DatabaseEngineManager;
import com.github.mistertea.zombiedb.IndexedDatabaseEngineManager;
import com.github.mistertea.zombiedb.engine.AstyanaxDatabaseEngine;
public class Utils {
private static IndexedDatabaseEngineManager engine = null;
@SuppressWarnings("unchecked")
public static <T> T deepCopy(T t) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(t);
oos.flush();
oos.close();
bos.close();
byte [] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
return (T) new ObjectInputStream(bais).readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static IndexedDatabaseEngineManager createDatabaseEngine(boolean readOnly) throws IOException {
/*
String dbDirectory = System.getProperty( "user.home" );
return new BerkeleyDBDatabaseEngine(dbDirectory, "MAMEHub",false,true,false,true, readOnly);
*/
if(Utils.engine==null) {
//Utils.engine = new JdbmDatabaseEngine(dbDirectory, "MAMEHub",false,true,false,true);
Utils.engine = new IndexedDatabaseEngineManager(new AstyanaxDatabaseEngine("Digi Cluster", "Html5AnimatorServer",false));
}
return Utils.engine;
}
public static void destroyDatabaseEngine() {
if(Utils.engine != null) {
try {
Utils.engine.destroy();
} catch (IOException e) {
e.printStackTrace();
}
Utils.engine = null;
}
}
}
|
package com.zxt.compplatform.authority.dao.impl;
import java.util.List;
import com.zxt.compplatform.authority.dao.UserLevelDao;
import com.zxt.compplatform.authority.entity.UserLevel;
import com.zxt.compplatform.formengine.entity.view.UserBasic;
import com.zxt.compplatform.formengine.entity.view.UserLevelBasic;
import com.zxt.framework.jdbc.ZXTJDBCTemplate;
public class UserLevelDaoImpl extends ZXTJDBCTemplate implements UserLevelDao{
/**
* 查询级别列表
*/
public List findUserLevel(int page,int rows) {
int result = judge();
String sql = "";
if(result == 1){
sql = "select id,level_name as levelname,level_number as levelnumber,level_note as levelnote " +
"from "+
"("+
"select A.*, rownum num "+
"from (select *from t_user_level) A "+
"where rownum <= "+(page*rows)+
")"+
"where num > "+(+page-1)*rows;
}else if(result == 2){
sql = "select top "+rows+" id,level_name as levelname,level_number as levelnumber,"+
"level_note as levelnote from t_user_level where id not in" +
"(select top "+rows*(page-1)+" id from t_user_level)";
}
return find(sql, UserLevelBasic.class);
}
/**
* 查询所有级别
*/
public List findAll(){
String sql = "select id,level_name as levelname, level_number as levelnumber ," +
"level_note as levelnote from t_user_level";
return find(sql, UserLevel.class);
}
/**
* 查询级别总条数
*/
public int findCount(){
String sql = "select count(*) from t_user_level";
return find(sql);
}
/**
* 删除级别
* @param id
*/
public void deleteUserLevel(String id){
String sql = "delete from t_user_level where id in("+id+")" ;
delete(sql);
}
/**
* 添加级别(级别ID查询最大值加1)
*/
public void addUserLevel(UserLevel userlevel){
String sql = "insert into t_user_level values(?,?,?,?)";
Object[] obj = new Object[]{userlevel.getId(),userlevel.getLevelname(),userlevel.getLevelnumber(),userlevel.getLevelnote()};
create(sql, obj);
}
/**
* 查询级别ID最大值
*/
public int findMaxId(){
String sql = "select max(id) as id from t_user_level t";
return find(sql);
}
/**
* 判断某名称的级别是否存在
*/
public List isExist(String name){
String sql = "select id from t_user_level where level_name = '"+name+"'";
return find(sql, UserLevel.class);
}
/**
* 判断某名称的级别是否存在(删除)
*/
public List isExist(String name ,String id){
String sql = "select id from t_user_level where level_name = '"+name+"' and id != '"+id+"'" ;
return find(sql, UserLevel.class);
}
/**
* 修改级别
*/
public void updateUserLevel(UserLevel userlevel){
String sql = "update t_user_level set level_name = ?, level_number=?,level_note = ? where id = ?";
Object[] obj = new Object[]{userlevel.getLevelname(),userlevel.getLevelnumber(),userlevel.getLevelnote(),userlevel.getId()};
update(sql, obj);
}
/**
* 根据id得到要修改某一条级别的信息
*/
public UserLevel updateUserLevelById(String id){
String sql = "select id,LEVEL_NAME as levelname ,LEVEL_NUMBER as levelnumber ,LEVEL_NOTE as levelnote from t_user_level where id = "+ id ;
List list = find(sql,UserLevel.class);
UserLevel userlevel = (UserLevel)list.get(0) ;
return userlevel ;
}
//********************************************************************
/**
* 级别下的用户列表
*/
public List getUserListUnderLevel(String levelID, int rows ,int page){
int result = judge();
String sql = "";
if(result == 1){
sql = "select * " +
"from "+
"("+
"select A.*, rownum num "+
"from (select *from user_union_view) A "+
"where A.levelid = "+levelID+" and rownum <= "+(page*rows)+
") B "+
"where B.levelid = "+levelID+" and num > "+(+page-1)*rows;
}else if(result == 2){
sql = "select top "+rows+" * " +
"from user_union_view where levelid = "+levelID+" and userid not in (select top "+rows*(page-1)+
" userid from user_union_view where levelid = "+levelID+
" order by oname asc)order by oname asc";
}
return find(sql, UserBasic.class);
}
/**
* 级别下的用户总数
*/
public int getTotleUnderLevel(String levelid){
String sql = "select count(*) from user_union_view where levelid = "+levelid;
return find(sql);
}
/**
* 用户修改级别
*/
public void updateUserLevel(String levelID ,String userid){
String sql = "update t_usertable set levelnumber = "+levelID+" where userid = "+userid;
update(sql);
}
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ChessPane extends JPanel{
//Properties
//Piece array is same as one in main program
piece[][] pieceArray = new piece[8][8];
//blnMovement will be activated if a piece is clicked upon
boolean blnMovement=false;
//X coordinate of mouse click
int intXMouseClicked;
//Y coordinate of mouse click
int intYMouseClicked;
//Array that will receieve the array from the movement method, is constantly run
int[][] movementArray;
//Array that will store the movement array
int[][] higlightArray;
//Stores the clicked piece X location on board
int intX1PieceSelected;
//Stores the clicked piece Y location on board
int intY1PieceSelected;
//Methods
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0,0,1000,1000);
g.setColor(Color.WHITE);
//Draws lines on the chessboard
g.drawLine(0,0,720,0);
g.drawLine(0,0,0,720);
g.drawLine(0,90,720,90);
g.drawLine(0,180,720,180);
g.drawLine(0,270,720,270);
g.drawLine(0,360,720,360);
g.drawLine(0,450,720,450);
g.drawLine(0,540,720,540);
g.drawLine(0,630,720,630);
g.drawLine(0,720,720,720);
g.drawLine(0,0,0,720);
g.drawLine(90,0,90,720);
g.drawLine(180,0,180,720);
g.drawLine(270,0,270,720);
g.drawLine(360,0,360,720);
g.drawLine(450,0,450,720);
g.drawLine(540,0,540,720);
g.drawLine(630,0,630,720);
g.drawLine(720,0,720,720);
int intCount=0;
int intCount2=0;
//The for loop draws all the pieces on the board
for(intCount=0;intCount<8;intCount++){
for(intCount2=0;intCount2<8;intCount2++){
while(pieceArray[intCount][intCount2]!=null){
g.setColor(Color.BLUE);
if(pieceArray[intCount][intCount2].Num()==1){
g.setColor(Color.BLUE);
g.fillRect(intCount*90,intCount2*90,90,90);
}
g.setColor(Color.GREEN);
if(pieceArray[intCount][intCount2].Num()==2){
g.setColor(Color.GREEN);
g.fillRect(intCount*90,intCount2*90,90,90);
}
g.setColor(Color.RED);
if(pieceArray[intCount][intCount2].Num()==3){
g.setColor(Color.RED);
g.fillRect(intCount*90,intCount2*90,90,90);
}
g.setColor(Color.ORANGE);
if(pieceArray[intCount][intCount2].Num()==4){
g.setColor(Color.ORANGE);
g.fillRect(intCount*90,intCount2*90,90,90);
}
g.setColor(Color.CYAN);
if(pieceArray[intCount][intCount2].Num()==5){
g.setColor(Color.CYAN);
g.fillRect(intCount*90,intCount2*90,90,90);
}
if(pieceArray[intCount][intCount2].Num()==6){
g.setColor(Color.YELLOW);
g.fillRect(intCount*90,intCount2*90,90,90);
}
break;
}
g.setColor(Color.BLACK);
}
}
/*if(move[intX][intY]==1){
pieceArray[intX][intY]=pieceArray[intX1][intY1];
pieceArray[intX1][intY1]=null;
}*/
//Activated if a tile is clicked
if(blnMovement){
//Check that tile has a piece
if(pieceArray[intXMouseClicked][intYMouseClicked]!=null){
//Determines movement of the piece
movementArray=pieceArray[intXMouseClicked][intYMouseClicked].checkMove(intXMouseClicked,intYMouseClicked,pieceArray);
for(intCount=0;intCount<8;intCount++){
for(intCount2=0;intCount2<8;intCount2++){
//For loops will highlight tiles piece can move
if(movementArray[intCount][intCount2]==1){
g.setColor(Color.PINK);
g.fillRect(intCount*90,intCount2*90,90,90);
//Stores highlight array
higlightArray=movementArray;
intX1PieceSelected=intXMouseClicked;
intY1PieceSelected=intXMouseClicked;
blnMovement=false;
}
}
}
}
}
}
//Constructor
public ChessPane(){
super();
}
}
|
package com.android.wendler.wendlerandroid.di.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.android.wendler.wendlerandroid.main.model.User;
import com.google.gson.Gson;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by QiFeng on 6/29/17.
*/
@Module
public class AppModule {
private Context mContext;
public AppModule(Context context){
mContext = context;
}
@Provides
@Singleton
public Context providesContext(){
return mContext;
}
@Provides
@Singleton
public SharedPreferences providesSharedPreferences(Context context){
return PreferenceManager.getDefaultSharedPreferences(context);
}
@Provides
@Singleton
public User providesUser(SharedPreferences sharedPreferences, Gson gson){
return User.loadFromSP(sharedPreferences, gson);
}
}
|
package com.flavio.android.petlegal.model;
public class Usuario {
private int idPessoa;
private int tipo;
private int cpf;
private String senha;
private int status;
//Construtor completo
public Usuario(int id,int tipo, int cpf, String senha,int status){
this.idPessoa = id;
this.tipo = tipo;
this.cpf = cpf;
this.senha = senha;
this.status =status;
}
public Usuario(Usuario user){
this.idPessoa = user.getIdPessoa ();
this.tipo = user.getTipo ();
this.cpf = user.getCpf ();
this.senha = user.getSenha ();
this.status = user.getStatus ();
}
//Construtor recebendo login e senha
public Usuario(int cpf, String senha,int tipo){
this.idPessoa = 0;
this.tipo = tipo;
this.cpf = cpf;
this.senha = senha;
this.status = 1;
}
//Construtor sem argumentos
public Usuario(){
this.idPessoa = -1;
this.tipo = 1;
this.cpf = -1;
this.senha = "";
this.status = 0;
}
public int getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(int idPessoa) {
this.idPessoa = idPessoa;
}
public int getCpf() {
return cpf;
}
public void setCpf(int cpf) {
this.cpf = cpf;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString(){
String txtStatus ;
if(this.status ==0){
txtStatus = "(Inativo)";
}else
txtStatus = " Ativo";
String txtTipo;
switch (this.getTipo ()){
case 1:
txtTipo = "Administrador";
break;
case 2:
txtTipo = "Funcionario";
break;
default:
txtTipo = "Usuario";
}
return "ID: "+this.getIdPessoa ()+" - Usuario: "+this.getCpf () +" ("+txtTipo+") "+txtStatus;
}
}
|
package com.nowcoder.community.service;
import com.nowcoder.community.dao.AlphaDao;
import com.nowcoder.community.dao.DiscussionPostMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.PostMapping;
@Service
public class AlphaService {
@Autowired
private UserMapper userMapper;
@Autowired
private DiscussionPostMapper discussionPostMapper;
@Autowired
private TransactionTemplate transactionTemplate;
@Transactional(isolation =Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void save(){
User user = new User();
user.setUsername("GG");
user.setActivationCode("123456");
user.setStatus(0);
user.setHeaderUrl("???");
user.setType(0);
userMapper.insertUser(user);
DiscussPost discussPost = new DiscussPost();
discussPost.setType(0);
discussPost.setContent("131321");
discussionPostMapper.insertDiscussPost(discussPost);
}
public Object save1(){
transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
return transactionTemplate.execute(
new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus transactionStatus) {
User user = new User();
user.setUsername("MM");
user.setActivationCode("123456");
user.setStatus(0);
user.setHeaderUrl("???");
user.setType(0);
userMapper.insertUser(user);
DiscussPost discussPost = new DiscussPost();
discussPost.setType(0);
discussPost.setContent("fdfdfd1");
discussionPostMapper.insertDiscussPost(discussPost);
Integer.valueOf("fdkdf");
return "ok";
}
});
}
}
|
package com.tugofwar;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class Player {
private String name;
private int score;
private int id;
private FriendsList friendslist;
public Player(String name, int score, int id, FriendsList f) {
this.name = name;
this.score = score;
this.id = id;
this.friendslist = f;
}
public void addFriend(Player p) {
this.friendslist.addPlayer(p);
}
public void removeFriend(Player p) {
this.friendslist.removePlayer(p);
}
@Override
public String toString() {
return "Player [name=" + name + ", score=" + score + "]";
}
// Getters & Setters Below
/**
* Work on getting getFriendsList to work
*/
public FriendsList getFriendsList() {
Supplier<TreeSet<Player>> supplier = () -> new TreeSet<>(new PlayerComparator());
return friendslist;
//return friendslist.stream().limit(3).collect(Collectors.toCollection(supplier));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
import java.util.Arrays;
/*
* @lc app=leetcode.cn id=57 lang=java
*
* [57] 插入区间
*/
// @lc code=start
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
int index = -1;
int[][] res = new int[intervals.length + 1][2];
int i = 0;
// 将newInterval开始前的的interval都加入res
for (i = 0; i < intervals.length; i++) {
if (intervals[i][0] < newInterval[0])
res[++index] = intervals[i];
else {
// index可能为-1
if (index == -1) {
res[++index] = newInterval;
} else {
if (newInterval[0] <= res[index][1])
if (newInterval[1] <= res[index][1]) {
// newInterval在res的其中一个区间内,可直接返回
// return intervals;
return Arrays.copyOfRange(intervals, 0, intervals.length);
} else
res[index][1] = newInterval[1];
else
res[++index] = newInterval;
}
break;
}
}
// newInterval区间在intervals所有区间的后面
if (i == intervals.length) {
if (intervals.length == 0)
res[++index] = newInterval;
else {
if (newInterval[0] > res[index][1])
res[++index] = newInterval;
else if (newInterval[1] > res[index][1])
res[index][1] = newInterval[1];
}
}
for (; i < intervals.length; i++) {
if (intervals[i][0] <= res[index][1]) {
if (intervals[i][1] > res[index][1])
res[index][1] = intervals[i][1];
} else {
res[++index] = intervals[i];
}
}
return Arrays.copyOfRange(res, 0, ++index);
}
}
// @lc code=end
|
package com.zantong.mobilecttx.weizhang.dto;
/**
* 43.生成违章缴费订单
*/
public class ViolationPayDTO {
private String carnum;//车牌号
private String usernum;//安盛用户ID(rsa加密)
private String peccancynum;//违章单号
private String peccancydate;//违章日期
private String orderprice;//罚款金额
private String enginenum;//发动机引擎号
public String getCarnum() {
return carnum;
}
public void setCarnum(String carnum) {
this.carnum = carnum;
}
public String getUsernum() {
return usernum;
}
public void setUsernum(String usernum) {
this.usernum = usernum;
}
public String getPeccancynum() {
return peccancynum;
}
public void setPeccancynum(String peccancynum) {
this.peccancynum = peccancynum;
}
public String getPeccancydate() {
return peccancydate;
}
public void setPeccancydate(String peccancydate) {
this.peccancydate = peccancydate;
}
public String getOrderprice() {
return orderprice;
}
public void setOrderprice(String orderprice) {
this.orderprice = orderprice;
}
public String getEnginenum() {
return enginenum;
}
public void setEnginenum(String enginenum) {
this.enginenum = enginenum;
}
}
|
package Vorlesung02;
public class FlensGreeter extends Greeter {
public FlensGreeter(String name) {
//ruft den Konstruktor von Greeter auf
super(name);
}
@Override
public String getMessage() {
return "Moin" + getName();
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.layout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.container.CenterLayoutContainer;
@Detail(name = "CenterLayout", icon = "centerlayout", category = "Layouts", fit = true)
public class CenterLayoutExample implements IsWidget, EntryPoint {
@Override
public Widget asWidget() {
CenterLayoutContainer con = new CenterLayoutContainer();
ContentPanel panel = new ContentPanel();
panel.setBodyStyle("padding: 6px");
panel.setHeadingText("CenterLayout");
panel.add(new Label("I should be centered"));
panel.setWidth(200);
con.add(panel);
return con;
}
public void onModuleLoad() {
RootPanel.get().add(asWidget());
}
}
|
package product3;
public class ProductC1 implements ProductC{
}
|
package tree.bst;
import java.util.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BSTree {
public final Logger logger = LoggerFactory.getLogger(BSTree.class);
final static class TreeNode<E extends Comparable>{
E element;
TreeNode parent;
TreeNode left;
TreeNode right;
TreeNode(E element){
this.element = element;
}
TreeNode(E element, TreeNode left, TreeNode right){
this.element = element;
this.left = left;
this.right = right;
}
TreeNode(E element, TreeNode left, TreeNode right, TreeNode parent){
this.element = element;
this.left = left;
this.right = right;
this.parent = parent;
}
@Override
public boolean equals(Object obj){
if (obj == null) {return false;}
if (obj instanceof TreeNode){
TreeNode target = (TreeNode) obj;
return target.element.compareTo(this.element) == 0;
}
return false;
}
@Override
public String toString(){
return "[element:"+element+"]";
}
}
/**
* 递归
* @param root
* @param target
* @param <E>
* @return
*/
public <E extends Comparable> TreeNode search_1(TreeNode root, E target){
// System.out.println(root);
if (root == null || target.compareTo(root.element) == 0){
return root;
}
if (target.compareTo(root.element) < 0){
return search_1(root.left, target);
} else {
return search_1(root.right, target);
}
}
/**
* 非递归、迭代
* @param root
* @param target
* @param <E>
* @return
*/
public <E extends Comparable>TreeNode search_2(TreeNode root, E target){
TreeNode current = root;
while (current != null){
if (target.compareTo(current.element) == 0){
return current;
}
if (target.compareTo(current.element) < 0){
current = current.left;
}else {
current = current.right;
}
}
return root;
}
/**
* 获得bst中的最小元素
* @param root
* @return
*/
public TreeNode getMinNode(TreeNode root){
TreeNode current = root;
while (current.left != null){
current = current.left;
}
return current;
}
/**
* 获得bst中的最大元素
* @param root
* @return
*/
public TreeNode getMaxNode(TreeNode root){
TreeNode current = root;
while (current.right != null){
current = current.right;
}
return current;
}
/**
* 求bst中某个节点的直接后继
* @param start
* @param root
* @param <E>
* @return
*/
public <E extends Comparable> TreeNode successorOf(E start, TreeNode root){
TreeNode target = null;
if ((target = search_1(root, start)) == null){
throw new NoSuchElementException("指定的节点"+new TreeNode<>(start)+"不存在!");
}
if (target.right != null) {
return getMinNode(target.right); //target有右子树,那么后继一定是右子树的最小值
}
/**
* 否则
* 1. 没后继:target是在所有祖先点的右子树上
* 2. 有后继:一定存在一个祖先节点,这个target是在这个祖先节点的左子树上
*/
TreeNode parent = target.parent;
while (parent != null) {
if (target.equals(parent.left)) {
return parent;
}
target = parent;
parent = parent.parent;
}
return null;
}
/**
* 求某个节点的直接前驱
* @param start
* @param root
* @param <E>
* @return
*/
public <E extends Comparable> TreeNode preDecessorOf(E start, TreeNode root) {
TreeNode target = search_1(root, start);
/**
* 如果有左子树,那么前驱就是左子树上的最大值
*/
System.out.println(target);
if (target.left != null){
return getMaxNode(target.left);
}
/**
* 如果没有左子树
* 1. 有前驱:那么target的祖先节点中,target一定在某个祖先节点的右子树上
*/
TreeNode parent = target.parent;
System.out.println(parent);
while (parent != null){
if (target.equals(parent.right)){
return parent;
}
target = parent;
parent = parent.parent;
}
return null;
}
private boolean isLeaf (TreeNode node){
if (node == null) {
throw new NoSuchElementException("节点为空");
}
return node.left == null && node.right == null;
}
/**
* 自己写的delete,还存在一些问题
* @param root
* @param target
* @param <E>
* @return
*/
public <E extends Comparable> boolean delete(TreeNode root, E target){
System.out.println("target: "+target);
System.out.println("root: "+root);
TreeNode parent = null;
TreeNode current = root;
while (current != null ){
if (target.compareTo(current.element) > 0){
parent = current;
current = current.right;
} else if (target.compareTo(current.element) < 0){
parent = current;
current = current.left;
} else {
System.out.println("break current:"+current);
break;
}
}
if (current == null){
System.out.println(parent);
throw new NoSuchElementException("待删除节点"+new TreeNode<>(target)+"不存在!");
}
System.out.println("current:"+current);
System.out.println("parent:"+parent);
/**
* 待删除的节点没有孩子节点,那么直接删除就可以
*/
if (isLeaf(current)){
if (parent.left == current){
parent.left = null;
} else {
parent.right = null;
}
current.parent = null;
return true;
}
/**
* 待删除的节点只有一个孩子,那么把这个孩子提升到待删除节点的位置代替它
*/
boolean isLeft = parent.left == current ? true : false; //删除的节点是根节点的时候,这个parent == null
if ((current.right == null && current.left != null) ||
(current.left == null && current.left == null)){
TreeNode child = current.left != null ? current.left : current.right;
if (isLeft){
parent.left = child;
}else {
parent.right = child;
}
child.parent = parent;
current.parent = null;
current.left = null;
current.right = null;
return true;
}
/**
* 待删除的节点有两个孩子节点
*/
TreeNode successor = successorOf(current.element, root);
System.out.println("successor:"+successor);
current.element = successor.element;
System.out.println("successor.element:"+successor.element);
//如果这个后继是待删除节点的右孩子的话
if (current.right == successor){
current.right = successor.right;
successor.right.parent = current;
successor.parent = null;
successor.right = null;
return true;
}
//如果这个后继不是待删除节点的右孩子的话
//这个后继的父亲一定在待删除节点的右子树上,并且,这个后继一定是父亲的左孩子,后继一定只有右孩子
TreeNode preParent = successor.parent;
System.out.println("preParent: "+preParent);
if (successor.right != null){
successor.right.parent = preParent;
preParent.left = successor.right;
successor.parent = null;
successor.right = null;
} else {
preParent.left = null;
successor.parent = null;
successor.right = null;
}
return true;
}
public <E extends Comparable> TreeNode deleteByAlgorithmInductionWithEle(TreeNode root, E target){
return deleteByAlgorithmInductionWithNode(root, search_1(root, target));
}
public TreeNode deleteByAlgorithmInductionWithNode(TreeNode root, TreeNode target){
if (target.left == null){
return transplate(root, target, target.right);
}
if (target.right == null){ // 只有左子树,没有右子树
return transplate(root, target, target.left);
}
TreeNode directSuccessor = getMinNode(target.right);
target.element = directSuccessor.element;
return deleteByAlgorithmInductionWithNode(root, directSuccessor);
}
private void nulled(TreeNode target){
target.parent = null;
target.left = null;
target.right = null;
}
private TreeNode transplate(TreeNode root, TreeNode transplated, TreeNode transplate){
if (transplated.parent == null){
root = transplate;
} else if (transplated.parent.left == transplated){
transplated.parent.left = transplate;
} else {
transplated.parent.right = transplate;
}
if (transplate != null){
transplate.parent = transplated.parent;
}
return root;
}
public TreeNode insert(TreeNode root, TreeNode node){
TreeNode parent = null;
TreeNode current = root;
while (current != null){
parent = current;
if (node.element.compareTo(current.element) >= 0){
current = current.right;
}else {
current = current.left;
}
}
node.parent = parent;
if (parent == null){
root = node;
return root;
}
if (parent.element.compareTo(node.element) > 0){
parent.left = node;
}else {
parent.right = node;
}
return root;
}
public <E extends Comparable> TreeNode buildFromArray(@NotNull E[] arrs){
TreeNode root = null;
for (E ele : arrs){
TreeNode current = new TreeNode(ele,null,null);
root = insert(root,current);
}
return root;
}
public static void main(String[] args) {
Integer[] arrs = {4,7,2,1,3,5,9,8};
BSTree bsTree = new BSTree();
TreeNode root = bsTree.buildFromArray(arrs);
/**
* 4
* 2 7
* 1 3 5 9
* 8
*/
// System.out.println(bsTree.search_2(root, 9));
// System.out.println("getMinNode:"+bsTree.getMinNode(root));
// System.out.println("getMaxNode:"+bsTree.getMaxNode(root));
// System.out.println("successorOf(8, root):"+bsTree.successorOf(8, root));
// System.out.println("successorOf(8, root):"+bsTree.preDecessorOf(5, root));
TreeNode node = bsTree.search_1(root,7);
root = bsTree.deleteByAlgorithmInductionWithEle(root, 7);
bsTree.preOrder(root);
System.out.println();
bsTree.inOrder(root);
System.out.println();
System.out.println(node);
System.out.println(node.parent);
System.out.println(node.left);
System.out.println(node.right);
}
public void preOrder(TreeNode root){
if (root == null){
return;
}
System.out.println(root);
preOrder(root.left);
preOrder(root.right);
}
public void inOrder(TreeNode root){
if (root == null){
return;
}
inOrder(root.left);
System.out.println(root);
inOrder(root.right);
}
}
|
package com.delrima.webgene.server.configuration;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.Aspects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import com.delrima.webgene.client.action.MemberLookupAction;
import com.delrima.webgene.client.action.RetrieveMemberTreeAction;
import com.delrima.webgene.client.action.RetrieveSingleMemberAction;
import com.delrima.webgene.client.action.SingleActionHandler;
import com.delrima.webgene.client.action.UpdateMemberAction;
import com.delrima.webgene.client.common.Action;
import com.delrima.webgene.client.common.Result;
import com.delrima.webgene.client.dao.MemberTreeDAO;
import com.delrima.webgene.client.dao.MemberTreeDataProvider;
import com.delrima.webgene.server.dao.MemberHierarchyCreatorTemplate;
import com.delrima.webgene.server.dao.MemberTreeDataProviderImpl;
import com.delrima.webgene.server.dao.orm.jpa.gae.MemberTreeDaoServerImpl;
import com.delrima.webgene.server.services.ActionHandlerServiceImpl;
import com.delrima.webgene.server.services.MemberLookupActionHandler;
import com.delrima.webgene.server.services.RetrieveMemberTreeActionHandler;
import com.delrima.webgene.server.services.RetrieveSingleMemberActionHandler;
import com.delrima.webgene.server.services.UpdateMemberActionHandler;
@Configuration
@Import(PersistenceJPAConfiguration.class)
@EnableSpringConfigured
public class ContainerConfiguration {
@Autowired
private PersistenceJPAConfiguration persistenceJPAConfiguration;
@Bean
public MemberTreeDAO familyTreeDao() {
return new MemberTreeDaoServerImpl(persistenceJPAConfiguration.entityManager());
}
@Bean
public MemberTreeDataProvider familyTreeDataProvider() {
return new MemberTreeDataProviderImpl(familyTreeDao());
}
@Bean
public MemberHierarchyCreatorTemplate MemberTreeIteratorTemplate() {
return new MemberHierarchyCreatorTemplate(familyTreeDao());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean
public <R extends Result> Map<Class<Action<R>>, SingleActionHandler<Action<R>, R>> singleActionHandlerList() {
Map<Class<Action<R>>, SingleActionHandler<Action<R>, R>> result = new HashMap<Class<Action<R>>, SingleActionHandler<Action<R>, R>>();
result.put((Class) MemberLookupAction.class, (SingleActionHandler) new MemberLookupActionHandler(familyTreeDataProvider()));
result.put((Class) RetrieveMemberTreeAction.class, (SingleActionHandler) new RetrieveMemberTreeActionHandler(familyTreeDataProvider()));
result.put((Class) RetrieveSingleMemberAction.class, (SingleActionHandler) retrieveSingleMemberActionHandler());
result.put((Class) UpdateMemberAction.class, (SingleActionHandler) new UpdateMemberActionHandler(familyTreeDataProvider(), retrieveSingleMemberActionHandler()));
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean
public <R extends Result> ActionHandlerServiceImpl<R> actionHandlerService() {
return new ActionHandlerServiceImpl<R>((Map) singleActionHandlerList());
}
@Bean
public RetrieveSingleMemberActionHandler retrieveSingleMemberActionHandler() {
return new RetrieveSingleMemberActionHandler(familyTreeDataProvider());
}
@Bean
public AnnotationBeanConfigurerAspect annotationBeanConfigurerAspect() {
return Aspects.aspectOf(AnnotationBeanConfigurerAspect.class);
}
}
|
package com.choupies.fdj.fdjback.service.mapper.impl;
import com.choupies.fdj.fdjback.dto.option.ConsulterOptionDtoOut;
import com.choupies.fdj.fdjback.dto.option.CreerOptionDtoIn;
import com.choupies.fdj.fdjback.model.Option;
import com.choupies.fdj.fdjback.service.mapper.OptionConverter;
import org.springframework.stereotype.Component;
@Component
public class OptionMapper implements OptionConverter {
@Override
public Option convert(ConsulterOptionDtoOut consulterOptionDtoOut) {
return null;
}
@Override
public Option convert(CreerOptionDtoIn creerOptionDtoIn) {
Option option = new Option();
option.setActif(creerOptionDtoIn.isActif());
option.setCode(creerOptionDtoIn.getCode());
option.setCout(creerOptionDtoIn.getCout());
option.setLibelle(creerOptionDtoIn.getLibelle());
option.setTypeLoteries(creerOptionDtoIn.getTypeLoteries());
return option;
}
}
|
package Model;
public class Uitgeleend implements MateriaalState {
private Materiaal materiaal;
public Uitgeleend(Materiaal materiaal){
setMateriaal(materiaal);
}
@Override
public void verwijder() {
System.out.println("product kan niet verwijderd worden als het uitgeleend zijn");
}
@Override
public void leenUit() {
System.out.println("product is al uitgeleend");
}
@Override
public void brengTerug(boolean isBeschadigd) {
if (isBeschadigd){
this.materiaal.setCurrentState(this.materiaal.getBeschadigd());
}else{
this.materiaal.setCurrentState(this.materiaal.getUitleenbaar());
}
}
@Override
public void herstel() {
System.out.println("product kan niet hersteld worden als het is uitgeleend");
}
public void setMateriaal(Materiaal materiaal) {
this.materiaal = materiaal;
}
}
|
package ggboy.study.java.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class SortMethods {
public static void main(String[] args) {
Random r = new Random();
int[] data = new int[100000];
for (int i = 0; i < data.length; i++) {
data[i] = r.nextInt(100000);
}
List<int[]> resultList = new ArrayList<>(8);
int[] tempData;
long start;
System.out.println("直接插入排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method1(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
System.out.println("希尔排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method2(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
System.out.println("简单选择排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method3(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
System.out.println("堆排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method4(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
System.out.println("冒泡排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method5(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
System.out.println("快速排序");
tempData = Arrays.copyOf(data, data.length);
start = System.currentTimeMillis();
tempData = method6(tempData);
System.out.println(System.currentTimeMillis() - start);
resultList.add(tempData);
// System.out.println("直接插入排序");
// tempData = Arrays.copyOf(data, data.length);
// start = System.currentTimeMillis();
// tempData = method7(tempData);
// System.out.println(System.currentTimeMillis() - start);
// resultList.add(tempData);
// System.out.println("直接插入排序");
// tempData = Arrays.copyOf(data, data.length);
// start = System.currentTimeMillis();
// tempData = method8(tempData);
// System.out.println(System.currentTimeMillis() - start);
// resultList.add(tempData);
for (int[] result : resultList) {
int temp = 0;
boolean flag = true;
for (int i : result) {
// System.out.print(i + ",");
// System.out.println();
if (i < temp) {
flag = !flag;
break;
}
temp = i;
}
System.out.println(flag);
}
}
/**
* 直接插入排序 <br />
* 在要排序的一组数中,假设前面(n-1) [n>=2] 个数已经是排 好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数
* 也是排好顺序的。如此反复循环,直到全部排好顺序。
*/
public static int[] method1(int[] data) {
int i, j, temp;
for (i = 1; i < data.length; i++) {
temp = data[i];
for (j = i; j > 0 && temp < data[j - 1]; j--) {
data[j] = data[j - 1];
}
data[j] = temp;
}
return data;
}
/**
* 希尔排序 <br />
* 算法先将要排序的一组数按某个增量d(n/2,n为要排序数的个数)分成若干组, 每组中记录的下标相差d.对每组中全部元素进行直接插入排序,
* 然后再用一个较小的增量(d/2)对它进行分组,在每组中再进行直接插入排序。 当增量减到1时,进行直接插入排序后,排序完成。
*/
public static int[] method2(int[] data) {
int zld = data.length;
while (zld > 1) {
zld = (int) Math.ceil(zld / 2);
for (int k = 0; k < zld; k++) {
int i, j, temp;
for (i = k + zld; i < data.length; i += zld) {
temp = data[i];
for (j = i; j > zld - 1 && temp < data[j - zld]; j -= zld) {
data[j] = data[j - zld];
}
data[j] = temp;
}
}
}
return data;
}
/**
* 简单选择排序 <br />
* 在要排序的一组数中,选出最小的一个数与第一个位置的数交换; 然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。
*/
public static int[] method3(int[] data) {
int i, j, temp, index;
for (i = 0; i < data.length - 1; i++) {
for (index = i, j = i + 1; j < data.length; j++) {
if (data[index] > data[j]) {
index = j;
}
}
if (index > i) {
temp = data[i];
data[i] = data[index];
data[index] = temp;
}
}
return data;
}
/**
* 堆排序 <br />
* 堆排序是一树形选择排序,在排序过程中,将R[1..N]看成是一颗完全二叉树的顺序存储结构,
* 利用完全二叉树中双亲结点和孩子结点之间的内在关系来选择最小的元素。
*/
public static int[] method4(int[] data) {
return data;
}
/**
* 冒泡排序 <br />
* 在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:
* 每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。
*/
public static int[] method5(int[] data) {
int i, j, temp;
for (i = 0; i < data.length; i++) {
for (j = data.length - 1; j > i; j--) {
if (data[j] < data[j - 1]) {
temp = data[j];
data[j] = data[j - 1];
data[j - 1] = temp;
}
}
}
return data;
}
/**
* 快速排序 <br />
* 选择一个基准元素,通常选择第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于等于基准元素,
* 此时基准元素在其排好序后的正确位置,然后再用同样的方法递归地排序划分的两部分。
*/
public static int[] method6(int[] data) {
quickSort(data, 0, data.length - 1);
return data;
}
private final static void quickSort(int[] data, int start, int end) {
int leftIndex = start, rightIndex = end, temp = data[start], index = leftIndex;
while (leftIndex < rightIndex) {
while (data[rightIndex] >= temp && rightIndex > leftIndex) {
rightIndex--;
}
data[leftIndex] = data[rightIndex];
index = rightIndex;
while (data[leftIndex] <= temp && leftIndex < rightIndex) {
leftIndex++;
}
data[rightIndex] = data[leftIndex];
index = leftIndex;
}
data[index] = temp;
if (index - start > 1) {
quickSort(data, start, index - 1);
}
if (end - index > 1) {
quickSort(data, index + 1, end);
}
}
/**
* 归并排序 <br />
* 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
*/
public static int[] method7(int[] data) {
return data;
}
/**
* 基数排序 <br />
* 将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。
*/
public static int[] method8(int[] data) {
return data;
}
}
|
package ro.ase.csie.cts.g1093.mironcristina.assignment4.exceptions;
public class WrongProductNameException extends Exception {
}
|
package com.splwg.cm.domain.batch;
import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import com.splwg.base.api.batch.CommitEveryUnitStrategy;
import com.splwg.base.api.batch.JobWork;
import com.splwg.base.api.batch.RunAbortedException;
import com.splwg.base.api.batch.ThreadAbortedException;
import com.splwg.base.api.batch.ThreadExecutionStrategy;
import com.splwg.base.api.batch.ThreadWorkUnit;
import com.splwg.base.api.businessObject.BusinessObjectDispatcher;
import com.splwg.base.api.businessObject.BusinessObjectInstance;
import com.splwg.base.api.businessObject.COTSFieldDataAndMD;
import com.splwg.base.api.businessObject.COTSInstanceNode;
import com.splwg.base.api.businessService.BusinessServiceDispatcher;
import com.splwg.base.api.businessService.BusinessServiceInstance;
import com.splwg.base.domain.todo.role.Role;
import com.splwg.base.domain.todo.role.Role_Id;
import com.splwg.cm.domain.common.businessComponent.CmXLSXReaderComponent;
import com.splwg.shared.logging.Logger;
import com.splwg.shared.logging.LoggerFactory;
import com.splwg.tax.domain.admin.formType.FormType;
import com.splwg.tax.domain.admin.formType.FormType_Id;
/**
* @author Denash.M
*
* @BatchJob (modules = {},softParameters = { @BatchJobSoftParameter (name = errorFilePathToMove, required = true, type = string)
* , @BatchJobSoftParameter (name = formType, required = true, type =string) , @BatchJobSoftParameter (name = filePaths, required =
* true, type = string) , @BatchJobSoftParameter (name = pathToMove,required = true, type = string)})
*/
public class CmProcessRegistrationEmployerBatch extends CmProcessRegistrationEmployerBatch_Gen {
private final static Logger log = LoggerFactory.getLogger(CmProcessRegistrationEmployerBatch.class);
@Override
public void validateSoftParameters(boolean isNewRun) {
System.out.println("File path: " + this.getParameters().getFilePaths());
System.out.println("Form Type: " + this.getParameters().getFormType());
System.out.println("Path To Move: " + this.getParameters().getPathToMove());
System.out.println("Path To Move: " + this.getParameters().getErrorFilePathToMove());
}
private File[] getNewTextFiles() {
File dir = new File(this.getParameters().getFilePaths());
return dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xlsx");
}
});
}
public JobWork getJobWork() {
log.info("***** Demarrage JobWorker***");
System.out.println("######################## Demarrage JobWorker ############################");
List<ThreadWorkUnit> listOfThreadWorkUnit = new ArrayList<ThreadWorkUnit>();
File[] files = this.getNewTextFiles();
for (File file : files) {
if (file.isFile()) {
ThreadWorkUnit unit = new ThreadWorkUnit();
// A unit must be created for every file in the path, this will
// represent a row to be processed.
// String fileName =
// this.getParameters().getFilePaths()+file.getName();
unit.addSupplementalData("fileName", this.getParameters().getFilePaths() + file.getName());
// unit.addSupplementalData("fileName", file.getName());
listOfThreadWorkUnit.add(unit);
log.info("***** getJobWork ::::: " + this.getParameters().getFilePaths() + file.getName());
}
}
JobWork jobWork = createJobWorkForThreadWorkUnitList(listOfThreadWorkUnit);
System.out.println("######################## Terminer JobWorker ############################");
return jobWork;
}
public Class<CmProcessRegistrationEmployerBatchWorker> getThreadWorkerClass() {
return CmProcessRegistrationEmployerBatchWorker.class;
}
public static class CmProcessRegistrationEmployerBatchWorker
extends CmProcessRegistrationEmployerBatchWorker_Gen {
public static final String AS_CURRENT = "asCurrent";
private CmXLSXReaderComponent cmXLSXReader = CmXLSXReaderComponent.Factory.newInstance();
private static CmHelper customHelper = new CmHelper();
XSSFSheet spreadsheet;
private int cellId = 0;
public ThreadExecutionStrategy createExecutionStrategy() {
return new CommitEveryUnitStrategy(this);
}
@Override
public void initializeThreadWork(boolean initializationPreviouslySuccessful)
throws ThreadAbortedException, RunAbortedException {
log.info("*****initializeThreadWork");
}
public boolean executeWorkUnit(ThreadWorkUnit listOfUnit) throws ThreadAbortedException, RunAbortedException {
System.out.println("######################## Demarrage executeWorkUnit ############################");
boolean foundNinea = false, checkErrorInExcel = false, processed = false;
Cell cell;
List<Object> listesValues = new ArrayList<Object>();
log.info("*****Starting Execute Work Unit");
String fileName = listOfUnit.getSupplementallData("fileName").toString();
log.info("*****executeWorkUnit : " + fileName);
cmXLSXReader.openXLSXFile(fileName);
spreadsheet = cmXLSXReader.openSpreadsheet(0, null);
Set<String> headerConstants = getHeaderConstants();
int rowCount = spreadsheet.getLastRowNum() - spreadsheet.getFirstRowNum();
System.out.println("rowCount:: " + rowCount);
Iterator<Row> rowIterator = spreadsheet.iterator();
int cellCount = spreadsheet.getRow(0).getLastCellNum();
log.info("CellCount:: " + cellCount);
while (rowIterator.hasNext()) {
XSSFRow row = (XSSFRow) rowIterator.next();
if (row.getRowNum() >= 2) {
break;
}
String nineaNumber = null;
cellId = 1;
String establishmentDate = null, immatriculationDate = null, premierEmployeeDate = null, deliveryDate = null;
Boolean checkValidationFlag = false;
if (row.getRowNum() == 0) {
continue;
}
log.info("#############----ENTERTING INTO ROW-----#############:" + row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext() && !foundNinea) {
try {
while (cellId <= cellCount && !checkErrorInExcel) {
cell = cellIterator.next();
String headerName = URLEncoder.encode(
cell.getSheet().getRow(0).getCell(cellId - 1).getRichStringCellValue().toString(),
CmConstant.UTF);
String actualHeader = cell.getSheet().getRow(0).getCell(cellId - 1).getRichStringCellValue()
.toString();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
if (headerName != null && headerName
.equalsIgnoreCase(URLEncoder.encode(CmConstant.EMAIL_EMPLOYER, CmConstant.UTF))) {
checkValidationFlag = customHelper.validateEmail(cell.getStringCellValue());
if (checkValidationFlag != null && !checkValidationFlag) {// Email validation
// Error Skip the row
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.EMPLOYER_EMAIL_INVALID, fileName);
log.info("Given Ninea Number: " + nineaNumber + " having Incorrect Email Id: "
+ cell.getStringCellValue());
break;
} else {
checkValidationFlag = customHelper
.validateEmailExist(cell.getStringCellValue());
if (checkValidationFlag != null && checkValidationFlag) {
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.EMPLOYER_EMAIL_EXIST, fileName);
log.info("Given Email ID:--> " + cell.getStringCellValue()
+ " already Exists");
break;
}
}
} else if (headerName != null
&& headerName.equalsIgnoreCase(URLEncoder.encode(CmConstant.EMAIL, CmConstant.UTF))) {
checkValidationFlag = customHelper.validateEmail(cell.getStringCellValue());
if (checkValidationFlag != null && !checkValidationFlag) {// Email validation
// Error Skip the row
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.EMAIL_INVALID, fileName);
log.info("Given Ninea Number: " + nineaNumber + " having Incorrect Email Id: "
+ cell.getStringCellValue());
break;
}
} else if (headerName != null && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.TRADE_REG_NUM, CmConstant.UTF))) {
if (customHelper.validateCommercialRegister(cell.getStringCellValue())) {// Validation trade register number
checkValidationFlag = customHelper
.validateTRNExist(cell.getStringCellValue());
if (checkValidationFlag != null && checkValidationFlag) {
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.TRN_EXIST, fileName);
log.info("Given Trade Registration Number--> " + cell.getStringCellValue()
+ " already Exists");
break;
}
} else {
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.TRN_INVALID, fileName);
log.info("Given Trade Registration Number:--> " + cell.getStringCellValue()
+ " is Invalid ");
break;
}
} else if (headerName != null && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.TAX_IDENTIFY_NUM, CmConstant.UTF))) {
checkValidationFlag = customHelper
.validateTaxIdenficationNumber(cell.getStringCellValue().toUpperCase());
if (checkValidationFlag != null && !checkValidationFlag) {// TIN validation
// Error Skip the row
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.TIN_INVALID, fileName);
log.info("Given Ninea Number having Invalid TIN Number:" + nineaNumber);
break;
}
listesValues.add(cell.getStringCellValue().toUpperCase());
break;
} else if (headerName != null && (headerName.equalsIgnoreCase(CmConstant.LAST_NAME)
|| headerName.equalsIgnoreCase(URLEncoder.encode(CmConstant.FIRST_NAME, CmConstant.UTF)))) {
checkValidationFlag = customHelper
.validateAlphabetsOnly(cell.getStringCellValue());
if (checkValidationFlag != null && !checkValidationFlag) { // Alphabets only
// Error Skip the row
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.NAME_INVALID, fileName);
log.info("Given " + actualHeader
+ "is having special characters or number for the given ninea number:"
+ nineaNumber);
break;
}
} else if (headerName != null && headerName.equalsIgnoreCase(CmConstant.NINET)) {
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.NINET_INVALID, fileName);
log.info("Given " + headerName
+ " having special characters or alphabets for the given ninea number:"
+ nineaNumber);
break;
} else if (headerName != null && headerName.equalsIgnoreCase(CmConstant.NINEA)) {
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.NINEA_INVALID, fileName);
log.info("Given " + headerName
+ " having special characters or alphabets for the given ninea number:"
+ nineaNumber);
break;
} else if (headerName != null && (headerName
.equalsIgnoreCase(URLEncoder.encode(CmConstant.LEGAL_REP_NIN, CmConstant.UTF))
|| headerName
.equalsIgnoreCase(URLEncoder.encode(CmConstant.EMPLOYEE_NIN, CmConstant.UTF)))) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.NIN_INVALID, fileName);
log.info("Given " + headerName
+ " having special characters or alphabets for the given ninea number:"
+ nineaNumber);
break;
}
listesValues.add(cell.getStringCellValue());
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {// Date Validation
// Immatriculation Date
if (!isBlankOrNull(headerName) && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.IMMATRICULATION_DATE, CmConstant.UTF))) {
immatriculationDate = cell.getDateCellValue().toString();
checkValidationFlag = customHelper
.compareDateWithSysDate(immatriculationDate, "lessEqual"); // validating with current date.
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_LESSEQUAL_TODAY_VALID, fileName);
log.info("Given->" + actualHeader + " Date greater than System Date-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
// Establishment Date
if (!isBlankOrNull(headerName) && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.ESTABLISHMENT_DATE, CmConstant.UTF))) {
establishmentDate = cell.getDateCellValue().toString();
checkValidationFlag = customHelper.compareDateWithSysDate(establishmentDate,
"lessEqual"); // validating with current date.
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_LESSEQUAL_TODAY_VALID, fileName);
log.info("Given->" + actualHeader + " Date greater than System Date-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
checkValidationFlag = customHelper.checkDateSunOrSat(establishmentDate); // validating data is on sat or sun
if (checkValidationFlag != null && checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_SAT_SUN_VALID, fileName);
log.info("Given->" + actualHeader
+ " Date should not be on Saturday or Sunday-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
checkValidationFlag = customHelper.compareTwoDates(establishmentDate,
immatriculationDate, "greatEqual"); // validate two dates
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_EST_GREAT_IMM, fileName);
log.info("Given->" + actualHeader
+ " Date lesser than Date de numéro de registre du commerce-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
// Premier Employee Date
if (!isBlankOrNull(headerName) && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.PREMIER_EMP_DATE, CmConstant.UTF))) {
premierEmployeeDate = cell.getDateCellValue().toString();
checkValidationFlag = customHelper
.compareDateWithSysDate(premierEmployeeDate, "lessEqual"); // validating with current date
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_LESSEQUAL_TODAY_VALID, fileName);
log.info("Given->" + actualHeader + " Date greater than System Date- "
+ cell.getDateCellValue() + ": " + nineaNumber);
break;
}
checkValidationFlag = customHelper.checkDateSunOrSat(premierEmployeeDate); // validating data is on sat or sun
if (checkValidationFlag != null && checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_SAT_SUN_VALID, fileName);
log.info("Given->" + actualHeader
+ " Date should not be on Saturday or Sunday-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
checkValidationFlag = customHelper.compareTwoDates(premierEmployeeDate,
establishmentDate, "greatEqual"); // validate two dates
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_EMP_GREAT_EST, fileName);
log.info("Given->" + actualHeader
+ " Date lesser than Date de l'inspection du travail-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
checkValidationFlag = customHelper.compareTwoDates(premierEmployeeDate,
immatriculationDate, "greatEqual"); // validate two dates
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_EMP_GREAT_IMM, fileName);
log.info("Given->" + actualHeader
+ " Date lesser than Date de numéro de registre du commerce-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
if (!isBlankOrNull(headerName) && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.DATE_DE_DELIVRANCE, CmConstant.UTF))) {
deliveryDate = cell.getDateCellValue().toString();
checkValidationFlag = customHelper
.compareDateWithSysDate(immatriculationDate, "lessEqual"); // validating with current date.
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_LESSEQUAL_TODAY_VALID, fileName);
log.info("Given->" + actualHeader + " Date greater than System Date-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
if (!isBlankOrNull(headerName) &&( headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.DATE_IDENTIFICATION_FISCALE, CmConstant.UTF)) || headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.DATE_DE_NAISSANCE, CmConstant.UTF)) || headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.DATE_DE_CREATION, CmConstant.UTF)))) {
checkValidationFlag = customHelper
.compareDateWithSysDate(cell.getDateCellValue().toString(), "lessEqual"); // validating with current date.
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_LESSEQUAL_TODAY_VALID, fileName);
log.info("Given->" + actualHeader + " Date greater than System Date-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
if (!isBlankOrNull(headerName) && headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.DATE_DE_EXPIRATION, CmConstant.UTF))) {
checkValidationFlag = customHelper.compareTwoDates(cell.getDateCellValue().toString(),
deliveryDate, "great"); // validate two dates
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.DATE_DEL_GREAT_EXP, fileName);
log.info("Given->" + actualHeader
+ " Date lesser than Date de délivrance-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
}
}
String convertedDate = customHelper
.convertDateFormat(cell.getDateCellValue().toString());
if (isBlankOrNull(convertedDate) || convertedDate.equalsIgnoreCase(CmConstant.INVALID_DATE_STRING)) {
checkErrorInExcel = true;
createToDo(cell.getDateCellValue().toString(), nineaNumber, CmConstant.INVALID_DATE, fileName);
log.info("Given Ninea Number having invalid Date Format-"
+ cell.getDateCellValue() + ":" + nineaNumber);
break;
} else {
listesValues.add(convertedDate);
}
System.out.println(convertedDate);
} else {
if (headerName != null && headerName.equalsIgnoreCase(CmConstant.NINEA)
&& cell.getColumnIndex() == 4) {// Ninea Validation
Double nineaNum = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("#");
nineaNumber = df.format(nineaNum);
if (nineaNum.toString().length() == 7) {// Adding zero based on functional testing feedback from khawla - 09April
nineaNumber = CmConstant.NINEA_PREFIX + nineaNumber;
}
if (customHelper.validateNineaNumber(nineaNumber)) {
checkValidationFlag = customHelper.validateNineaExist(nineaNumber);
if (checkValidationFlag != null && checkValidationFlag) {
checkErrorInExcel = true;
createToDo("", nineaNumber, CmConstant.NINEA_EXIST, fileName);
log.info("Given Ninea Number already Exists: " + nineaNumber);
break;
}
} else {
checkErrorInExcel = true;
createToDo("", nineaNumber, CmConstant.NINEA_INVALID, fileName);
log.info("Given Ninea Number is Invalid: " + cell.getNumericCellValue());
break;
}
} else if (headerName != null && headerName.equalsIgnoreCase(CmConstant.NINET)) {
checkValidationFlag = customHelper
.validateNinetNumber(cell.getNumericCellValue());
if (checkValidationFlag != null && !checkValidationFlag) {// NINET validation
// Error Skip the row
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.NINET_INVALID, fileName);
log.info("Given Ninea Number having Invalid NINET:" + nineaNumber);
break;
}
} else if (headerName != null && (headerName.equalsIgnoreCase(URLEncoder.encode(CmConstant.TELEPHONE, CmConstant.UTF))
|| headerName.equalsIgnoreCase(URLEncoder.encode(CmConstant.PHONE, CmConstant.UTF)) || headerName
.equalsIgnoreCase(URLEncoder.encode(CmConstant.MOBILE_NUM, CmConstant.UTF)))) { // PhoneNum Validation
checkValidationFlag = customHelper
.validatePhoneNumber(cell.getNumericCellValue());
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.TELEPHONE_INVALID, fileName);
log.info("Given Ninea Number having invalid PhoneNumber- " + actualHeader
+ ":" + cell.getNumericCellValue() + ":" + nineaNumber);
break;
}
} else if (headerName != null && (headerName.equalsIgnoreCase(CmConstant.LAST_NAME)
|| headerName.equalsIgnoreCase(URLEncoder.encode(CmConstant.FIRST_NAME, CmConstant.UTF)))) {
// Error Skip the row
checkErrorInExcel = true;
createToDo(cell.getStringCellValue(), nineaNumber, CmConstant.NAME_LETTER_CHECK, fileName);
log.info("Given " + headerName
+ " should be alphabets for the given ninea number:" + nineaNumber);
break;
} else if (headerName != null && (headerName
.equalsIgnoreCase(URLEncoder.encode(CmConstant.LEGAL_REP_NIN, CmConstant.UTF))
|| headerName.equalsIgnoreCase(
URLEncoder.encode(CmConstant.EMPLOYEE_NIN, CmConstant.UTF)))) {
Double ninNum = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("#");
String ninNumber = df.format(ninNum);
checkValidationFlag = customHelper.validateNinNumber(ninNumber);
if (checkValidationFlag != null && !checkValidationFlag) {
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.NIN_INVALID, fileName);
log.info("Given Ninea Number having invalid Nin Number- " + actualHeader + ":"
+ cell.getNumericCellValue() + ":" + nineaNumber);
break;
}
}
listesValues.add((long) cell.getNumericCellValue());
System.out.println((long) cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
if (headerConstants.contains(headerName)){
checkErrorInExcel = true;
createToDo(actualHeader, nineaNumber, CmConstant.EMPTY, fileName);
log.info(actualHeader+ " is Empty: for the NineaNumber: "+ nineaNumber);
break;
}
System.out.println("Blank:");
break;
case Cell.CELL_TYPE_BOOLEAN:
listesValues.add(cell.getBooleanCellValue());
System.out.println(cell.getBooleanCellValue());
break;
default:
listesValues.add("");
System.out.println("Blank:");
break;
}
cellId++;
}
} catch (UnsupportedEncodingException ex) {
log.info("*****Unsupported Encoding**** " + ex);
}
foundNinea = true;
if (checkErrorInExcel) {
checkErrorInExcel = false;
break;
}
try {
processed = formCreator(fileName, listesValues);
System.out.println("*****Bo Creation Status**** " + processed);
log.info("*****Bo Creation Status**** " + processed);
} catch (Exception exception) {
processed = false;
System.out.println("*****Issue in Processing file***** " + fileName + "NineaNumber:: "
+ listesValues.get(3));
log.info("*****Issue in Processing file***** " + fileName + "NineaNumber:: "
+ listesValues.get(3));
exception.printStackTrace();
}
}
foundNinea = false;
}
if (processed) {
customHelper.moveFileToProcessedFolder(fileName, this.getParameters().getPathToMove());
} else {
customHelper.moveFileToFailuireFolder(fileName, this.getParameters().getErrorFilePathToMove());
}
System.out.println("######################## Terminer executeWorkUnit ############################");
return true;
}
/**
* Method to create BO
*
* @param fileName
* @param listesValues
* @return
*/
private boolean formCreator(String fileName, List<Object> listesValues) {
BusinessObjectInstance boInstance = null;
boInstance = createFormBOInstance(this.getParameters().getFormType(), "EMPLOYER_REG-" + getSystemDateTime().toString());
COTSInstanceNode employerQuery = boInstance.getGroup("employerQuery");
COTSInstanceNode mainRegistrationForm = boInstance.getGroup("mainRegistrationForm");
COTSInstanceNode legalRepresentativeForm = boInstance.getGroup("legalRepresentativeForm");
//COTSInstanceNode documentsForm = boInstance.getGroup("documentsForm");
int count = 0;
while (count == 0) {
COTSFieldDataAndMD<?> employerType = employerQuery.getFieldAndMDForPath("employerType/asCurrent");
employerType.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> estType = employerQuery.getFieldAndMDForPath("estType/asCurrent");
estType.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> employerName = employerQuery.getFieldAndMDForPath("employerName/asCurrent");
employerName.setXMLValue(listesValues.get(count).toString());
count++;// Moved from second section
COTSFieldDataAndMD<?> hqId = employerQuery.getFieldAndMDForPath("hqId/asCurrent");
hqId.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> nineaNumber = employerQuery.getFieldAndMDForPath("nineaNumber/asCurrent");
nineaNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> ninetNumber = employerQuery.getFieldAndMDForPath("ninetNumber/asCurrent");
ninetNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> companyOriginId = employerQuery.getFieldAndMDForPath("companyOriginId/asCurrent");
companyOriginId.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalStatus = employerQuery.getFieldAndMDForPath("legalStatus/asCurrent");
legalStatus.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> startDate = employerQuery.getFieldAndMDForPath("startDate/asCurrent");
startDate.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> taxId = employerQuery.getFieldAndMDForPath("taxId/asCurrent");
taxId.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> taxIdDate = employerQuery.getFieldAndMDForPath("taxIdDate/asCurrent");
taxIdDate.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> tradeRegisterNumber = employerQuery.getFieldAndMDForPath("tradeRegisterNumber/asCurrent");
tradeRegisterNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> tradeRegisterDate = employerQuery.getFieldAndMDForPath("tradeRegisterDate/asCurrent");
tradeRegisterDate.setXMLValue(listesValues.get(count).toString());
count++;
// --------------------------*************------------------------------------------------------------------------------//
// ******Main Registration Form BO Creation*********************************//
COTSFieldDataAndMD<?> dateOfFirstHire = mainRegistrationForm.getFieldAndMDForPath("dateOfInspection/asCurrent");
dateOfFirstHire.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> dateOfHiringFirstExecutiveEmpl = mainRegistrationForm.getFieldAndMDForPath("dateOfFirstHire/asCurrent");
dateOfHiringFirstExecutiveEmpl.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> shortName = mainRegistrationForm.getFieldAndMDForPath("shortName/asCurrent");
shortName.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> businessSector = mainRegistrationForm.getFieldAndMDForPath("businessSector/asCurrent");
businessSector.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> mainLineOfBusiness = mainRegistrationForm.getFieldAndMDForPath("mainLineOfBusiness/asCurrent");
mainLineOfBusiness.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> atRate = mainRegistrationForm.getFieldAndMDForPath("atRate/asCurrent");
atRate.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> noOfWorkersInGenScheme = mainRegistrationForm.getFieldAndMDForPath("noOfWorkersInGenScheme/asCurrent");
noOfWorkersInGenScheme.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> noOfWorkersInBasicScheme = mainRegistrationForm.getFieldAndMDForPath("noOfWorkersInBasicScheme/asCurrent");
noOfWorkersInBasicScheme.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> region = mainRegistrationForm.getFieldAndMDForPath("region/asCurrent");
region.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> department = mainRegistrationForm.getFieldAndMDForPath("department/asCurrent");
department.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> arondissement = mainRegistrationForm.getFieldAndMDForPath("arondissement/asCurrent");
arondissement.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> city = mainRegistrationForm.getFieldAndMDForPath("commune/asCurrent");
city.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> qartier = mainRegistrationForm.getFieldAndMDForPath("qartier/asCurrent");
qartier.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> address = mainRegistrationForm.getFieldAndMDForPath("address/asCurrent");
address.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> empPostboxNumber = mainRegistrationForm.getFieldAndMDForPath("postboxNo/asCurrent");
empPostboxNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> telephone = mainRegistrationForm.getFieldAndMDForPath("telephone/asCurrent");
telephone.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> email = mainRegistrationForm.getFieldAndMDForPath("email/asCurrent");
email.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> website = mainRegistrationForm.getFieldAndMDForPath("website/asCurrent");
website.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> zoneCss = mainRegistrationForm.getFieldAndMDForPath("zoneCss/asCurrent");
zoneCss.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> zoneIpres = mainRegistrationForm.getFieldAndMDForPath("zoneIpres/asCurrent");
zoneIpres.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> sectorCss = mainRegistrationForm.getFieldAndMDForPath("sectorCss/asCurrent");
sectorCss.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> sectorIpres = mainRegistrationForm.getFieldAndMDForPath("sectorIpres/asCurrent");
sectorIpres.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> cssAgency = mainRegistrationForm.getFieldAndMDForPath("agencyCss/asCurrent");
cssAgency.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> ipresAgency = mainRegistrationForm.getFieldAndMDForPath("agencyIpres/asCurrent");
ipresAgency.setXMLValue(listesValues.get(count).toString());
count++;
// --------------------------*************------------------------------------------------------------------------------//
// ------------------------------LegalRepresentativeForm BO Creation----------------------------------------------------//
COTSFieldDataAndMD<?> legalRepPerson = legalRepresentativeForm.getFieldAndMDForPath("legalRepPerson/asCurrent");
legalRepPerson.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> lastName = legalRepresentativeForm.getFieldAndMDForPath("lastName/asCurrent");
lastName.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> firstName = legalRepresentativeForm.getFieldAndMDForPath("firstName/asCurrent");
firstName.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> dateOfBirth = legalRepresentativeForm.getFieldAndMDForPath("birthDate/asCurrent");
dateOfBirth.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> nationality = legalRepresentativeForm.getFieldAndMDForPath("nationality/asCurrent");
nationality.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> nin = legalRepresentativeForm.getFieldAndMDForPath("nin/asCurrent");
nin.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> placeOfBirth = legalRepresentativeForm.getFieldAndMDForPath("placeOfBirth/asCurrent");
placeOfBirth.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> cityOfBirth = legalRepresentativeForm.getFieldAndMDForPath("cityOfBirth/asCurrent");
cityOfBirth.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> typeOfIdentity = legalRepresentativeForm.getFieldAndMDForPath("typeOfIdentity/asCurrent");
typeOfIdentity.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> identityIdNumber = legalRepresentativeForm.getFieldAndMDForPath("identityIdNumber/asCurrent");
identityIdNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> dateOfIssue = legalRepresentativeForm.getFieldAndMDForPath("issuedDate/asCurrent");
dateOfIssue.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> expirationDate = legalRepresentativeForm.getFieldAndMDForPath("expiryDate/asCurrent");
expirationDate.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalRegion = legalRepresentativeForm.getFieldAndMDForPath("region/asCurrent");
legalRegion.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalDepartment = legalRepresentativeForm.getFieldAndMDForPath("department/asCurrent");
legalDepartment.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalArondissement = legalRepresentativeForm.getFieldAndMDForPath("arondissement/asCurrent");
legalArondissement.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalCity = legalRepresentativeForm.getFieldAndMDForPath("commune/asCurrent");
legalCity.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalQartier = legalRepresentativeForm.getFieldAndMDForPath("qartier/asCurrent");
legalQartier.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legaladdress = legalRepresentativeForm.getFieldAndMDForPath("address/asCurrent");
legaladdress.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> landLineNumber = legalRepresentativeForm.getFieldAndMDForPath("landLineNumber/asCurrent");
landLineNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> mobileNumber = legalRepresentativeForm.getFieldAndMDForPath("mobileNumber/asCurrent");
mobileNumber.setXMLValue(listesValues.get(count).toString());
count++;
COTSFieldDataAndMD<?> legalRepresentativeEmail = legalRepresentativeForm.getFieldAndMDForPath("email/asCurrent");
legalRepresentativeEmail.setXMLValue(listesValues.get(count).toString());
count++;
// --------------------------*************------------------------------------------------------------------------------//
// Invokde GED with the help of SOA
/*
* COTSFieldDataAndMD<?> url =
* documentsForm.getFieldAndMDForPath("url/asCurrent");
* url.setXMLValue("http://ged/3565622"); COTSFieldDataAndMD<?>
* docType =
* documentsForm.getFieldAndMDForPath("docType/asCurrent");
* docType.setXMLValue("contract");
*/
}
if (boInstance != null) {
boInstance = validateAndPostForm(boInstance);
}
return true;
}
/**
* Method to create FormBOInstance
*
* @param formType
* @param string
* @return
*/
private BusinessObjectInstance createFormBOInstance(String formTypeString, String documentLocator) {
FormType formType = new FormType_Id(formTypeString).getEntity();
String formTypeBo = formType.getRelatedTransactionBOId().getTrimmedValue();
log.info("#### Creating BO for " + formType);
BusinessObjectInstance boInstance = BusinessObjectInstance.create(formTypeBo);
log.info("#### Form Type BO MD Schema: " + boInstance.getSchemaMD());
boInstance.set("bo", formTypeBo);
boInstance.set("formType", formType.getId().getTrimmedValue());
boInstance.set("receiveDate", getSystemDateTime().getDate());
boInstance.set("documentLocator", documentLocator);
return boInstance;
}
/**
* Method to get the getter constants
*
* @return
*/
private Set<String> getHeaderConstants() {
Set<String> headerConstanstSet = null;
try {
headerConstanstSet = new HashSet<String>(
Arrays.asList(URLEncoder.encode(CmConstant.TYPE_D_EMPLOYEUR, CmConstant.UTF),URLEncoder.encode(CmConstant.RAISON_SOCIALE, CmConstant.UTF),URLEncoder.encode(CmConstant.NINEA, CmConstant.UTF),
URLEncoder.encode(CmConstant.NINET, CmConstant.UTF),URLEncoder.encode(CmConstant.FORME_JURIDIQUE, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_DE_CREATION, CmConstant.UTF),
URLEncoder.encode(CmConstant.DATE_IDENTIFICATION_FISCALE, CmConstant.UTF),URLEncoder.encode(CmConstant.NUMERO_REGISTER_DE_COMMERCE, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_IMM_REGISTER_DE_COMMERCE, CmConstant.UTF),
URLEncoder.encode(CmConstant.DATE_OUVERTURE_EST, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_EMBAUCHE_PREMIER_SALARY, CmConstant.UTF),URLEncoder.encode(CmConstant.SECTEUR_ACTIVITIES, CmConstant.UTF),
URLEncoder.encode(CmConstant.ACTIVATE_PRINCIPAL, CmConstant.UTF),URLEncoder.encode(CmConstant.TAUX_AT, CmConstant.UTF),
URLEncoder.encode(CmConstant.NOMBRE_TRAVAIL_REGIME_GENERAL, CmConstant.UTF),URLEncoder.encode(CmConstant.NOMBRE_TRAVAIL_REGIME_CADRE, CmConstant.UTF),
URLEncoder.encode(CmConstant.REGION, CmConstant.UTF),URLEncoder.encode(CmConstant.DEPARTMENT, CmConstant.UTF),URLEncoder.encode(CmConstant.ARONDISSEMENT, CmConstant.UTF),
URLEncoder.encode(CmConstant.COMMUNE, CmConstant.UTF),URLEncoder.encode(CmConstant.QUARTIER, CmConstant.UTF),URLEncoder.encode(CmConstant.ADDRESS, CmConstant.UTF),
URLEncoder.encode(CmConstant.TELEPHONE, CmConstant.UTF),URLEncoder.encode(CmConstant.EMAIL, CmConstant.UTF),URLEncoder.encode(CmConstant.ZONE_GEOGRAPHIQUE_CSS, CmConstant.UTF),
URLEncoder.encode(CmConstant.ZONE_GEOGRAPHIQUE_IPRES, CmConstant.UTF),URLEncoder.encode(CmConstant.SECTOR_GEOGRAPHIC_CSS, CmConstant.UTF),URLEncoder.encode(CmConstant.SECTOR_GEOGRAPHIC_IPRES, CmConstant.UTF),
URLEncoder.encode(CmConstant.AGENCE_CSS, CmConstant.UTF),URLEncoder.encode(CmConstant.AGENCE_IPRES, CmConstant.UTF),URLEncoder.encode(CmConstant.LEGAL_REPRESENTANT, CmConstant.UTF),
URLEncoder.encode(CmConstant.LAST_NAME, CmConstant.UTF),URLEncoder.encode(CmConstant.FIRST_NAME, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_DE_NAISSANCE, CmConstant.UTF),
URLEncoder.encode(CmConstant.NATIONALITE, CmConstant.UTF),URLEncoder.encode(CmConstant.LEGAL_REP_NIN, CmConstant.UTF),URLEncoder.encode(CmConstant.EMPLOYEE_NIN, CmConstant.UTF),
URLEncoder.encode(CmConstant.PAYS_DE_NAISSANCE, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_DE_DELIVRANCE, CmConstant.UTF),URLEncoder.encode(CmConstant.DATE_DE_EXPIRATION, CmConstant.UTF),
URLEncoder.encode(CmConstant.MOBILE_NUM, CmConstant.UTF),URLEncoder.encode(CmConstant.TYPE_PIECE_IDENTITE, CmConstant.UTF),URLEncoder.encode(CmConstant.NUMERO_PIECE_IDENTITE, CmConstant.UTF)
));
} catch (UnsupportedEncodingException e) {
log.error("*****Issue in Processing file***** "+e);
}
return headerConstanstSet;
}
/**
* Method to create BoInstance
*
* @param boInstance
* @return
*/
private BusinessObjectInstance validateAndPostForm(BusinessObjectInstance boInstance) {
log.info("#### BO Instance Schema before ADD: " + boInstance.getDocument().asXML());
boInstance = BusinessObjectDispatcher.add(boInstance);
log.info("#### BO Instance Schema after ADD: " + boInstance.getDocument().asXML());
/*
* boInstance.set("boStatus", "VALIDATE"); boInstance =
* BusinessObjectDispatcher.update(boInstance); log.info(
* "#### BO Instance Schema after VALIDATE: " +
* boInstance.getDocument().asXML());
*
* boInstance.set("boStatus", "READYFORPOST"); boInstance =
* BusinessObjectDispatcher.update(boInstance); log.info(
* "#### BO Instance Schema after READYFORPOST: " +
* boInstance.getDocument().asXML());
*
* boInstance.set("boStatus", "POSTED"); boInstance =
* BusinessObjectDispatcher.update(boInstance); log.info(
* "#### BO Instance Schema after POSTED: " +
* boInstance.getDocument().asXML());
*/
return boInstance;
}
/**
* Method to create To Do
*
* @param messageParam
* @param nineaNumber
* @param messageNumber
* @param fileName
*/
private void createToDo(String messageParam, String nineaNumber, String messageNumber, String fileName) {
startChanges();
// BusinessService_Id businessServiceId=new
// BusinessService_Id("F1-AddToDoEntry");
BusinessServiceInstance businessServiceInstance = BusinessServiceInstance.create("F1-AddToDoEntry");
Role_Id toDoRoleId = new Role_Id("CM-REGTODO");
Role toDoRole = toDoRoleId.getEntity();
businessServiceInstance.getFieldAndMDForPath("sendTo").setXMLValue("SNDR");
businessServiceInstance.getFieldAndMDForPath("subject").setXMLValue("Batch Update from PSRM");
businessServiceInstance.getFieldAndMDForPath("toDoType").setXMLValue("CM-REGTO");
businessServiceInstance.getFieldAndMDForPath("toDoRole").setXMLValue(toDoRole.getId().getTrimmedValue());
businessServiceInstance.getFieldAndMDForPath("drillKey1").setXMLValue("CM-REGBT");
businessServiceInstance.getFieldAndMDForPath("messageCategory").setXMLValue("90007");
businessServiceInstance.getFieldAndMDForPath("messageNumber").setXMLValue(messageNumber);
businessServiceInstance.getFieldAndMDForPath("messageParm1").setXMLValue(messageParam);
businessServiceInstance.getFieldAndMDForPath("messageParm2").setXMLValue(nineaNumber);
businessServiceInstance.getFieldAndMDForPath("messageParm3").setXMLValue(fileName);
businessServiceInstance.getFieldAndMDForPath("sortKey1").setXMLValue("CM-REGBT");
BusinessServiceDispatcher.execute(businessServiceInstance);
saveChanges();
// getSession().commit();
}
@Override
public void finalizeThreadWork() throws ThreadAbortedException, RunAbortedException {
// completeProcessing();
}
@Override
public void finalizeJobWork() throws Exception {
log.error("finalizeJobWork!!!");
super.finalizeJobWork();
}
}
}
|
package cn.edu.cqut.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.cqut.entity.CustomerPlan;
import cn.edu.cqut.entity.SaleChance;
import cn.edu.cqut.service.ICustomerPlanService;
import cn.edu.cqut.service.ISaleChanceService;
import cn.edu.cqut.util.CrmResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;
import java.time.LocalDate;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* <p>
* 前端控制器
* </p>
*
* @author CQUT SE 2020
* @since 2020-06-11
*/
@RestController
@RequestMapping("/customerPlan")
@CrossOrigin
public class CustomerPlanController {
@Autowired
private ICustomerPlanService customerplanservice;
@ApiOperation(value = "分页返回客户信息12456",
notes = "分页查询客户信息,默认返回第一页,每页10行。")
@RequestMapping(value = "/CustomerPlans", method = RequestMethod.POST)
public CrmResult<CustomerPlan> getAllCustomerPlan(
@ApiParam(value = "要查询的页码", required = true)
@RequestParam(defaultValue = "1")
Integer page, //page请求的页码,默认为1
@ApiParam(value = "每页的行数", required = true)
@RequestParam(defaultValue = "10")
Integer limit,//limit每页的行数,默认为10
CustomerPlan customerplan) {
QueryWrapper<CustomerPlan> qw = new QueryWrapper<>();
if (customerplan.getSaleChanceId()!=null) {
qw.eq("sale_Chance_Id", customerplan.getSaleChanceId()); //第一个参数是字段名
}
Page<CustomerPlan> pageCustomerPlan = customerplanservice.page(
new Page<>(page, limit), qw);
CrmResult<CustomerPlan> ret = new CrmResult<>();
ret.setCode(0);
ret.setMsg("");
ret.setCount(pageCustomerPlan.getTotal());//表里的记录总数
ret.setData(pageCustomerPlan.getRecords()); //这页的数据列表
return ret;
}
@ApiIgnore
@RequestMapping("/updateCustomerPlan")
public CrmResult<CustomerPlan> updateSaleChance(CustomerPlan customerplan) {
customerplanservice.updateById(customerplan); //根据主键更新表
CrmResult<CustomerPlan> ret = new CrmResult<>();
ret.setCode(0);
ret.setMsg("更新开发计划成功");
return ret;
}
@ApiIgnore
@RequestMapping("/addCustomerPlan")
public CrmResult<CustomerPlan> addSaleChance(CustomerPlan customerplan) {
customerplan.setResult("未完成");
customerplan.setUserName("妮子");
customerplan.setSaleChanceId(1016);
CrmResult<CustomerPlan> ret = new CrmResult<>();
ret.setCode(0);
ret.setMsg("新增计划成功");
return ret;
}
@ApiIgnore
@RequestMapping("/delCustomerPlan")
public CrmResult<SaleChance> delSaleChance(String[] ids) {
customerplanservice.removeByIds(Arrays.asList(ids));
CrmResult<SaleChance> ret = new CrmResult<>();
ret.setCode(0);
ret.setMsg("删除计划成功");
return ret;
}
}
|
package swivl.demo.entities.responses;
import lombok.Data;
import swivl.demo.entities.BrowserContent;
import java.util.List;
@Data
public class ImageRequestResponse {
private boolean valid;
private List<BrowserContent> browserContent;
}
|
package otf.gui.screens;
import java.sql.Timestamp;
import java.util.Collections;
import bt.gui.fx.core.annot.FxmlElement;
import bt.utils.NumberUtils;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.Callback;
import otf.gui.components.PercentageSizedTableColumn;
import otf.model.ClientDataModel;
import otf.model.text.TextDefinition;
import otf.model.text.Texts;
import otf.obj.BloodSugarValueEntity;
import otf.obj.msg.DeletedBloodSugarValue;
import otf.obj.msg.MessageDispatcher;
import otf.obj.msg.ModelLoadStarted;
import otf.obj.msg.ModelLoaded;
import otf.obj.msg.NewBloodSugarValue;
import otf.obj.msg.NewBolus;
/**
* @author ⋈
*
*/
public class OverviewScreen extends TabBase
{
@FxmlElement
private TableView<BloodSugarValueEntity> table;
/**
* @see bt.gui.fx.core.FxScreen#prepareScreen()
*/
@Override
protected void prepareScreen()
{
setupTable();
MessageDispatcher.get().subscribeTo(NewBloodSugarValue.class, ent -> addEntry(ent.getBz()));
MessageDispatcher.get().subscribeTo(DeletedBloodSugarValue.class, ent -> removeEntry(ent.getBz()));
MessageDispatcher.get().subscribeTo(NewBolus.class, e -> refreshTableData());
MessageDispatcher.get().subscribeTo(ModelLoaded.class, e -> refreshTableData());
MessageDispatcher.get().subscribeTo(ModelLoadStarted.class, e -> Platform.runLater(() -> this.table.setPlaceholder(new Label(Texts.get().get(TextDefinition.LOADING_VALUES).toString()))));
MessageDispatcher.get().subscribeTo(ModelLoaded.class, e -> Platform.runLater(() -> this.table.setPlaceholder(new Label(Texts.get().get(TextDefinition.NO_VALUES_FOUND).toString()))));
}
private void refreshTableData()
{
this.table.getItems().setAll(ClientDataModel.get().getBloodSugarValues());
}
private void removeEntry(int index)
{
removeEntry(this.table.getItems().get(index));
}
private void removeEntry(BloodSugarValueEntity entry)
{
this.table.getItems().removeIf(ent ->
{
boolean result = false;
if (ent.getId() != null && entry.getId() != null)
{
result = ent.getId().longValue() == entry.getId().longValue();
}
return result;
});
}
private void addEntry(BloodSugarValueEntity entry)
{
this.table.getItems().add(entry);
Collections.sort(this.table.getItems());
}
private void setupTable()
{
PercentageSizedTableColumn<BloodSugarValueEntity, String> timestampCol = new PercentageSizedTableColumn();
timestampCol.setText(Texts.get().get(TextDefinition.TIME).toString());
timestampCol.setPercentageWidth(13);
timestampCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
var timestamp = new Timestamp(t.getValue().getTimestamp());
return new ReadOnlyStringWrapper(timestamp.toString());
}
});
PercentageSizedTableColumn<BloodSugarValueEntity, String> bzCol = new PercentageSizedTableColumn();
bzCol.setText(Texts.get().get(TextDefinition.BLOODSUGAR).toString());
bzCol.setPercentageWidth(13);
bzCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
return new ReadOnlyStringWrapper(t.getValue().getBloodSugar() + "");
}
});
bzCol.setCellFactory(column ->
{
return new TableCell<>()
{
@Override
protected void updateItem(String text, boolean empty)
{
if (text != null)
{
int value = Integer.parseInt(text);
int r = 0;
if (value > 120)
{
r = NumberUtils.clamp((value - 120) * 2, 0, 255);
}
int g = 180 - (value - 100);
int b = 0;
if (value < 120)
{
b = NumberUtils.clamp((value - 120) * -4, 0, 255);
}
setStyle("-fx-background-color: rgb(" + r + "," + g + ", " + b + ");");
setText(text);
}
}
};
});
PercentageSizedTableColumn<BloodSugarValueEntity, String> beCol = new PercentageSizedTableColumn();
beCol.setText(Texts.get().get(TextDefinition.BE).toString());
beCol.setPercentageWidth(13);
beCol.setCellValueFactory(t ->
{
var bolus = t.getValue().getBolus();
String text = "-";
if (bolus != null)
{
text = bolus.getBe() > 0 ? bolus.getBe() + "" : "-";
}
return new ReadOnlyStringWrapper(text);
}
);
PercentageSizedTableColumn<BloodSugarValueEntity, String> factorCol = new PercentageSizedTableColumn();
factorCol.setText(Texts.get().get(TextDefinition.FACTOR).toString());
factorCol.setPercentageWidth(13);
factorCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
var bolus = t.getValue().getBolus();
String text = "-";
if (bolus != null)
{
text = bolus.getFactor() + "";
}
return new ReadOnlyStringWrapper(text);
}
});
PercentageSizedTableColumn<BloodSugarValueEntity, String> totalBolusCol = new PercentageSizedTableColumn();
totalBolusCol.setText(Texts.get().get(TextDefinition.TOTAL_BOLUS).toString());
totalBolusCol.setPercentageWidth(13);
totalBolusCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
var bolus = t.getValue().getBolus();
String text = "-";
if (bolus != null)
{
text = bolus.getBolusUnits() + bolus.getCorrectionUnits() + "";
}
return new ReadOnlyStringWrapper(text);
}
});
PercentageSizedTableColumn<BloodSugarValueEntity, String> bolusCol = new PercentageSizedTableColumn();
bolusCol.setText(Texts.get().get(TextDefinition.BOLUS).toString());
bolusCol.setPercentageWidth(13);
bolusCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
var bolus = t.getValue().getBolus();
String text = "-";
if (bolus != null)
{
text = bolus.getBolusUnits() + "";
}
return new ReadOnlyStringWrapper(text);
}
});
PercentageSizedTableColumn<BloodSugarValueEntity, String> correctionCol = new PercentageSizedTableColumn();
correctionCol.setText(Texts.get().get(TextDefinition.CORRECTION).toString());
correctionCol.setPercentageWidth(13);
correctionCol.setCellValueFactory(new Callback<CellDataFeatures<BloodSugarValueEntity, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(CellDataFeatures<BloodSugarValueEntity, String> t)
{
var bolus = t.getValue().getBolus();
String text = "-";
if (bolus != null)
{
text = bolus.getCorrectionUnits() + "";
}
return new ReadOnlyStringWrapper(text);
}
});
this.table.setPlaceholder(new Label(Texts.get().get(TextDefinition.NO_VALUES_FOUND).toString()));
this.table.getColumns().addAll(timestampCol, bzCol, beCol, factorCol, totalBolusCol, bolusCol, correctionCol);
}
/**
* @see bt.gui.fx.core.FxScreen#prepareStage(javafx.stage.Stage)
*/
@Override
protected void prepareStage(Stage stage)
{
}
/**
* @see bt.gui.fx.core.FxScreen#prepareScene(javafx.scene.Scene)
*/
@Override
protected void prepareScene(Scene scene)
{
}
/**
* @see otf.gui.screens.TabBase#getTabName()
*/
@Override
public String getTabName()
{
return Texts.get().get(TextDefinition.OVERVIEW).toString();
}
/**
* @see otf.gui.screens.TabBase#onTabSelect()
*/
@Override
public void onTabSelect()
{
}
/**
* @see otf.gui.screens.TabBase#onTabDeselect()
*/
@Override
public void onTabDeselect()
{
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.pmm.sdgc.converter;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
*
* @author acg
*/
@Converter(autoApply = false)
public class BooleanConverter implements AttributeConverter<Boolean, String> {
@Override
public String convertToDatabaseColumn(Boolean valor) {
if (valor==null) return null;
if (valor) {
return "S";
} else {
return "N";
}
}
@Override
public Boolean convertToEntityAttribute(String valor) {
if (valor==null) return null;
if (valor.isEmpty()) return null;
if (valor.equals("S")) return true;
return false;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.test.context.BootstrapContext;
import org.springframework.test.context.CacheAwareContextLoaderDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextAnnotationUtils;
import org.springframework.test.context.TestContextAnnotationUtils.AnnotationDescriptor;
import org.springframework.test.context.TestContextBootstrapper;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.context.util.TestContextSpringFactoriesUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Abstract implementation of the {@link TestContextBootstrapper} interface which
* provides most of the behavior required by a bootstrapper.
*
* <p>Concrete subclasses typically will only need to provide implementations for
* the following methods:
* <ul>
* <li>{@link #getDefaultContextLoaderClass}
* <li>{@link #processMergedContextConfiguration}
* </ul>
*
* <p>To plug in custom
* {@link org.springframework.test.context.cache.ContextCache ContextCache}
* support, override {@link #getCacheAwareContextLoaderDelegate()}.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @author Phillip Webb
* @since 4.1
*/
public abstract class AbstractTestContextBootstrapper implements TestContextBootstrapper {
private final Log logger = LogFactory.getLog(getClass());
@Nullable
private BootstrapContext bootstrapContext;
@Override
public void setBootstrapContext(BootstrapContext bootstrapContext) {
this.bootstrapContext = bootstrapContext;
}
@Override
public BootstrapContext getBootstrapContext() {
Assert.state(this.bootstrapContext != null, "No BootstrapContext set");
return this.bootstrapContext;
}
/**
* Build a new {@link DefaultTestContext} using the {@linkplain Class test class}
* in the {@link BootstrapContext} associated with this bootstrapper and
* by delegating to {@link #buildMergedContextConfiguration()} and
* {@link #getCacheAwareContextLoaderDelegate()}.
* <p>Concrete subclasses may choose to override this method to return a
* custom {@link TestContext} implementation.
* @since 4.2
*/
@Override
public TestContext buildTestContext() {
return new DefaultTestContext(getBootstrapContext().getTestClass(), buildMergedContextConfiguration(),
getCacheAwareContextLoaderDelegate());
}
@Override
public final List<TestExecutionListener> getTestExecutionListeners() {
Class<?> clazz = getBootstrapContext().getTestClass();
Class<TestExecutionListeners> annotationType = TestExecutionListeners.class;
List<TestExecutionListener> listeners = new ArrayList<>(8);
boolean usingDefaults = false;
AnnotationDescriptor<TestExecutionListeners> descriptor =
TestContextAnnotationUtils.findAnnotationDescriptor(clazz, annotationType);
// Use defaults?
if (descriptor == null) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("@TestExecutionListeners is not present for class [%s]: using defaults.",
clazz.getName()));
}
usingDefaults = true;
listeners.addAll(getDefaultTestExecutionListeners());
}
else {
// Traverse the class hierarchy...
while (descriptor != null) {
Class<?> declaringClass = descriptor.getDeclaringClass();
TestExecutionListeners testExecutionListeners = descriptor.getAnnotation();
if (logger.isTraceEnabled()) {
logger.trace(String.format("Retrieved @TestExecutionListeners [%s] for declaring class [%s].",
testExecutionListeners, declaringClass.getName()));
}
boolean inheritListeners = testExecutionListeners.inheritListeners();
AnnotationDescriptor<TestExecutionListeners> parentDescriptor = descriptor.next();
// If there are no listeners to inherit, we might need to merge the
// locally declared listeners with the defaults.
if ((!inheritListeners || parentDescriptor == null) &&
testExecutionListeners.mergeMode() == MergeMode.MERGE_WITH_DEFAULTS) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Merging default listeners with listeners configured via " +
"@TestExecutionListeners for class [%s].", descriptor.getRootDeclaringClass().getName()));
}
usingDefaults = true;
listeners.addAll(getDefaultTestExecutionListeners());
}
listeners.addAll(0, instantiateListeners(testExecutionListeners.listeners()));
descriptor = (inheritListeners ? parentDescriptor : null);
}
}
if (usingDefaults) {
// Remove possible duplicates if we loaded default listeners.
List<TestExecutionListener> uniqueListeners = new ArrayList<>(listeners.size());
listeners.forEach(listener -> {
Class<? extends TestExecutionListener> listenerClass = listener.getClass();
if (uniqueListeners.stream().map(Object::getClass).noneMatch(listenerClass::equals)) {
uniqueListeners.add(listener);
}
});
listeners = uniqueListeners;
// Sort by Ordered/@Order if we loaded default listeners.
AnnotationAwareOrderComparator.sort(listeners);
}
if (logger.isTraceEnabled()) {
logger.trace("Using TestExecutionListeners for test class [%s]: %s"
.formatted(clazz.getName(), listeners));
}
else if (logger.isDebugEnabled()) {
logger.debug("Using TestExecutionListeners for test class [%s]: %s"
.formatted(clazz.getSimpleName(), classSimpleNames(listeners)));
}
return listeners;
}
/**
* Get the default {@link TestExecutionListener TestExecutionListeners} for
* this bootstrapper.
* <p>The default implementation delegates to
* {@link TestContextSpringFactoriesUtils#loadFactoryImplementations(Class)}.
* <p>This method is invoked by {@link #getTestExecutionListeners()}.
* @return an <em>unmodifiable</em> list of default {@code TestExecutionListener}
* instances
* @since 6.0
*/
protected List<TestExecutionListener> getDefaultTestExecutionListeners() {
return TestContextSpringFactoriesUtils.loadFactoryImplementations(TestExecutionListener.class);
}
@SuppressWarnings("unchecked")
private List<TestExecutionListener> instantiateListeners(Class<? extends TestExecutionListener>... classes) {
List<TestExecutionListener> listeners = new ArrayList<>(classes.length);
for (Class<? extends TestExecutionListener> listenerClass : classes) {
try {
listeners.add(BeanUtils.instantiateClass(listenerClass));
}
catch (BeanInstantiationException ex) {
Throwable cause = ex.getCause();
if (cause instanceof ClassNotFoundException || cause instanceof NoClassDefFoundError) {
if (logger.isDebugEnabled()) {
logger.debug("""
Skipping candidate %1$s [%2$s] due to a missing dependency. \
Specify custom %1$s classes or make the default %1$s classes \
and their required dependencies available. Offending class: [%3$s]"""
.formatted(TestExecutionListener.class.getSimpleName(), listenerClass.getName(),
cause.getMessage()));
}
}
else {
throw ex;
}
}
}
return listeners;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public final MergedContextConfiguration buildMergedContextConfiguration() {
Class<?> testClass = getBootstrapContext().getTestClass();
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = getCacheAwareContextLoaderDelegate();
if (TestContextAnnotationUtils.findAnnotationDescriptorForTypes(
testClass, ContextConfiguration.class, ContextHierarchy.class) == null) {
return buildDefaultMergedContextConfiguration(testClass, cacheAwareContextLoaderDelegate);
}
if (TestContextAnnotationUtils.findAnnotationDescriptor(testClass, ContextHierarchy.class) != null) {
Map<String, List<ContextConfigurationAttributes>> hierarchyMap =
ContextLoaderUtils.buildContextHierarchyMap(testClass);
MergedContextConfiguration parentConfig = null;
MergedContextConfiguration mergedConfig = null;
for (List<ContextConfigurationAttributes> list : hierarchyMap.values()) {
List<ContextConfigurationAttributes> reversedList = new ArrayList<>(list);
Collections.reverse(reversedList);
// Don't use the supplied testClass; instead ensure that we are
// building the MCC for the actual test class that declared the
// configuration for the current level in the context hierarchy.
Assert.notEmpty(reversedList, "ContextConfigurationAttributes list must not be empty");
Class<?> declaringClass = reversedList.get(0).getDeclaringClass();
mergedConfig = buildMergedContextConfiguration(
declaringClass, reversedList, parentConfig, cacheAwareContextLoaderDelegate, true);
parentConfig = mergedConfig;
}
// Return the last level in the context hierarchy
Assert.state(mergedConfig != null, "No merged context configuration");
return mergedConfig;
}
else {
return buildMergedContextConfiguration(testClass,
ContextLoaderUtils.resolveContextConfigurationAttributes(testClass),
null, cacheAwareContextLoaderDelegate, true);
}
}
private MergedContextConfiguration buildDefaultMergedContextConfiguration(Class<?> testClass,
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) {
List<ContextConfigurationAttributes> defaultConfigAttributesList =
Collections.singletonList(new ContextConfigurationAttributes(testClass));
ContextLoader contextLoader = resolveContextLoader(testClass, defaultConfigAttributesList);
if (logger.isTraceEnabled()) {
logger.trace(String.format(
"Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s",
testClass.getName(), contextLoader.getClass().getName()));
}
else if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s",
testClass.getSimpleName(), contextLoader.getClass().getSimpleName()));
}
return buildMergedContextConfiguration(testClass, defaultConfigAttributesList, null,
cacheAwareContextLoaderDelegate, false);
}
/**
* Build the {@link MergedContextConfiguration merged context configuration}
* for the supplied {@link Class testClass}, context configuration attributes,
* and parent context configuration.
* @param testClass the test class for which the {@code MergedContextConfiguration}
* should be built (must not be {@code null})
* @param configAttributesList the list of context configuration attributes for the
* specified test class, ordered <em>bottom-up</em> (i.e., as if we were
* traversing up the class hierarchy and enclosing class hierarchy); never
* {@code null} or empty
* @param parentConfig the merged context configuration for the parent application
* context in a context hierarchy, or {@code null} if there is no parent
* @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
* be passed to the {@code MergedContextConfiguration} constructor
* @param requireLocationsClassesOrInitializers whether locations, classes, or
* initializers are required; typically {@code true} but may be set to {@code false}
* if the configured loader supports empty configuration
* @return the merged context configuration
* @see #resolveContextLoader
* @see ContextLoaderUtils#resolveContextConfigurationAttributes
* @see SmartContextLoader#processContextConfiguration
* @see ContextLoader#processLocations
* @see ActiveProfilesUtils#resolveActiveProfiles
* @see ApplicationContextInitializerUtils#resolveInitializerClasses
* @see MergedContextConfiguration
*/
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributesList, @Nullable MergedContextConfiguration parentConfig,
CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate,
boolean requireLocationsClassesOrInitializers) {
Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be null or empty");
ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
List<String> locations = new ArrayList<>();
List<Class<?>> classes = new ArrayList<>();
List<Class<?>> initializers = new ArrayList<>();
for (ContextConfigurationAttributes configAttributes : configAttributesList) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Processing locations and classes for context configuration attributes %s",
configAttributes));
}
if (contextLoader instanceof SmartContextLoader smartContextLoader) {
smartContextLoader.processContextConfiguration(configAttributes);
locations.addAll(0, Arrays.asList(configAttributes.getLocations()));
classes.addAll(0, Arrays.asList(configAttributes.getClasses()));
}
else {
@SuppressWarnings("deprecation")
String[] processedLocations = contextLoader.processLocations(
configAttributes.getDeclaringClass(), configAttributes.getLocations());
locations.addAll(0, Arrays.asList(processedLocations));
// Legacy ContextLoaders don't know how to process classes
}
initializers.addAll(0, Arrays.asList(configAttributes.getInitializers()));
if (!configAttributes.isInheritLocations()) {
break;
}
}
Set<ContextCustomizer> contextCustomizers = getContextCustomizers(testClass,
Collections.unmodifiableList(configAttributesList));
Assert.state(!(requireLocationsClassesOrInitializers &&
areAllEmpty(locations, classes, initializers, contextCustomizers)), () -> String.format(
"%s was unable to detect defaults, and no ApplicationContextInitializers " +
"or ContextCustomizers were declared for context configuration attributes %s",
contextLoader.getClass().getSimpleName(), configAttributesList));
MergedTestPropertySources mergedTestPropertySources =
TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
StringUtils.toStringArray(locations), ClassUtils.toClassArray(classes),
ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
ActiveProfilesUtils.resolveActiveProfiles(testClass),
mergedTestPropertySources.getPropertySourceDescriptors(),
mergedTestPropertySources.getProperties(),
contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);
return processMergedContextConfiguration(mergedConfig);
}
private Set<ContextCustomizer> getContextCustomizers(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributes) {
List<ContextCustomizerFactory> factories = getContextCustomizerFactories();
Set<ContextCustomizer> customizers = new LinkedHashSet<>(factories.size());
for (ContextCustomizerFactory factory : factories) {
ContextCustomizer customizer = factory.createContextCustomizer(testClass, configAttributes);
if (customizer != null) {
customizers.add(customizer);
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using ContextCustomizers for test class [%s]: %s"
.formatted(testClass.getName(), customizers));
}
else if (logger.isDebugEnabled()) {
logger.debug("Using ContextCustomizers for test class [%s]: %s"
.formatted(testClass.getSimpleName(), classSimpleNames(customizers)));
}
return customizers;
}
/**
* Get the {@link ContextCustomizerFactory} instances for this bootstrapper.
* <p>The default implementation delegates to
* {@link TestContextSpringFactoriesUtils#loadFactoryImplementations(Class)}.
* @since 4.3
*/
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
return TestContextSpringFactoriesUtils.loadFactoryImplementations(ContextCustomizerFactory.class);
}
/**
* Resolve the {@link ContextLoader} {@linkplain Class class} to use for the
* supplied list of {@link ContextConfigurationAttributes} and then instantiate
* and return that {@code ContextLoader}.
* <p>If the user has not explicitly declared which loader to use, the value
* returned from {@link #getDefaultContextLoaderClass} will be used as the
* default context loader class. For details on the class resolution process,
* see {@link #resolveExplicitContextLoaderClass} and
* {@link #getDefaultContextLoaderClass}.
* @param testClass the test class for which the {@code ContextLoader} should be
* resolved; must not be {@code null}
* @param configAttributesList the list of configuration attributes to process; must
* not be {@code null}; must be ordered <em>bottom-up</em>
* (i.e., as if we were traversing up the class hierarchy and enclosing class hierarchy)
* @return the resolved {@code ContextLoader} for the supplied {@code testClass}
* (never {@code null})
* @throws IllegalStateException if {@link #getDefaultContextLoaderClass(Class)}
* returns {@code null}
*/
protected ContextLoader resolveContextLoader(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributesList) {
Assert.notNull(testClass, "Class must not be null");
Assert.notNull(configAttributesList, "ContextConfigurationAttributes list must not be null");
Class<? extends ContextLoader> contextLoaderClass = resolveExplicitContextLoaderClass(configAttributesList);
if (contextLoaderClass == null) {
contextLoaderClass = getDefaultContextLoaderClass(testClass);
}
if (logger.isTraceEnabled()) {
logger.trace(String.format("Using ContextLoader class [%s] for test class [%s]",
contextLoaderClass.getName(), testClass.getName()));
}
return BeanUtils.instantiateClass(contextLoaderClass, ContextLoader.class);
}
/**
* Resolve the {@link ContextLoader} {@linkplain Class class} to use for the supplied
* list of {@link ContextConfigurationAttributes}.
* <p>Beginning with the first level in the context configuration attributes hierarchy:
* <ol>
* <li>If the {@link ContextConfigurationAttributes#getContextLoaderClass()
* contextLoaderClass} property of {@link ContextConfigurationAttributes} is
* configured with an explicit class, that class will be returned.</li>
* <li>If an explicit {@code ContextLoader} class is not specified at the current
* level in the hierarchy, traverse to the next level in the hierarchy and return to
* step #1.</li>
* </ol>
* @param configAttributesList the list of configuration attributes to process;
* must not be {@code null}; must be ordered <em>bottom-up</em>
* (i.e., as if we were traversing up the class hierarchy and enclosing class hierarchy)
* @return the {@code ContextLoader} class to use for the supplied configuration
* attributes, or {@code null} if no explicit loader is found
* @throws IllegalArgumentException if supplied configuration attributes are
* {@code null} or <em>empty</em>
*/
@Nullable
protected Class<? extends ContextLoader> resolveExplicitContextLoaderClass(
List<ContextConfigurationAttributes> configAttributesList) {
Assert.notNull(configAttributesList, "ContextConfigurationAttributes list must not be null");
for (ContextConfigurationAttributes configAttributes : configAttributesList) {
if (logger.isTraceEnabled()) {
logger.trace("Resolving ContextLoader for context configuration attributes " + configAttributes);
}
Class<? extends ContextLoader> contextLoaderClass = configAttributes.getContextLoaderClass();
if (ContextLoader.class != contextLoaderClass) {
if (logger.isTraceEnabled()) {
logger.trace("Found explicit ContextLoader class [%s] for context configuration attributes %s"
.formatted(contextLoaderClass.getName(), configAttributes));
}
else if (logger.isDebugEnabled()) {
logger.debug("Found explicit ContextLoader class [%s] for test class [%s]"
.formatted(contextLoaderClass.getSimpleName(), configAttributes.getDeclaringClass().getSimpleName()));
}
return contextLoaderClass;
}
}
return null;
}
/**
* Get the {@link CacheAwareContextLoaderDelegate} to use for transparent
* interaction with the {@code ContextCache}.
* <p>The default implementation delegates to
* {@code getBootstrapContext().getCacheAwareContextLoaderDelegate()} and
* the default one will load {@link org.springframework.test.context.ApplicationContextFailureProcessor}
* via the service loading mechanism.
* <p>Concrete subclasses may choose to override this method to return a custom
* {@code CacheAwareContextLoaderDelegate} implementation with custom
* {@link org.springframework.test.context.cache.ContextCache ContextCache} support.
* @return the context loader delegate (never {@code null})
* @see org.springframework.test.context.ApplicationContextFailureProcessor
*/
protected CacheAwareContextLoaderDelegate getCacheAwareContextLoaderDelegate() {
return getBootstrapContext().getCacheAwareContextLoaderDelegate();
}
/**
* Determine the default {@link ContextLoader} {@linkplain Class class}
* to use for the supplied test class.
* <p>The class returned by this method will only be used if a {@code ContextLoader}
* class has not been explicitly declared via {@link ContextConfiguration#loader}.
* @param testClass the test class for which to retrieve the default
* {@code ContextLoader} class
* @return the default {@code ContextLoader} class for the supplied test class
* (never {@code null})
*/
protected abstract Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass);
/**
* Process the supplied, newly instantiated {@link MergedContextConfiguration} instance.
* <p>The returned {@link MergedContextConfiguration} instance may be a wrapper
* around or a replacement for the original.
* <p>The default implementation simply returns the supplied instance unmodified.
* <p>Concrete subclasses may choose to return a specialized subclass of
* {@link MergedContextConfiguration} based on properties in the supplied instance.
* @param mergedConfig the {@code MergedContextConfiguration} to process; never {@code null}
* @return a fully initialized {@code MergedContextConfiguration}; never {@code null}
*/
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
return mergedConfig;
}
private static List<String> classSimpleNames(Collection<?> components) {
return components.stream().map(Object::getClass).map(Class::getSimpleName).toList();
}
private static boolean areAllEmpty(Collection<?>... collections) {
return Arrays.stream(collections).allMatch(Collection::isEmpty);
}
}
|
package controllers;
import static services.UserService.getUserByStudentNumber;
import static spark.Spark.*;
import controllers.utils.Request;
import controllers.utils.Response;
import services.UserService.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static services.SessionService.*;
import static services.SessionTryService.*;
public class SessionController {
public static void init() {
path("/sessions", () -> {
before("", Request::requiresAuthentication);
before("/*", Request::requiresAuthentication);
/*
* Get all sessions
*/
get("", (req, res) -> {
int id = Integer.parseInt(req.queryParams("user"));
String userRole = Request.getRole(req);
boolean isOwner =
Request.getUserId(req) == id ||
Request.hasOneOfRoles(req, Arrays.asList(User.TEACHER, User.ADMIN));
if(!isOwner) {
return Response.unauthorized(res);
}
List<Session> sessions;
if(Request.getUserId(req) != id && userRole.equals(User.TEACHER)) {
sessions = getSessionsByUserForCreator(id, Request.getUserId(req));
} else {
sessions = getSessionsByUser(id);
}
List<Session> response = sessions.stream().map(session -> {
session.populateSessionTries(getSessionTriesBySession(session.id));
return session;
})
.collect(Collectors.toList());
return Response.ok(res, response);
});
/*
* Get session by id
*/
get("/:id", (req, res) -> {
int id = Integer.parseInt(req.params(":id"));
return Response.ok(res, getSessionById(id));
});
exception(NumberFormatException.class, (exception, request, response) ->
Response.badRequest(response)
);
exception(SessionNotFound.class, (exception, request, response) ->
Response.notFound(response)
);
/*
* Create new session
*/
post("", (req, res) -> {
Session session = Request.getBodyAs(req.body(), Session.class);
String studentNumber = Request.getStudentNumber(req);
User user = getUserByStudentNumber(studentNumber);
session.user = user.id;
Session createdSession = createSession(session);
return Response.created(res, createdSession);
});
exception(SessionNotCreated.class, (exception, request, response) ->
Response.internalServerError(response)
);
});
}
}
|
package com.article.service;
import com.article.entities.Article;
import com.article.repository.ArticleRepository;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by musaceylan on 11/8/16.
*/
@Service
public class ArticleService {
@Autowired
private ArticleRepository repository;
public Iterable <Article> findAll(){
return repository.findAll();
}
public void deleteAll(){
this.repository.deleteAll();
}
public void getArticle(){
Date publishDate = new Date();
List<Article> articlesList = new ArrayList<>();
for (int i = 0 ; i<1 ; i++){
List articlesListTemp = getArticlesList(publishDate.toString());
articlesList.addAll(articlesListTemp);
/// startDate = startDate.plusDays(1L); uses not DATE LOCALDATE
}
// for (Article article:articlesList){
// getArticleContent(article);
// //System.out.print(article.getContent);
// this.repository.save(article);
// }
}
private List<Article> getArticlesList(String date){
Article article = null;
List<Article> articleList = new ArrayList<>();
try{
Jsoup.connect("http://dergipark.gov.tr/api/public/oai/?verb=ListRecords&metadataPrefix=oai_dc").get();
}
catch (IOException e ){
e.printStackTrace();
}
return articleList;
}
private void getArticleContent(Article article) {
}
}
|
package me.itzg.ghrelwatcher.model;
import lombok.Data;
/**
* @author Geoff Bourne
* @since Jul 2018
*/
@Data
public class ValueHolder<T> {
T value;
public static <T> ValueHolder<T> of(T data) {
final ValueHolder<T> response = new ValueHolder<>();
response.setValue(data);
return response;
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
只有两种情况:
Case 1:p和q在两棵不同的子树 => 返回current root node
Case 2:p和q在同侧(p在q的子树或q在p的子树)=> 先遇到p就返回p,先遇到q就返回q
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return search(root, p.val, q.val);
}
private TreeNode search(TreeNode node, int pValue, int qValue) {
if(node == null) {
return null;
}
if(node.val == pValue || node.val == qValue) {
return node;
}
TreeNode targetNodeFromLeft = search(node.left, pValue, qValue);
TreeNode targetNodeFromRight = search(node.right, pValue, qValue);
// if one is on the left, the other is on the right
if(targetNodeFromLeft != null && targetNodeFromRight != null) {
return node;
}
// if only one node was found
if(targetNodeFromLeft != null) {
return targetNodeFromLeft;
}
if(targetNodeFromRight != null) {
return targetNodeFromRight;
}
// if neither of them was found
return null;
}
}
|
package com.esum.web.apps.dbc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.esum.appetizer.dao.AbstractDao;
import com.esum.appetizer.util.PageUtil;
import com.esum.appframework.exception.ApplicationException;
import com.esum.web.apps.dbc.vo.BatchJobErrorLog;
import com.esum.web.apps.dbc.vo.BatchJobInstanceLog;
public class BatchJobInstanceLogDao extends AbstractDao {
@Autowired
@Resource(name="dataSource")
private DataSource ds;
public List<BatchJobInstanceLog> selectList(BatchJobInstanceLog batchJobInstanceLog, PageUtil pageUtil) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("batchJobInstanceLog", batchJobInstanceLog);
param.put("startRow", pageUtil.getStartRow());
param.put("endRow", pageUtil.getEndRow());
return getSqlSession().selectList("batchJobInstanceLog.selectPageList", param);
}
public int countList(BatchJobInstanceLog batchJobInstanceLog) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("batchJobInstanceLog", batchJobInstanceLog);
return (Integer)getSqlSession().selectOne("batchJobInstanceLog.countList", param);
}
public List<BatchJobErrorLog> selectErrorList(String jobInstanceId, PageUtil pageUtil) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("jobInstanceId", jobInstanceId);
param.put("startRow", pageUtil.getStartRow());
param.put("endRow", pageUtil.getEndRow());
return getSqlSession().selectList("batchJobInstanceLog.selectErrorPageList", param);
}
public int errorCountList(String jobInstanceId) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("jobInstanceId", jobInstanceId);
return (Integer)getSqlSession().selectOne("batchJobInstanceLog.errorCountList", param);
}
public Map selectErrorList4Excel(String jobInstanceId) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Map result = new HashMap();
List queryResult = new ArrayList();
String sql = "select * from ( SELECT LOG.JOB_INSTANCE_ID, LOG.JOB_NAME "
// + "case when LOG.JOB_TYPE = 'T' then 'Template' "
// + " when LOG.JOB_TYPE = 'J' then 'Task' end JOB_TYPE "
// + ", LOG.NODE_ID"
+ ", LOG.DOC_NUMBER, LOG.ERROR_CODE"
+ " , CODE.SOLUTION, CODE.DESCRIPTION"
+ ", LOG.ERROR_MESSAGE"
+ " , to_char(to_date(substr(LOG.ERROR_TIME, 1,8)),'YYYY-MM-DD') || ' ' || to_char(to_timestamp(substr(LOG.ERROR_TIME, 1,14)), 'HH24:MI:SS') as ERROR_TIME"
+ " FROM BATCH_JOB_ERROR_LOG LOG, BATCH_JOB_ERROR_CODE CODE";
if(jobInstanceId != null && jobInstanceId.length() > 0 ) {
sql += " WHERE LOG.JOB_INSTANCE_ID = '" + jobInstanceId +"' AND LOG.ERROR_CODE = CODE.ERROR_CODE(+) " ;
} else {
sql += " WHERE LOG.ERROR_CODE = CODE.ERROR_CODE(+) " ;
}
sql += " )";
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
String[] title = new String[rsmd.getColumnCount()];
int[] colSize = new int[rsmd.getColumnCount()];
for(int i=0; i<rsmd.getColumnCount(); i++) {
title[i] = rsmd.getColumnName(i+1);
colSize[i] = rsmd.getColumnDisplaySize(i+1);
}
int count = 0;
while(rs.next()) {
List row = new ArrayList();
for(int i=0; i<rsmd.getColumnCount(); i++) {
Object col = rs.getObject(i+1);
row.add(i, col);
}
queryResult.add(count, row);
count++;
}
result.put("table", StringUtils.isEmpty(rsmd.getTableName(1)) ? "BATCH_JOB_ERROR_LOG" : rsmd.getTableName(1));
result.put("header", title);
result.put("size", colSize);
result.put("data", queryResult);
return result;
} catch (Exception e) {
throw new ApplicationException(e);
} finally {
if(rs != null) try { rs.close(); } catch(SQLException e) { }
if(stmt != null) try { stmt.close(); } catch(SQLException e) { }
if(conn != null) try { conn.close(); } catch(SQLException e) { }
}
}
}
|
package com.github.andlyticsproject.util;
import android.os.AsyncTask;
public abstract class DetachableAsyncTask<Params, Progress, Result, Parent> extends
AsyncTask<Params, Progress, Result> {
protected Parent activity;
public DetachableAsyncTask(Parent activity) {
this.activity = activity;
}
public void attach(Parent activity) {
this.activity = activity;
}
public DetachableAsyncTask<Params, Progress, Result, Parent> detach() {
activity = null;
return this;
}
Parent getParent() {
return activity;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.