text stringlengths 10 2.72M |
|---|
package com.vr.player.ndk;
import com.vr.player.settings.SettingsManager;
/**
* Created by qiangwang on 1/13/17.
*/
public interface INative {
boolean setShowMode(SettingsManager.ShowMode mode, SettingsManager.ResolutionRatio resolution, boolean isLeft);
int onSurfaceCreated(boolean isSingle);
void onSurfaceChanged(int w, int h);
void onDrawFrame(float degreeX, float degreeY, float degreeZ, float fov, boolean isLeft);
void draw(int textureId);
float getDegreeX(boolean isLeft);
float getDegreeY(boolean isLeft);
float getDegreeZ(boolean isLeft);
float getFov(boolean isLeft);
void resetDegree();
String aesEncode(String id);
boolean aesDecode(String hardId, String androidId, String result1, String result2);
boolean hasLicence();
}
|
package com.itobuz.android.awesomechat.navigation;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.itobuz.android.awesomechat.R;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Created by Debasis on 24/02/17.
*/
public class AndroidAboutNavigator implements AboutNavigator {
private final AppCompatActivity activity;
private AboutNavigator.AboutDialogListener dialogListener;
public AndroidAboutNavigator(AppCompatActivity activity) {
this.activity = activity;
}
@Override
public void showOkDialog() {
MaterialDialog dialog = new MaterialDialog.Builder(activity)
.content(R.string.about_dialog_save_content)
.positiveText(R.string.about_dialog_about_positive)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
// activity.finish();
}
})
.show();
}
@Override
public void attach(AboutDialogListener dialogListener) {
this.dialogListener = dialogListener;
}
@Override
public void detach(AboutDialogListener dialogListener) {
this.dialogListener = null;
}
@Override
public void toLogin() {
}
@Override
public void toMainActivity() {
}
@Override
public void toParent() {
activity.finish();
}
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
return true;
}
}
|
package com.citibank.ods.entity.bg.valueobject;
import java.math.BigInteger;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
//
//ยฉ2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.entity.bg.valueobject;
* @version 1.0
* @author gerson.a.rodrigues,Apr 18, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class BaseTbgBranchEntityVO extends BaseEntityVO
{
private String m_agnBankCode;
private String m_agnCode;
private String m_agnVrfyCode;
private String m_agnText;
private String m_agnAddrText;
private String m_agencyTwshpText;
private String m_agencyTwshpStateCode;
private String m_agnZipCode;
private String m_agnAreaCode;
private String m_agnPhoneNbr;
private String m_agnFaxNbr;
private String m_agnTelexNbr;
private BigInteger m_agnClearHouseCode;
private String m_actyCode;
/**
* @return Returns actyCode.
*/
public String getActyCode()
{
return m_actyCode;
}
/**
* @param actyCode_ Field actyCode to be setted.
*/
public void setActyCode( String actyCode_ )
{
m_actyCode = actyCode_;
}
/**
* @return Returns agencyTwshpStateCode.
*/
public String getAgencyTwshpStateCode()
{
return m_agencyTwshpStateCode;
}
/**
* @param agencyTwshpStateCode_ Field agencyTwshpStateCode to be setted.
*/
public void setAgencyTwshpStateCode( String agencyTwshpStateCode_ )
{
m_agencyTwshpStateCode = agencyTwshpStateCode_;
}
/**
* @return Returns agencyTwshpText.
*/
public String getAgencyTwshpText()
{
return m_agencyTwshpText;
}
/**
* @param agencyTwshpText_ Field agencyTwshpText to be setted.
*/
public void setAgencyTwshpText( String agencyTwshpText_ )
{
m_agencyTwshpText = agencyTwshpText_;
}
/**
* @return Returns agnAddrText.
*/
public String getAgnAddrText()
{
return m_agnAddrText;
}
/**
* @param agnAddrText_ Field agnAddrText to be setted.
*/
public void setAgnAddrText( String agnAddrText_ )
{
m_agnAddrText = agnAddrText_;
}
/**
* @return Returns agnAreaCode.
*/
public String getAgnAreaCode()
{
return m_agnAreaCode;
}
/**
* @param agnAreaCode_ Field agnAreaCode to be setted.
*/
public void setAgnAreaCode( String agnAreaCode_ )
{
m_agnAreaCode = agnAreaCode_;
}
/**
* @return Returns agnBankCode.
*/
public String getAgnBankCode()
{
return m_agnBankCode;
}
/**
* @param agnBankCode_ Field agnBankCode to be setted.
*/
public void setAgnBankCode( String agnBankCode_ )
{
m_agnBankCode = agnBankCode_;
}
/**
* @return Returns agnClearHouseCode.
*/
public BigInteger getAgnClearHouseCode()
{
return m_agnClearHouseCode;
}
/**
* @param agnClearHouseCode_ Field agnClearHouseCode to be setted.
*/
public void setAgnClearHouseCode( BigInteger agnClearHouseCode_ )
{
m_agnClearHouseCode = agnClearHouseCode_;
}
/**
* @return Returns agnCode.
*/
public String getAgnCode()
{
return m_agnCode;
}
/**
* @param agnCode_ Field agnCode to be setted.
*/
public void setAgnCode( String agnCode_ )
{
m_agnCode = agnCode_;
}
/**
* @return Returns agnFaxNbr.
*/
public String getAgnFaxNbr()
{
return m_agnFaxNbr;
}
/**
* @param agnFaxNbr_ Field agnFaxNbr to be setted.
*/
public void setAgnFaxNbr( String agnFaxNbr_ )
{
m_agnFaxNbr = agnFaxNbr_;
}
/**
* @return Returns agnPhoneNbr.
*/
public String getAgnPhoneNbr()
{
return m_agnPhoneNbr;
}
/**
* @param agnPhoneNbr_ Field agnPhoneNbr to be setted.
*/
public void setAgnPhoneNbr( String agnPhoneNbr_ )
{
m_agnPhoneNbr = agnPhoneNbr_;
}
/**
* @return Returns agnTelexNbr.
*/
public String getAgnTelexNbr()
{
return m_agnTelexNbr;
}
/**
* @param agnTelexNbr_ Field agnTelexNbr to be setted.
*/
public void setAgnTelexNbr( String agnTelexNbr_ )
{
m_agnTelexNbr = agnTelexNbr_;
}
/**
* @return Returns agnText.
*/
public String getAgnText()
{
return m_agnText;
}
/**
* @param agnText_ Field agnText to be setted.
*/
public void setAgnText( String agnText_ )
{
m_agnText = agnText_;
}
/**
* @return Returns agnVrfyCode.
*/
public String getAgnVrfyCode()
{
return m_agnVrfyCode;
}
/**
* @param agnVrfyCode_ Field agnVrfyCode to be setted.
*/
public void setAgnVrfyCode( String agnVrfyCode_ )
{
m_agnVrfyCode = agnVrfyCode_;
}
/**
* @return Returns agnZipCode.
*/
public String getAgnZipCode()
{
return m_agnZipCode;
}
/**
* @param agnZipCode_ Field agnZipCode to be setted.
*/
public void setAgnZipCode( String agnZipCode_ )
{
m_agnZipCode = agnZipCode_;
}
} |
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class Launcher
{
public static void main (String[] args)
{
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
// change configuration settings
config.width = 800;
config.height = 600;
config.title = "Remembering You";
BaseGame myProgram = new AdventureGame();
LwjglApplication launcher = new LwjglApplication( myProgram, config );
}
} |
import java.lang.*;
import java.util.*;
import java.io.*;
// #!/usr/bin/python -O
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include<stdbool.h>
// #include<limits.h>
// #include<iostream>
// #include<algorithm>
// #include<string>
// #include<vector>
// #include<queue>
// using namespace std;
/*
# Author : @RAJ009F
# Topic or Type : GFG/BT
# Problem Statement : check the covered and uncoveed sum in Tree
# Description :
# Complexity :
=======================
#steps:
=----------------
#sample output
----------------------
=======================
*/
class Node
{
Node l;
Node r;
int data;
Node(int data)
{
this.l = this.r = null;
this.data = data;
}
}
class checkCoveredUnCoveredTreeUT
{
Node root;
public int sumTree(Node node)
{
if(node == null)
return 0;
return sumTree(node.l)+node.data+sumTree(node.r);
}
public int uncoveredSumLeft(Node node)
{
if(node == null)
return 0;
if(node.l != null)
return node.data+uncoveredSumLeft(node.l);
else if(node.r != null)
return node.data + uncoveredSumLeft(node.r);
else
return 0;
}
public int uncoveredSumRight(Node node)
{
if(node == null)
return 0;
if(node.r != null)
return node.data+uncoveredSumRight(node.r);
else if(node.l != null)
return node.data + uncoveredSumRight(node.l);
else
return 0;
}
public boolean isTreeCovered(Node node)
{
if(node == null)
return true;
int sum = sumTree(node);
int uncoveredSum = node.data+uncoveredSumLeft(node.l) + uncoveredSumRight(node.r);
System.out.println(sum +" "+uncoveredSum);
return (sum-uncoveredSum == uncoveredSum);
}
public static void main(String args[])
{
checkCoveredUnCoveredTreeUT bt = new checkCoveredUnCoveredTreeUT();
bt.root = new Node(8);
bt.root.l = new Node(3);
bt.root.l.l = new Node(1);
bt.root.l.r = new Node(6);
bt.root.l.r.l = new Node(4);
bt.root.l.r.r = new Node(7);
bt.root.r = new Node(10);
bt.root.r.l = new Node(32);
bt.root.r.r = new Node(14);
bt.root.r.r.l = new Node(13);
System.out.println(bt.isTreeCovered(bt.root));
}
} |
import java.util.Calendar;
public class A3Calendar {
public static void main(String[] args) {
Calendar c=Calendar.getInstance();
int y=c.get(Calendar.YEAR);
int m=c.get(Calendar.MONTH)+1;
int m2=c.get(Calendar.DAY_OF_MONTH);
int m3=c.get(Calendar.WEEK_OF_MONTH);
int d=c.get(Calendar.DAY_OF_YEAR);
System.out.println(y);
System.out.println(m);
System.out.println(m2);
System.out.println(m3);
System.out.println(d);
}
}
|
package com.example.forcatapp.Member;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.forcatapp.Main.MainActivity;
import com.example.forcatapp.R;
import com.example.forcatapp.util.OracleDBUpload;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
static RequestQueue requestQueue;
List<Map<String, Object>> memberInfo;
private EditText etMem_id, etMem_pw;
private Button signup;
private FirebaseAuth mAuth;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private FirebaseAuth.AuthStateListener authStateListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etMem_id = findViewById(R.id.et_memId);
etMem_pw = findViewById(R.id.et_memPw);
//ํ์ด์ด๋ฒ ์ด์ค ๋ก๊ทธ์ธ ๊ฐ์ฒด ์์ฑ
mAuth = FirebaseAuth.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
//์ด์ ๋ก๊ทธ์ธ์ ๋ณด ์ญ์
//์ค๋ผํด ์ธ์
๋ก๊ทธ์์ ์ฒ๋ฆฌ
android.webkit.CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(null);
cookieManager.flush();
// //ํ์ด์ด๋ฒ ์ด์ค ๋ก๊ทธ์์ ์ฒ๋ฆฌ
mAuth.signOut();
//ํ์๊ฐ์
ํด๋ฆญ ์
signup = (Button)findViewById(R.id.loginActivity_buttn_signup);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,SignupActivity.class));
}
});
if (requestQueue == null) {
// requestQueue ์ด๊ธฐํ
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
//๋ก๊ทธ์ธ ๋ฒํผ ํด๋ฆญ ์
Button btn_login = findViewById(R.id.btnLogin);
btn_login.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//์ค๋ผํด ๋ก๊ทธ์ธ ํ ์ธ์
์ฒ๋ฆฌ
String pmem_id = etMem_id.getText().toString();
String pmem_pw = etMem_pw.getText().toString();
OracleDBUpload oracleDBUpload = new OracleDBUpload("loginGetSession", LoginActivity.this);
Map<String, Object> params = new HashMap<String, Object>();
params.put("mem_email", pmem_id);
params.put("mem_pw", pmem_pw);
oracleDBUpload.execute(params);
Log.d(TAG, "onClick: params ===> " + params);
//์ฑ ๋ก๊ทธ์ธ
login(pmem_id, pmem_pw);
}
});
}
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser currentUser) {
if(currentUser != null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
private void login(String pmem_id, String pmem_pw) {
//---------------------------------------------------------------------- firebase ๋ก๊ทธ์ธ ์ฒ๋ฆฌ
mAuth.signInWithEmailAndPassword(pmem_id, pmem_pw)
.addOnCompleteListener(new OnCompleteListener<AuthResult>(){
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
//๋ก๊ทธ์ธ ์คํจ
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
//---------------------------------------------------------------------- firebase ๋ก๊ทธ์ธ ์ฒ๋ฆฌ
}
@Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(authStateListener);
}
} |
package com.metoo.manage.admin.tools;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.FreeApplyLog;
import com.metoo.foundation.domain.FreeClass;
import com.metoo.foundation.domain.Goods;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.service.IFreeApplyLogService;
import com.metoo.foundation.service.IFreeClassService;
import com.metoo.foundation.service.IGoodsService;
import com.metoo.foundation.service.IUserService;
/**
*
* <p>
* Title: FreeTools.java
* </p>
*
* <p>
* Description:0ๅ
่ฏ็จ็ธๅ
ณๅทฅๅ
ท็ฑป
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: ๆฒ้ณ็ฝไนๅ็งๆๆ้ๅ
ฌๅธ www.koala.com
* </p>
*
* @author jinxinzhe
*
* @date 2014-11-11
*
*
* @version koala_b2b2c v2.0 2015็
*/
@Component
public class FreeTools {
@Autowired
private IFreeClassService freeClassService;
@Autowired
private IGoodsService goodsService;
@Autowired
private IUserService userService;
@Autowired
private IFreeApplyLogService freeApplyLogService;
public FreeClass queyFreeClass(String class_id) {
FreeClass fc = this.freeClassService.getObjById(CommUtil
.null2Long(class_id));
return fc;
}
public Goods queryGoods(String goods_id) {
Goods goods = this.goodsService
.getObjById(CommUtil.null2Long(goods_id));
return goods;
}
public List<User> queryUser(String free_id) {
List<User> users = new ArrayList<User>();
Map map = new HashMap();
map.put("free_id", CommUtil.null2Long(free_id));
List<FreeApplyLog> fals = this.freeApplyLogService
.query("select obj from FreeApplyLog obj where obj.freegoods_id=:free_id order by obj.addTime desc",
map, 0, 10);
for (FreeApplyLog fal : fals) {
User user = this.userService.getObjById(CommUtil.null2Long(fal
.getUser_id()));
if (user != null) {
users.add(user);
}
}
return users;
}
public User queryEvaluteUser(String user_id) {
User user = this.userService.getObjById(CommUtil.null2Long(user_id));
return user;
}
}
|
package com.cos.blog.domain.reply.dto;
import lombok.Data;
@Data
public class DeleteReqDto {
private int userId;
private int replyId;
}
|
/**
*๋ฒ ํํ
์คํธ์ ์ด์์์๊ฒ ๋นํด๋์ค
*<p> ์ ๋ชฉ:BetaAdminBean.java</p>
*<p> ์ค๋ช
:์ด์์์๊ฒ ๋น</p>
*<p> Copyright: Copright(c)2004</p>
*<p> Company: VLC</p>
*@author ๋ฐ์คํ
*@version 1.0
*/
package com.ziaan.beta;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import com.ziaan.library.ConfigSet;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.ListSet;
import com.ziaan.library.MailSet;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.library.StringManager;
public class BetaAdminBean {
private ConfigSet config;
private int row;
public BetaAdminBean() {
try {
config = new ConfigSet();
row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // ์ด ๋ชจ๋์ ํ์ด์ง๋น row ์๋ฅผ ์
ํ
ํ๋ค
}
catch( Exception e ) {
e.printStackTrace();
}
}
/**
HyunDai์ด์์ํ๋ฉด ๋ฆฌ์คํธ
@param box receive from the form object and session
@return ArrayList ์ด์์ ๋ฆฌ์คํธ
*/
public ArrayList selectListAdminhyundai(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
DataBox dbox = null;
String v_searchtext = box.getString("p_searchtext");
String v_search = box.getString("p_select");
int v_pageno = box.getInt("p_pageno");
String v_gcode = box.getString("s_grcode");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT DISTINCT a.userid, a.name, get_jikwinm(a.jikwi, a.comp) as jikwinm, a.handphone, a.comptel, ";
sql += "c.gadmin, a.email, a.orga_ename " ;
sql += "FROM tz_member a, tz_manager b, tz_grcodeman c ";
sql += "WHERE a.userid = b.userid ";
sql += "AND a.userid = c.userid and substr(b.comp,1,4) = '0101' ";
sql += " and a.jikwi >= '28'";
sql += "AND ( (substr(c.gadmin,1,2) = 'H1') OR (substr(c.gadmin,1,2) = 'A1') OR (substr(c.gadmin,1,2) = 'A2' ) )" ;
if ( !v_gcode.equals("") && !v_gcode.equals("----") ) {
sql += " and c.grcode = " + SQLString.Format(v_gcode);
}
if ( !v_searchtext.equals("") ) { // ๊ฒ์์ด๊ฐ ์์ผ๋ฉด
// ์ด๋ฆ์ผ๋ก ๊ฒ์ํ ๋
sql += " and a.name like " + StringManager.makeSQL("%" + v_searchtext + "%");
}
sql += " order by jikwinm desc";
ls = connMgr.executeQuery(sql);
ls.setPageSize(row); // ํ์ด์ง๋น row ๊ฐฏ์๋ฅผ ์ธํ
ํ๋ค.
ls.setCurrentPage(v_pageno); // ํ์ฌํ์ด์ง๋ฒํธ๋ฅผ ์ธํ
ํ๋ค.
int total_page_count = ls.getTotalPage(); // ์ ์ฒด ํ์ด์ง ์๋ฅผ ๋ฐํํ๋ค.
int total_row_count = ls.getTotalCount(); // ์ ์ฒด row ์๋ฅผ ๋ฐํํ๋ค.
while ( ls.next() ) {
dbox = ls.getDataBox();
dbox.put("d_dispnum", new Integer(total_row_count - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(total_page_count));
dbox.put("d_rowcount", new Integer(row));
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) {
try {
ls.close();
} catch ( Exception e ) {
}
}
if ( connMgr != null ) {
try {
connMgr.freeConnection();
} catch ( Exception e10 ) {
}
}
}
return list;
}
/**
kia์ด์์ํ๋ฉด ๋ฆฌ์คํธ
@param box receive from the form object and session
@return ArrayList ์ด์์ ๋ฆฌ์คํธ
*/
public ArrayList selectListAdminkia(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
DataBox dbox = null;
String v_searchtext = box.getString("p_searchtext");
String v_search = box.getString("p_select");
int v_pageno = box.getInt("p_pageno");
String v_gcode = box.getString("s_grcode");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = " SELECT DISTINCT a.userid, a.name, get_jikwinm(a.jikwi, a.comp) as jikwinm, a.handphone, a.comptel, ";
sql += " c.gadmin, a.email, a.orga_ename ";
sql += " FROM tz_member a, tz_manager b, tz_grcodeman c ";
sql += " WHERE a.userid = b.userid ";
sql += " AND a.userid = c.userid and substr(b.comp,1,4) = '0102' ";
sql += " and a.jikwi >= '28' ";
sql += " AND ( (substr(c.gadmin,1,2) = 'H1') OR (substr(c.gadmin,1,2) = 'A1') OR (substr(c.gadmin,1,2) = 'A2' ) )";
if ( !v_gcode.equals("") && !v_gcode.equals("----") ) {
sql += " and c.grcode = " + SQLString.Format(v_gcode);
}
if ( !v_searchtext.equals("") ) { // ๊ฒ์์ด๊ฐ ์์ผ๋ฉด
// ์ด๋ฆ์ผ๋ก ๊ฒ์ํ ๋
sql += " and a.name like " + StringManager.makeSQL("%" + v_searchtext + "%");
}
sql += " order by jikwinm desc ";
ls = connMgr.executeQuery(sql);
ls.setPageSize(row); // ํ์ด์ง๋น row ๊ฐฏ์๋ฅผ ์ธํ
ํ๋ค
ls.setCurrentPage(v_pageno); // ํ์ฌํ์ด์ง๋ฒํธ๋ฅผ ์ธํ
ํ๋ค.
int total_page_count = ls.getTotalPage(); // ์ ์ฒด ํ์ด์ง ์๋ฅผ ๋ฐํํ๋ค.
int total_row_count = ls.getTotalCount(); // ์ ์ฒด row ์๋ฅผ ๋ฐํํ๋ค.
while ( ls.next() ) {
dbox = ls.getDataBox();
dbox.put("d_dispnum" , new Integer(total_row_count - ls.getRowNum() + 1) );
dbox.put("d_totalpage" , new Integer(total_page_count) );
dbox.put("d_rowcount" , new Integer(row) );
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) {
try { ls.close(); } catch ( Exception e ) { }
}
if ( connMgr != null ) {
try {
connMgr.freeConnection();
} catch ( Exception e10 ) { }
}
}
return list;
}
/*
์ด์์์๊ฒ DB์ ์
๋ ฅํ ๋ฉ์ผ๋ณด๋ด๊ธฐ
@param box receive from the form object and session
@param v_gubun ๋ฒ ํํ
์คํธ์์คํ
์ ๊ตฌ๋ถ๋ช
@raturn ๋ฉ์ผ๋ฐ์ก์ ์ฑ๊ณตํ๋ฉด true๋ฅผ ๋ฆฌํดํ๋ค
*/
public boolean selectPds(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
String sql = "";
String sql1 = "";
String sql2 = "";
DataBox dbox = null;
boolean isMailed = false;
PreparedStatement pstmt1 = null;
int isOk1 = 0;
String v_toEmail = box.getString("p_toemail");
String v_toCono = box.getString("p_cono");
String v_mailTitle = box.getString("p_title");
String v_mailContent = box.getString("p_content");
String s_userid = box.getSession("userid");
String v_gubun = "04";
MailSet mset = new MailSet(box); // ๋ฉ์ผ ์ธํ
๋ฐ ๋ฐ์ก
try {
connMgr = new DBConnectionManager();
// ---------------------- ๊ฒ์ํ ๋ฒํธ ๊ฐ์ ธ์จ๋ค ----------------------------
sql2 = "select nvl(max(seq), 0) from tz_contact";
ls = connMgr.executeQuery(sql2);
ls.next();
int v_seq = ls.getInt(1) + 1;
ls.close();
// ------------------------------------------------------------------------------------
sql1 = "insert into TZ_CONTACT(seq, addate, queid, quetitle, quecontent, gubun) ";
sql1 += " values (?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, ?) ";
pstmt1 = connMgr.prepareStatement(sql1);
pstmt1.setInt(1,v_seq);
pstmt1.setString(2, s_userid);
pstmt1.setString(3, v_mailTitle);
pstmt1.setString(4, v_mailContent);
pstmt1.setString(5, v_gubun);
isOk1 = pstmt1.executeUpdate();
if ( isOk1 == 1) {
isMailed = mset.sendMail(v_toCono, v_toEmail, v_mailTitle, v_mailContent, "1", "");
}
ls.close();
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) {
try {
ls.close();
} catch ( Exception e ) { }
}
if ( pstmt1 != null ) {
try {
pstmt1.close();
} catch ( Exception e1 ) { }
}
if ( connMgr != null ) {
try {
connMgr.freeConnection();
} catch ( Exception e10 ) { }
}
}
return isMailed;
}
/**
๋ฉ์ผ์ ๊ฒ์ํ๋ค
@param box receive from the form object and session
@return list ์กฐํํ ๋ฉ์ผ์ ๋ณด
*/
public ArrayList selectMail(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
DataBox dbox = null;
String v_touserid = box.getString("p_touserid");
String v_fromuserid = box.getString("p_formuserid");
try {
list = new ArrayList();
connMgr = new DBConnectionManager();
sql += " SELECT Name \n" ;
sql += " , Email \n" ;
sql += " , Orga_Ename \n" ;
sql += " , GET_JIKWINM(Jikwi, Comp) as Jikwinm \n" ;
sql += " , jikmunm \n" ;
sql += " , cono \n" ;
sql += " FROM Tz_Member \n" ;
sql += " WHERE Userid = " + SQLString.Format( v_touserid ) ;
sql += " OR Userid = " + SQLString.Format( v_fromuserid ) ;
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) {
try {
ls.close();
} catch ( Exception e ) { }
}
if ( connMgr != null ) {
try {
connMgr.freeConnection();
} catch ( Exception e10 ) { }
}
}
return list;
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.base;
import java.util.Calendar;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityExistsException;
import javax.persistence.TransactionRequiredException;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import java.util.logging.Level;
import javax.persistence.EntityManager;
public class BaseEntityServicio<E> extends BaseServicio implements AdministracionTablasInterface<E>
{
private Class objEntity;
public BaseEntityServicio(final EntityManager em, final Class claseEntity) {
super(em);
this.objEntity = claseEntity;
}
@Override
public void adicionar(final E pEntity) throws EntityExistsException, EntityServicioExcepcion {
if (pEntity != null) {
try {
this.em.persist((Object)pEntity);
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (TransactionRequiredException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "Noexiste una transacci\u00f3n activa", (Throwable)ex2);
throw new EntityServicioExcepcion((Throwable)ex2);
}
catch (IllegalArgumentException ex3) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex3);
throw new EntityServicioExcepcion(ex3);
}
}
}
@Override
public Collection<E> getTodos() {
final String nombreQueryTodos = this.objEntity.getSimpleName() + ".todos";
Collection<E> regs = new ArrayList<E>();
try {
this.em.clear();
regs = (Collection<E>)this.em.createNamedQuery(nombreQueryTodos).setHint("javax.persistence.cache.storeMode", (Object)"REFRESH").getResultList();
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
}
catch (IllegalArgumentException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex2);
}
finally {
if (regs.isEmpty()) {
BaseEntityServicio.configApp.loggerApp.finest("No se encontraron datos con la b\u00fasqueda " + nombreQueryTodos);
}
}
return regs;
}
@Override
public Collection<E> getTodos(final Integer pagina, final Integer regsPorPagina) throws EntityServicioExcepcion {
return this.consultarPorQuery(pagina, regsPorPagina, this.objEntity.getSimpleName() + ".todos");
}
@Override
public E buscar(final Class objClase, final Object llave) throws EntityServicioExcepcion {
E entity = null;
try {
entity = (E)this.em.find(objClase, llave);
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex2);
throw new EntityServicioExcepcion(ex2);
}
return entity;
}
@Override
public E buscar(final Object llave) throws EntityServicioExcepcion {
return this.buscar(this.objEntity, llave);
}
@Override
public Collection<E> consultarPorQuery(Integer pagina, Integer regsPorPagina, final String nombreQuery) throws EntityServicioExcepcion {
Collection<E> regs = null;
Query query = null;
regsPorPagina = ((regsPorPagina == null) ? 1 : regsPorPagina);
pagina = ((pagina == null) ? 1 : pagina);
Integer regInicial = pagina * regsPorPagina;
--regInicial;
try {
query = this.em.createNamedQuery(nombreQuery);
if (regInicial > 0) {
query.setFirstResult((int)regInicial);
}
if (regsPorPagina > 0) {
query.setMaxResults((int)regsPorPagina);
}
regs = (Collection<E>)query.getResultList();
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
return regs;
}
@Override
public void borrar(final E entity) throws EntityServicioExcepcion {
try {
this.em.remove((Object)entity);
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (TransactionRequiredException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "Na existe una transacci\u00f3n activa", (Throwable)ex2);
throw new EntityServicioExcepcion((Throwable)ex2);
}
catch (IllegalArgumentException ex3) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex3);
throw new EntityServicioExcepcion(ex3);
}
catch (Exception ex4) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No se puede borrar el entity " + ex4.getMessage(), ex4);
throw new EntityServicioExcepcion(ex4);
}
}
@Override
public E actualizar(final E objeto) throws EntityServicioExcepcion {
try {
return (E)this.em.merge((Object)objeto);
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (TransactionRequiredException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "Na existe una transacci\u00f3n activa", (Throwable)ex2);
throw new EntityServicioExcepcion((Throwable)ex2);
}
catch (IllegalArgumentException ex3) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex3);
throw new EntityServicioExcepcion(ex3);
}
}
@Override
public void borrarPorLlave(final Object llave) throws EntityServicioExcepcion {
final E entity = this.buscar(llave);
this.borrar(entity);
}
@Override
public void actualizarPersistencia() throws EntityServicioExcepcion {
try {
this.em.flush();
}
catch (IllegalStateException ex) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No hay acceso al manejador de entitys ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (TransactionRequiredException ex2) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "Na existe una transacci\u00f3n activa", (Throwable)ex2);
throw new EntityServicioExcepcion((Throwable)ex2);
}
catch (IllegalArgumentException ex3) {
BaseEntityServicio.configApp.loggerApp.log(Level.SEVERE, "No es un entity", ex3);
throw new EntityServicioExcepcion(ex3);
}
}
public void ejecutarSpDesdeJob(final String nombreSP) {
BaseEntityServicio.configApp.loggerApp.log(Level.INFO, "Entra Invocando SP " + nombreSP + " a las: " + Calendar.getInstance().getTime());
final Query query = this.em.createNativeQuery(" declare l_jobid number := null; begin dbms_job.submit ( job => l_jobid, what => 'BEGIN " + nombreSP + " END;', next_date => sysdate, interval => null ); commit; end;");
BaseEntityServicio.configApp.loggerApp.log(Level.INFO, "Query: " + query.toString());
query.executeUpdate();
BaseEntityServicio.configApp.loggerApp.log(Level.INFO, "Sale de invocacion SP " + nombreSP + " a las: " + Calendar.getInstance().getTime());
}
}
|
package com.barnettwong.coolview.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.barnettwong.coolview.R;
import com.barnettwong.view_library.view.likebutton.LikeButton;
import com.barnettwong.view_library.view.likebutton.OnLikeListener;
import com.blankj.utilcode.util.ToastUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by wang on 2019/1/18 14:43
*/
public class LikeButtonActivity extends BaseActivity implements OnLikeListener, View.OnClickListener{
@BindView(R.id.heart_button)
LikeButton heartButton;
@BindView(R.id.thumb_button)
LikeButton thumbButton;
@BindView(R.id.btn_text_likebutton)
Button btnTextLikebutton;
// ็นๅป็ๆฌกๆฐ
private long clickcounts=0;
@Override
public int getLayoutId() {
return R.layout.activity_likebutton;
}
@Override
public void initView() {
heartButton.setOnLikeListener(this);
thumbButton.setOnLikeListener(this);
btnTextLikebutton.setOnClickListener(this);
}
@Override
public void liked(LikeButton likeButton)
{
int btn_id=likeButton.getId();
switch (btn_id){
case R.id.heart_button:
ToastUtils.showShort("ๅ
ณๆณจ");
break;
case R.id.thumb_button:
ToastUtils.showShort("็น่ต");
break;
}
}
@Override
public void unLiked(LikeButton likeButton) {
int btn_id=likeButton.getId();
switch (btn_id){
case R.id.heart_button:
ToastUtils.showShort("ๅๆถๅ
ณๆณจ");
break;
case R.id.thumb_button:
ToastUtils.showShort("ๅๆถ็น่ต");
break;
}
}
@Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btn_text_likebutton:
clickcounts++;
if (clickcounts%2==0){
ToastUtils.showShort("ๆฎ้ๆ้ฎ-- ๅๆฌข");
btnTextLikebutton.setText(clickcounts+" ๅๆฌข");
}else {
ToastUtils.showShort("ๆฎ้ๆ้ฎ-- ไธๅๆฌข");
btnTextLikebutton.setText(clickcounts+" ไธๅๆฌข");
}
break;
}
}
}
|
package pages;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Scrutinize extends AbstractPage {
public Scrutinize() {
PageFactory.initElements(getEventDriver(), this);
}
@FindBy(how=How.XPATH,using="//button[@id='Scruntize']")
private WebElement eleScrubutton;
public Scrutinize clickScrubutton() {
click(eleScrubutton);
return this;
}
@FindBy(how=How.XPATH,using="//button[@title='Click here to view filter...!']")
public WebElement eleSCruFilter;
public Scrutinize clickScruFilter() {
pause(4);
click(eleSCruFilter);
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='SelectedJobCode']")
public WebElement eleScrujobFilter;
public Scrutinize clickScruJobFilter() {
pause(4);
click(eleScrujobFilter);
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='Selectedclaimno']")
public WebElement eleScruClaimFilter;
public Scrutinize clickScruClaimFilter() {
pause(4);
click(eleScruClaimFilter);
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='strClaimStatus']/preceding-sibling::span/span[@class='k-select']/span")
public WebElement eleScruClaimStatusbutton;
public Scrutinize clickScruStatusbutton(){
pause(2);
JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleScruClaimStatusbutton);
return this;
}
public Scrutinize selectUsingTexteleAckClaimStatus(String ScruClaimStatus){
pause(2);
selectUsingText(locateElement("xpath","//li[text()='"+ScruClaimStatus+"']"), ScruClaimStatus);
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='SelectedPolicyNo']")
public WebElement eleSCruPolicyNo;
public Scrutinize typeAndEnterPolicyNo(String dataScruPolicyNo){
pause(1);
typeAndChoose(eleSCruPolicyNo, dataScruPolicyNo);
return this;
}
@FindBy(how=How.XPATH,using="//button[text()='Get List']")
private WebElement eleScruGetList;
public Scrutinize clickScruGetList() {
click(eleScruGetList);
return this;
}
@FindBy(how=How.XPATH,using="//button[text()='Close']")
private WebElement eleScruClose;
public Scrutinize clickScruClose() {
click(eleScruClose);
return this;
}
@FindBy(how=How.XPATH,using="(//button[text()='ร'])[2]")
private WebElement elexClosescru;
public Scrutinize clickxCloseScru() {
click(elexClosescru);
return this;
}
@FindBy(how=How.XPATH,using="(//a[text()='Claim Request No.']/following::u)[1]")
private WebElement eleGridscrufirstvalue;
public Scrutinize clickGridScrufirstvalue() {
//click(eleGridEdit);
pause(5);
mouseOverOnElement(eleGridscrufirstvalue);
/*JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleGridEdit); */
return this;
}
@FindBy(how=How.XPATH,using="(//input[@class='checkboxR'])[1]")
private WebElement eleSendBack;
public Scrutinize clicSendBack() {
click(eleSendBack);
return this;
}
@FindBy(how=How.XPATH,using="(//a[text()='Scrutinize']/following::u)[2]")
private WebElement eleGridfirstScru;
public Scrutinize clickGridfirstScru() {
pause(3);
//click(eleGridEdit);
WebDriverWait wait=new WebDriverWait(getEventDriver(), 30);
wait.until(ExpectedConditions.visibilityOf(eleGridfirstScru));
mouseOverOnElement(eleGridfirstScru);
/*JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleGridEdit); */
return this;
}
@FindBy(how=How.XPATH,using="(//a[text()='Claim Cancel']/following::u)[3]")
private WebElement eleGridCancel;
public Scrutinize clickGridfristCancelButton() {
//click(eleGridEdit);
pause(3);
mouseOverOnElement(eleGridCancel);
/*JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleGridEdit); */
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='strFCremarks']")
public WebElement eleScruRemarks;
public Scrutinize typeScruRemarks(String dataScruRemarks){
pause(1);
type(eleScruRemarks, dataScruRemarks);
return this;
}
@FindBy(how=How.XPATH,using="//span[text()='arrow-e']")
private WebElement eleScruPaginationRight;
public Scrutinize clickACkPaginationRight() {
click(eleScruPaginationRight);
return this;
}
@FindBy(how=How.XPATH,using="//span[text()='seek-e']")
private WebElement eleScruPaginationRightlast;
public Scrutinize clickScruPaginationRightlast() {
click(eleScruPaginationRightlast);
return this;
}
@FindBy(how=How.XPATH,using="//span[text()='arrow-w']")
private WebElement eleScruPaginationLeft;
public Scrutinize clickACkPaginationLeft() {
click(eleScruPaginationLeft);
return this;
}
@FindBy(how=How.XPATH,using="//span[text()='seek-w']")
private WebElement eleScruPaginationLeftlast;
public Scrutinize clickScruPaginationLeftlast() {
click(eleScruPaginationLeftlast);
return this;
}
@FindBy(how=How.XPATH,using="(//span[text()='select'])[2]")
public WebElement eleScruPaginationItemPerPage;
public Scrutinize clickScruPaginationItemPerPage(){
pause(2);
JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleScruPaginationItemPerPage);
return this;
}
public Scrutinize selectUsingTexteleAckItemperpage(String AckItemPerPage){
pause(2);
selectUsingText(locateElement("xpath","//li[text()='"+AckItemPerPage+"']"), AckItemPerPage);
return this;
}
@FindBy(how=How.XPATH,using="//button[@id='btnSubmit']")
private WebElement eleScruGridSubmit;
public Scrutinize clickScruGridSubmit() {
click(eleScruGridSubmit);
return this;
}
@FindBy(how=How.XPATH,using="//button[text()='OK'] ")
private WebElement eledialogMsgClose;
public Scrutinize closeDialogMsg()
{
click(eledialogMsgClose);
return this;
}
@FindBy(how=How.XPATH,using="//div[@class='bootbox-body']/div")
private WebElement eledialogMsg;
public Scrutinize getdialogMsg()
{
pause(5);
//dialogMessage = getText(eledialogMsg);
System.out.println("Dialog message:"+ getText(eledialogMsg));
reportStep("The element"+ eledialogMsg +"is not visible", "WARNING");
return this;
}
@FindBy(how=How.XPATH,using="//div[text()='Scrutinize Remarks']/following::textarea")
public WebElement eleScruRemark;
public Scrutinize typeScrutinizeRemarks(String dataACKPolicyNo){
pause(4);
//click(eleACKPolicyNo);
/*JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("arguments[0].click();",eleACKPolicyNo); */
//mouseOverOnElement(eleScruRemark);
pause(1);
try {
getEventDriver().executeScript("eleScruRemark.scroll();","");
eleScruRemark.click();
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Remark entered");
type(eleScruRemark, dataACKPolicyNo);
}
//type(eleScruRemark, dataACKPolicyNo);
return this;
}
@FindBy(how=How.XPATH,using="//button[text()[contains(.,'Submit')]]")
public WebElement eleSubmit;
public Scrutinize clickSubmit(){
click(eleSubmit);
return this;
}
@FindBy(how=How.XPATH,using="//button[@title='Click here to view filter...!']")
public WebElement eleCreateFilter;
public Scrutinize clickCreateClaimFilter() {
pause(4);
click(eleCreateFilter);
return this;
}
@FindBy(how=How.XPATH,using="//input[@id='Selectedclaimno']")
public WebElement eleEditCreateClaimFilter;
public Scrutinize typeCreateClaim() {
pause(4);
System.out.println(ClaimNum);
typeAndChoose(eleEditCreateClaimFilter,ClaimNum);
return this;
}
@FindBy(how=How.XPATH,using="//button[text()='Get List']")
private WebElement eleEditGetList;
public Scrutinize clickCreateGetList() {
click(eleEditGetList);
return this;
}
}
|
package org.hadoop.praveen;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Mapper;
public class MultipleOutputMapper extends Mapper<LongWritable,Text,Text,Text>{
private Text empId = new Text();
private Text empData = new Text();
@Override
protected void map(LongWritable key,Text value,Context con) throws IOException, java.lang.InterruptedException{
String line = value.toString(); // DJPX255251,Arthur,HR,6397,2016
/* Split csv string */
String[] words = line.split(",");
empId.set(words[0]); // empId = DJPX255251
empData.set(words[1] + "," + words[2] + "," + words[3]);
con.write(empId, empData);
//con.write(new Text(words[0]), new Text(words[1] + "," + words[2] + "," + words[3]));
}
}
|
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import entidades.Tarefa;
public class TarefaDAO {
private Connection con = Conexao.getConnection();
public void cadastrar(Tarefa tarefa){
String sql = "INSERT INTO TAREFA (nome, disciplina, situacao, finalizacao, mensagem, auth, idusuario) values (?,?,?,?,?,?,?)";
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, tarefa.getNome());
preparador.setString(2, tarefa.getDisciplina());
preparador.setString(3, tarefa.getFinalizado());
preparador.setString(4, tarefa.getDataFinalizacao());
preparador.setString(5, tarefa.getDescricao());
preparador.setString(6, tarefa.getAuth());
preparador.setInt(7, tarefa.getIdusuario());
preparador.execute();
preparador.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void alterar (Tarefa tarefa){
String sql = "UPDATE TAREFA SET nome=?, disciplina=?, situacao=?, finalizacao=?, mensagem=? where id=?";
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, tarefa.getNome());
preparador.setString(2, tarefa.getDisciplina());
preparador.setString(3, tarefa.getFinalizado());
preparador.setString(4, tarefa.getDataFinalizacao());
preparador.setString(5, tarefa.getDescricao());
preparador.setInt(6, tarefa.getId());
preparador.execute();
preparador.close();
System.out.println("Tarefa Alterado com sucesso!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void excluir (Tarefa tarefa){
String sql = "DELETE FROM TAREFA where id=?";
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, tarefa.getId());
preparador.execute();
preparador.close();
System.out.println("Tarefa Excluido com sucesso!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Tarefa>BuscarTodos(Integer idusu){
String sql = "SELECT *FROM TAREFA where idusuario=?";
List<Tarefa> lista = new ArrayList<Tarefa>();
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, idusu);
ResultSet resultado = preparador.executeQuery();
while(resultado.next()){
Tarefa tarefa = new Tarefa();
tarefa.setId(resultado.getInt("id"));
tarefa.setNome(resultado.getString("nome"));
tarefa.setDisciplina(resultado.getString("disciplina"));
tarefa.setFinalizado(resultado.getString("situacao"));
tarefa.setDataFinalizacao(resultado.getString("finalizacao"));
tarefa.setDescricao(resultado.getString("mensagem"));
lista.add(tarefa);
}
} catch (SQLException e) {
e.printStackTrace();
}
return lista;
}
public Tarefa BuscarPorId(Integer id){
String sql = "SELECT *FROM TAREFA Where id=?";
Tarefa tarefa = null;
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setInt(1, id);
ResultSet resultado = preparador.executeQuery();
if (resultado.next()){
tarefa = new Tarefa();
tarefa.setId(resultado.getInt("id"));
tarefa.setNome(resultado.getString("nome"));
tarefa.setDisciplina(resultado.getString("disciplina"));
tarefa.setFinalizado(resultado.getString("situacao"));
tarefa.setDataFinalizacao(resultado.getString("finalizacao"));
tarefa.setDescricao(resultado.getString("mensagem"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tarefa;
}
public void salvar(Tarefa tarefa){
if(tarefa.getId()!=null && tarefa.getId()!=0){
alterar(tarefa);
}
else{
cadastrar(tarefa);
}
}
public List<Tarefa> BuscarPorNome(String nome) {
String sql = "SELECT * FROM TAREFA where nome LIKE '?'";
List<Tarefa> lista = new ArrayList<Tarefa>();
try {
PreparedStatement preparador = con.prepareStatement(sql);
preparador.setString(1, nome);
ResultSet resultado = preparador.executeQuery();
while(resultado.next()){
Tarefa tarefa = new Tarefa();
tarefa.setId(resultado.getInt("id"));
tarefa.setNome(resultado.getString("nome"));
tarefa.setDisciplina(resultado.getString("disciplina"));
tarefa.setFinalizado(resultado.getString("situacao"));
tarefa.setDataFinalizacao(resultado.getString("finalizacao"));
tarefa.setDescricao(resultado.getString("mensagem"));
lista.add(tarefa);
}
} catch (SQLException e) {
e.printStackTrace();
}
return lista;
}
} |
package com.KingIsDdServer;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
public class Main {
public static Boolean ExitGame = false;
public static void main(String[] args) throws IOException, InterruptedException {
String readFile = "/tmp/From";
String writeFile = "/tmp/To";
for (int i = 1 ; i <=3 ;i ++) {
String playerName = "P" + i;
String readPath = readFile + playerName;
String writePath = writeFile + playerName;
File readFileName = new File(readPath);
readFileName.deleteOnExit();
File writeFileName = new File(writePath);
writeFileName.deleteOnExit();
writeFileName.setReadable(true);
writeFileName.setWritable(true);
readFileName.setReadable(true);
readFileName.setWritable(true);
readFileName.setExecutable(true);
writeFileName.setExecutable(true);
Files.newOutputStream(readFileName.toPath(), CREATE_NEW);
Files.newOutputStream(writeFileName.toPath(), CREATE_NEW);
}
System.out.println("fisrt");
GameProcessing.initializeFile(writeFile);
System.out.println("second");
GameProcessing.distributeFoll(writeFile);
System.out.println("third");
GameProcessing.distributeReg(writeFile);
// System.out.println("in");
Utility.readAllFile(ExitGame , readFile, writeFile);
}
}
|
/*
* 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.transaction;
import java.util.Collection;
/**
* Common configuration interface for transaction manager implementations.
* Provides registration facilities for {@link TransactionExecutionListener}.
*
* @author Juergen Hoeller
* @since 6.1
* @see PlatformTransactionManager
* @see ReactiveTransactionManager
*/
public interface ConfigurableTransactionManager extends TransactionManager {
/**
* Set the transaction execution listeners for begin/commit/rollback callbacks
* from this transaction manager.
* @see #addListener
*/
void setTransactionExecutionListeners(Collection<TransactionExecutionListener> listeners);
/**
* Return the registered transaction execution listeners for this transaction manager.
* @see #setTransactionExecutionListeners
*/
Collection<TransactionExecutionListener> getTransactionExecutionListeners();
/**
* Conveniently register the given listener for begin/commit/rollback callbacks
* from this transaction manager.
* @see #getTransactionExecutionListeners()
*/
default void addListener(TransactionExecutionListener listener) {
getTransactionExecutionListeners().add(listener);
}
}
|
package ciphers;
import interfaces.Cipherable;
public abstract class Rotor implements Cipherable {
/* input and output alphabets */
char[] in; //Input alphabet
char[] out; //Output alphabet
int alphabetLength; //Length of alphabets
int position; //Current position of rotor (between 0 and alphabetLength - 1)s
int period; //Number of encipherments before the rotor turns.
//1 = turn each letter, 26 = turn every 26 letters
/* Constructors */
public Rotor(char[] in, char[] out) {
this.in = in;
this.out = out;
this.period = 1;
if (in.length != out.length)
System.out.println("Alphabets must be the same length");
else
this.alphabetLength = in.length;
this.position = 0;
}
/* Getters */
public char[] getIn() {
return in;
}
public char[] getOut() {
return out;
}
public int getPeriod() {
return period;
}
public int getPosition() {
return position;
}
/* Setters */
public void setPeriod(int period) {
this.period = period;
}
public void setPosition(int position) {
this.position = position;
}
/* Methods */
/* Move the rotor 1 position forward */
public void turn() {
position++;
}
public char[][] getAlphabetTable() {
char [][] alphabetTable = new char[alphabetLength][alphabetLength];
int startingPosition = position;
for (int i = 0; i < alphabetLength; i++) {
for (int j = 0; j < alphabetLength; j++) {
alphabetTable[j][i] = encipherChar(in[i]);
turn();
}
setPosition(startingPosition);
}
return alphabetTable;
}
/* Returns the location of a character within a given alphabet */
protected int getIndex(char c, char[] alphabet) {
for (int i = 0; i < alphabet.length; i++)
if (Character.toUpperCase(alphabet[i]) == Character.toUpperCase(c))
return i;
return -1;
}
protected final class Direction {
protected static final int UP = 1;
protected static final int DOWN = -1;
}
}
|
package com.example.demo;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
@SpringBootApplication
@Controller
public class Demo9Application {
public static void main(String[] args) {
SpringApplication.run(Demo9Application.class, args);
}
//็ฌฌไธ็งๅฝ้
ๅ
@Value(value = "${spring.messages.basename}")
private String basename;
@Bean(name = "messageSource")
public ResourceBundleMessageSource getMessageResource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(basename);
return messageSource;
}
//็ฌฌไธ็งๅฝ้
ๅ
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
//่ฎพ็ฝฎ้ป่ฎคๅบๅ,
slr.setDefaultLocale(Locale.CHINA);
return slr;
}
@RequestMapping("/changeSessionLanauage")
public String changeSessionLanauage(HttpServletRequest request,String lang){
if("zh".equals(lang)){
//ไปฃ็ ไธญๅณๅฏ้่ฟไปฅไธๆนๆณ่ฟ่ก่ฏญ่จ่ฎพ็ฝฎ
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("zh","CN"));
}else if("en".equals(lang)){
//ไปฃ็ ไธญๅณๅฏ้่ฟไปฅไธๆนๆณ่ฟ่ก่ฏญ่จ่ฎพ็ฝฎ
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("en","US"));
}
return"redirect:getList";
}
}
|
public class Driver{
public static void main(String[] args){
Frame x = new Frame();
System.out.println(x.frame(5,4));
}
} |
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository repo;
public void processOAuthPostLogin(String username) {
User existUser = repo.getUserByUsername(username);
if (existUser == null) {
User newUser = new User();
newUser.setUsername(username);
// newUser.setProvider(Provider.GOOGLE);
newUser.setEnabled(true);
repo.save(newUser);
}
}
}
|
package com.example.rihaf.diabetesdietexpert;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class dietplanActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editText,bbtxt,usiatxt ;
TextView imttxt,kategoritxt,idtextview;
Button button1;
String id, id2, text, textBB, textIMT, textKATEGORI, textUSIA, selectedtext, selectedtextB;
//MAIN BUTTON REKOMENDASI DIET//
//VARIABEL RADIO GROUP UNTUK SELEKSI JENIS KELAMIN//
private static RadioGroup radio_jk;
private static RadioButton radio_b;
//VARIABEL RADIO GROUP UNTUK SELEKSI AKTIVITAS//
private static RadioGroup radio_aktv;
private static RadioButton radio_b_aktv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dietplan);
myDb = new DatabaseHelper(this);
onClickListener(); //OnClick Function of: HITUNG IMT//
}
//****
//****
//****
//****
//****
//****************************************AWAL---FUNGSI PADA BUTTON "HITUNG IMT"***************************************************//
public void IMTonButtonClick(View v) {
//ASSIGN VARIABELS FOR EACH INPUT AND OUTPUT//
EditText e1 = (EditText) findViewById(R.id.tb);
EditText e2 = (EditText) findViewById(R.id.bb);
TextView t1 = (TextView) findViewById(R.id.imt);
TextView t2 = (TextView) findViewById(R.id.kategoribb);
TextView tb_txt = (TextView) findViewById(R.id.tb_txt);
TextView bb_txt = (TextView) findViewById(R.id.bb_txt);
//JIKA INPUT TB DAB B KOSONG MAKA AKAN MUNCUL POP-UP MESSAGE//
if ((e1.getText().toString().length() == 0 && e2.getText().toString().length() == 0) || (e1.getText().toString().length() == 0 || e2.getText().toString().length() == 0)) {
Toast.makeText(dietplanActivity.this, "Silahkan masukkan Tinggi Badan dan Berat Badan anda terlebih dahulu", Toast.LENGTH_LONG).show();
t1.setText(" ");
t2.setText(" ");
}
else { //JIKA INPUT TB DAB B TERISI MAKA AKAN DILAKUKAN PROSES PERHITUNGAN IMT//
double num1 = Double.parseDouble(e1.getText().toString());
double num2 = Double.parseDouble(e2.getText().toString());
tb_txt.setText(Double.toString(num1));
bb_txt.setText(Double.toString(num2));
double sum = num2 / (num1 * num1);
t1.setText(Double.toString(sum));
if (sum <= 1) {
Toast.makeText(dietplanActivity.this, "Masukkan Tinggi Badan dalam satuan meter", Toast.LENGTH_LONG).show();
t1.setText(" ");
t2.setText(" ");
} else {
if (sum < 19.8)
t2.setText("BB Kurang");
if (sum >= 19.8 && sum <= 26)
t2.setText("BB Normal");
if (sum > 26)
t2.setText("BB Lebih");
}
}
}
//****************************************AKHIR --- FUNGSI PADA BUTTON "HITUNG IMT"***************************************************//
//****
//****
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_activity_save, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cancel_id:
Toast.makeText(dietplanActivity.this, "Membatalkan", Toast.LENGTH_LONG).show();
startActivity(new Intent (dietplanActivity.this, FirstSetupActivity.class));
return super.onOptionsItemSelected(item);
case R.id.save_id:
EditText editText = (EditText)findViewById(R.id.tb); //1
EditText bbtxt = (EditText)findViewById(R.id.bb); //2
TextView imttxt = (TextView) findViewById(R.id.imt); //3
TextView kategoritxt = (TextView) findViewById(R.id.kategoribb); //4
EditText usiatxt = (EditText)findViewById(R.id.usia); //5
String text = editText.getText().toString();
String textBB = bbtxt.getText().toString();
String textIMT = imttxt.getText().toString();
// double textIMT = Double.parseDouble(imttxt.getText().toString());
String textKATEGORI = kategoritxt.getText().toString();
String textUSIA = usiatxt.getText().toString();
//RADIO GROUP JENIS KELAMIN//
RadioGroup radioGroupA = (RadioGroup) findViewById(R.id.RadioGroupJK); //6
int radioButtonID = radioGroupA.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) radioGroupA.findViewById(radioButtonID);
String selectedtext = (String) radioButton.getText();
//RADIO GROUP AKTV//
RadioGroup radioGroupB = (RadioGroup) findViewById(R.id.radioGroupAKTV); //7
int radioButtonID2 = radioGroupB.getCheckedRadioButtonId();
RadioButton radioButtonB = (RadioButton) radioGroupB.findViewById(radioButtonID2);
String selectedtextB = (String) radioButtonB.getText();
TextView discIMT = (TextView) findViewById(R.id.hideimt);
TextView discUSIA = (TextView) findViewById(R.id.hideusia);
TextView discJK = (TextView) findViewById(R.id.hidejk);
TextView discAKTV = (TextView) findViewById(R.id.hideaktv);
discIMT.setText(textIMT.toString());
discUSIA.setText(textUSIA.toString());
discJK.setText(selectedtext.toString());
discAKTV.setText(selectedtextB.toString());
String SdiscIMT = discIMT.getText().toString();
String SdiscUSIA = discUSIA.getText().toString();
String SdiscJK = discJK.getText().toString();
String SdiscAKTV = discAKTV.getText().toString();
if (SdiscIMT.length() < 4 ) {
Toast.makeText(dietplanActivity.this, "Hitung IMT anda terlebih dahulu", Toast.LENGTH_LONG).show();
}
else
if (SdiscUSIA.equals("") || SdiscJK.equals("0") || SdiscAKTV.equals("0")) {
Toast.makeText(dietplanActivity.this, "Data anda belum lengkap. Lengkapi data anda terlebih dahulu", Toast.LENGTH_LONG).show();
}
else {
//---------------------AWAL : INSERT DATA INPUT TO DATABASE SQLite--------------------------------------------//
boolean isInserted = myDb.insertData(text,textBB,textIMT,textKATEGORI,textUSIA,selectedtext,selectedtextB);
if(isInserted =true)
Toast.makeText(dietplanActivity.this,"DATA TELAH DISIMPAN", Toast.LENGTH_LONG).show();
else
Toast.makeText(dietplanActivity.this,"DATA GAGAL DISIMPAN", Toast.LENGTH_LONG).show();
//---------------------AKHIR : INSERT DATA INPUT TO DATABASE SQLite--------------------------------------------//
startActivity(new Intent(dietplanActivity.this, DataListActivity.class));
}
default:
return super.onOptionsItemSelected(item);
}
}
//****
//****
//****
//****
//****
//****
//*****************************************AWAL DARI ONCLICKLISTENER RADIO BUTTON***********************************************//
public void onClickListener(){
//*************************************RADIO BUTTON UNTUK MEMILIH JENIS KELAMIN*************************************************//
radio_jk=(RadioGroup)findViewById(R.id.RadioGroupJK);
radio_jk.setOnClickListener(
new View.OnClickListener()
{
@Override
public void onClick (View v){
int selected_id=radio_jk.getCheckedRadioButtonId();
radio_b=(RadioButton)findViewById(selected_id);
}
});
//*****************************************RADIO BUTTON UNTUK MEMILIH AKTIVITAS***********************************************//
radio_aktv=(RadioGroup)findViewById(R.id.radioGroupAKTV);
radio_aktv.setOnClickListener(
new View.OnClickListener()
{
@Override
public void onClick (View v){
int selected_id=radio_aktv.getCheckedRadioButtonId();
radio_b_aktv=(RadioButton)findViewById(selected_id);
}
});
}
//*****************************************AKHIR DARI ONCLICKLISTENER RADIO BUTTON***********************************************//
}
|
package com.graphbuilder.curve;
/**
Curves that extend the ParametricCurve class are continuous and can use the
BinaryCurveApproximationAlgorithm class to generate a sequence of points that
approximate the curve. Note: Approximate means a finite set of points that
are <i>on</i> the curve, <u>not</u> close to the curve.
@see com.graphbuilder.curve.BinaryCurveApproximationAlgorithm
@see com.graphbuilder.curve.Curve
*/
public abstract class ParametricCurve extends Curve {
public ParametricCurve(ControlPath cp, GroupIterator gp) {
super(cp, gp);
}
/**
The eval method evaluates a point on a curve given a parametric value "t". The parametric
value "t" is stored in the last index location of the specified double array. <i>This value
should not be changed</i>. The dimension of the point to evaluate is p.length - 1. The result
of the evaluation is placed in index locations 0 .. p.length - 2 (inclusive).
The eval method should remain protected except for those curves that do no need any
preparation to be done in the appendTo method.
*/
protected abstract void eval(double[] p);
/**
The sample limit specifies how many additional subdivisions are done to ensure that there
are no missed pieces of the curve. The sample limit must be >= 0.
*/
public abstract int getSampleLimit();
} |
public class AlreadySorted {
public static void main(String[] args) {
Array arr = new Array(10000);
arr.randomInit(10000);
arr.sort();
Array arr1 = new Array(arr);
Array arr2 = new Array(arr);
Array arr3 = new Array(arr);
long startTime1 = TimeUtils.now();
arr1.bubbleSort();
long endTime1 = TimeUtils.now();
System.out.println("Time of bubble sort: " + (endTime1 - startTime1) + "ms");
long startTime2 = TimeUtils.now();
arr2.selectionSort();
long endTime2 = TimeUtils.now();
System.out.println("Time of selection sort: " + (endTime2 - startTime2) + "ms");
long startTime3 = TimeUtils.now();
arr3.insertionSort();
long endTime3 = TimeUtils.now();
System.out.println("Time of insertion sort: " + (endTime3 - startTime3) + "ms");
}
}
|
package com.niit.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Length;
@Table(name="Connect_User", schema="ANGULARDB")
@Entity
public class Connect implements Serializable
{ @Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int userid;
@Column(unique = true)
@Pattern(regexp = ".+@.+\\..+", message = "Wrong email!")
private String email;
@Size(min = 1, max = 10, message = "Your name should be between 1 to 10 characters.")
private String username;
@NotNull(message = "Please enter a password")
@Length(min = 4, max = 10, message = "Password should be between 4 to 10 charactes")
private String password;
@Size(min = 10, message = "You cannot entered lessthan 10 digits.")
private String contactno;
private String role;
private boolean isactive;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getContactno() {
return contactno;
}
public void setContactno(String contactno) {
this.contactno = contactno;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isIsactive() {
return isactive;
}
public void setIsactive(boolean isactive) {
this.isactive = isactive;
}
}
|
package com.engin.activity;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import com.engin.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhaoningqiang on 16/6/18.
*/
public class MainActivity extends BaseActivity {
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 127;
private static final String TAG = "permission";
@Override
public int getLayout() {
return R.layout.activity_main;
}
@Override
public void initView() {
}
private boolean requestPermissions(Object obj, int requestCode, String... permissions) {
//checkๆฒกๆๆๆ็ๆ้
List<String> denyPermissions = new ArrayList<String>();
Context context = obj instanceof Activity ? (Context) obj : ((Fragment) obj).getActivity();
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
{
denyPermissions.add(permission);
}
}
if (denyPermissions.size() > 0){
if (obj instanceof Activity){
ActivityCompat.requestPermissions((Activity)obj,denyPermissions.toArray(new String[denyPermissions.size()]),requestCode);
}else if (obj instanceof Fragment){
((Fragment)obj).requestPermissions(denyPermissions.toArray(new String[denyPermissions.size()]),requestCode);
}else{
throw new RuntimeException("argument"+obj+" is not a fragment or activity");
}
return false;
}else{
return true;
}
}
public boolean isAllPermissionGrant(int[] grantResults){
if (grantResults.length > 0){
for (int grantResult : grantResults){
if (grantResult != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}else {
return false;
}
}
@Override
public void setListener() {
findViewById(R.id.tv_name).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{ Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
//
// // Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
// Manifest.permission.READ_CONTACTS)) {
// Log.d(TAG, "shouldShowRequestPermissionRationale true");
//
// // Show an expanation to the user *asynchronously* -- don't block
// // this thread waiting for the user's response! After the user
// // sees the explanation, try again to request the permission.
//
// } else {
//
// Log.d(TAG, "shouldShowRequestPermissionRationale false");
// // No explanation needed, we can request the permission.
//
// ActivityCompat.requestPermissions(MainActivity.this,
// new String[]{Manifest.permission.READ_CONTACTS},
// MY_PERMISSIONS_REQUEST_READ_CONTACTS);
//
// // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// // app-defined int constant. The callback method gets the
// // result of the request.
// }
//
// }
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult requestCode = " + requestCode+" permissions size = "+permissions.length );
for (String permission : permissions) {
Log.d(TAG, "onRequestPermissionsResult permission = " + permission);
}
for (int grantResult : grantResults) {
Log.d(TAG, "onRequestPermissionsResult permission = " + grantResult);
}
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "onRequestPermissionsResult permission was granted");
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.d(TAG, "onRequestPermissionsResult permission was denied");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
|
package by.herzhot.impl;
import by.herzhot.*;
import by.herzhot.exceptions.DaoException;
import by.herzhot.exceptions.ServiceException;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
/**
* @author Herzhot
* @version 1.0
* 03.08.2016
*/
@Stateless
public class MaterialServiceImpl extends BaseService<Material> implements IMaterialService {
@Inject
private IMaterialDao dao;
@Override
public List<Material> findByCriterion(String criterion, Map<String, Integer> paginationParams) throws ServiceException {
List<Material> materials = null;
try {
materials = dao.findByCriterion(criterion, paginationParams);
} catch (DaoException e) {
throw new ServiceException();
}
return materials;
}
@Override
public Long countByCriterion(String criterion) throws ServiceException {
Long count;
try {
count = dao.countByCriterion(criterion);
} catch (DaoException e) {
throw new ServiceException();
}
return count;
}
@Override
public List<Material> readAll(Map<String, Integer> paginationParams) throws ServiceException {
List<Material> materials;
try {
materials = dao.readAll(paginationParams);
} catch (DaoException e) {
throw new ServiceException();
}
return materials;
}
@Override
protected IDao<Material> getDao() {
return dao;
}
}
|
package com.health.system.domain.dto;
import com.health.system.domain.SysRole;
import com.health.system.domain.SysUser;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* @author zhangqing
* @version V1.0
* @Description: ๅจ่ฟ้็ฎๅๆ่ฟฐ่ฏฅ็ฑป็ไฝ็จ
* @Copyright: Copyright (c) 2018
* @company TODOๅนฟๅทๆ่ไผ็ฟๅพไฟกๆฏๆๆฏๆ้ๅ
ฌๅธ
* @date 17/5/2020 2:30 PM
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class SysRoleDto extends SysRole {
/**
* ็จๆทๆฏๅฆๅญๅจๆญค่ง่ฒๆ ่ฏ ้ป่ฎคไธๅญๅจ
*/
private boolean flag = false;
/**
* ่ๅ็ป
*/
private List<Long> menuIds;
/**
* ้จ้จ็ป๏ผๆฐๆฎๆ้๏ผ
*/
private Long[] deptIds;
private List<SysUser> users;
}
|
/*
* 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.aot;
import org.springframework.aot.AotDetector;
import org.springframework.lang.Nullable;
/**
* Holder for metadata specific to ahead-of-time (AOT) support in the <em>Spring
* TestContext Framework</em>.
*
* <p>AOT test attributes are supported in two modes of operation: build-time
* and run-time. At build time, test components can {@linkplain #setAttribute contribute}
* attributes during the AOT processing phase. At run time, test components can
* {@linkplain #getString(String) retrieve} attributes that were contributed at
* build time. If {@link AotDetector#useGeneratedArtifacts()} returns {@code true},
* run-time mode applies.
*
* <p>For example, if a test component computes something at build time that
* cannot be computed at run time, the result of the build-time computation can
* be stored as an AOT attribute and retrieved at run time without repeating the
* computation.
*
* <p>An {@link AotContextLoader} would typically contribute an attribute in
* {@link AotContextLoader#loadContextForAotProcessing loadContextForAotProcessing()};
* whereas, an {@link AotTestExecutionListener} would typically contribute an attribute
* in {@link AotTestExecutionListener#processAheadOfTime processAheadOfTime()}.
* Any other test component — such as a
* {@link org.springframework.test.context.TestContextBootstrapper TestContextBootstrapper}
* — can choose to contribute an attribute at any point in time. Note that
* contributing an attribute during standard JVM test execution will not have any
* adverse side effect since AOT attributes will be ignored in that scenario. In
* any case, you should use {@link AotDetector#useGeneratedArtifacts()} to determine
* if invocations of {@link #setAttribute(String, String)} and
* {@link #removeAttribute(String)} are permitted.
*
* @author Sam Brannen
* @since 6.0
*/
public interface AotTestAttributes {
/**
* Get the current instance of {@code AotTestAttributes} to use.
* <p>See the class-level {@link AotTestAttributes Javadoc} for details on
* the two supported modes.
*/
static AotTestAttributes getInstance() {
return new DefaultAotTestAttributes(AotTestAttributesFactory.getAttributes());
}
/**
* Set a {@code String} attribute for later retrieval during AOT run-time execution.
* <p>In general, users should take care to prevent overlaps with other
* metadata attributes by using fully-qualified names, perhaps using a
* class or package name as a prefix.
* @param name the unique attribute name
* @param value the associated attribute value
* @throws UnsupportedOperationException if invoked during
* {@linkplain AotDetector#useGeneratedArtifacts() AOT run-time execution}
* @throws IllegalArgumentException if the provided value is {@code null} or
* if an attempt is made to override an existing attribute
* @see #setAttribute(String, boolean)
* @see #removeAttribute(String)
* @see AotDetector#useGeneratedArtifacts()
*/
void setAttribute(String name, String value);
/**
* Set a {@code boolean} attribute for later retrieval during AOT run-time execution.
* <p>In general, users should take care to prevent overlaps with other
* metadata attributes by using fully-qualified names, perhaps using a
* class or package name as a prefix.
* @param name the unique attribute name
* @param value the associated attribute value
* @throws UnsupportedOperationException if invoked during
* {@linkplain AotDetector#useGeneratedArtifacts() AOT run-time execution}
* @throws IllegalArgumentException if an attempt is made to override an
* existing attribute
* @see #setAttribute(String, String)
* @see #removeAttribute(String)
* @see Boolean#toString(boolean)
* @see AotDetector#useGeneratedArtifacts()
*/
default void setAttribute(String name, boolean value) {
setAttribute(name, Boolean.toString(value));
}
/**
* Remove the attribute stored under the provided name.
* @param name the unique attribute name
* @throws UnsupportedOperationException if invoked during
* {@linkplain AotDetector#useGeneratedArtifacts() AOT run-time execution}
* @see AotDetector#useGeneratedArtifacts()
* @see #setAttribute(String, String)
*/
void removeAttribute(String name);
/**
* Retrieve the attribute value for the given name as a {@link String}.
* @param name the unique attribute name
* @return the associated attribute value, or {@code null} if not found
* @see #getBoolean(String)
* @see #setAttribute(String, String)
*/
@Nullable
String getString(String name);
/**
* Retrieve the attribute value for the given name as a {@code boolean}.
* @param name the unique attribute name
* @return {@code true} if the attribute is set to "true" (ignoring case),
* {@code} false otherwise
* @see #getString(String)
* @see #setAttribute(String, String)
* @see Boolean#parseBoolean(String)
*/
default boolean getBoolean(String name) {
return Boolean.parseBoolean(getString(name));
}
}
|
package fr.lteconsulting.pomexplorer;
import fr.lteconsulting.pomexplorer.graph.relation.BuildDependencyRelation;
import fr.lteconsulting.pomexplorer.graph.relation.DependencyRelation;
import fr.lteconsulting.pomexplorer.graph.relation.ParentRelation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.jboss.shrinkwrap.resolver.api.InvalidConfigurationFileException;
import org.jboss.shrinkwrap.resolver.api.maven.*;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency;
import org.jboss.shrinkwrap.resolver.api.maven.pom.ParsedPomFile;
import org.jboss.shrinkwrap.resolver.impl.maven.MavenWorkingSessionImpl;
import org.jboss.shrinkwrap.resolver.impl.maven.task.AddScopedDependenciesTask;
import org.jboss.shrinkwrap.resolver.impl.maven.task.ConfigureSettingsFromFileTask;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PomAnalyzer
{
public void analyze(String directory, WorkingSession session, ILogger log)
{
processFile(new File(directory), session, log);
}
private void processFile(File file, WorkingSession session, ILogger log)
{
if (file == null)
return;
if (file.isDirectory())
{
String name = file.getName();
if ("target".equalsIgnoreCase(name) || "bin".equalsIgnoreCase(name) || "src".equalsIgnoreCase(name))
return;
for (File f : file.listFiles())
processFile(f, session, log);
}
else if (file.getName().equalsIgnoreCase("pom.xml"))
{
processPom(file, session, log);
}
}
/**
* Takes a GAV, download it if needed, analyse its dependencies and add them
* to the graph
*
* @param gav gav to be analyzed
* @param session working session
*/
public void registerExternalDependency(WorkingSession session, ILogger log, GAV gav)
{
String mavenSettingsFilePath = session.getMavenSettingsFilePath();
MavenResolverSystem resolver;
if (mavenSettingsFilePath != null && !mavenSettingsFilePath.isEmpty())
resolver = Maven.configureResolver().fromFile(mavenSettingsFilePath);
else
resolver = Maven.resolver();
MavenResolvedArtifact resolvedArtifact = null;
try
{
resolvedArtifact = resolver.resolve(gav.toString()).withoutTransitivity().asSingle(MavenResolvedArtifact.class);
} catch (Exception e)
{
log.html(Tools.errorMessage("shrinkwrap error : " + e.getMessage()));
}
if (resolvedArtifact == null)
{
log.html(Tools.warningMessage("cannot resolve the artifact " + gav));
return;
}
log.html("resolved artifact : " + resolvedArtifact.getCoordinate().toString() + "<br/>");
// Big hack here !
String pomPath = resolvedArtifact.asFile().getAbsolutePath();
int idx = pomPath.lastIndexOf('.');
if (idx < 0)
return;
pomPath = pomPath.substring(0, idx + 1) + "pom";
processPom(new File(pomPath), session, log);
}
private void processPom(File pomFile, WorkingSession session, ILogger log)
{
MavenProject unresolved = readPomFile(pomFile);
if (unresolved == null)
{
log.html("<span style='color:orange;'>cannot read pom " + pomFile.getAbsolutePath() + "</span><br/>");
return;
}
ParsedPomFile resolved = loadPomFile(session, pomFile);
if (resolved == null)
{
log.html("<span style='color:orange;'>cannot load pom " + unresolved.getGroupId() + ":" + unresolved.getArtifactId() + ":" + unresolved.getVersion() + " (<i>" + pomFile.getAbsolutePath() + "</i>)</span><br/>");
return;
}
GAV gav = new GAV(resolved.getGroupId(), resolved.getArtifactId(), resolved.getVersion());
if (session.projects().contains(gav))
{
log.html("<span style='color:orange;'>pom already processed '" + pomFile.getAbsolutePath() + "' ! Ignoring.</span><br/>");
return;
}
session.graph().addGav(gav);
// hierarchy
Parent parent = unresolved.getModel().getParent();
if (parent != null)
{
GAV parentGav = new GAV(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
session.graph().addGav(parentGav);
session.graph().addRelation(gav, parentGav, new ParentRelation());
}
// dependencies
for (MavenDependency dependency : resolved.getDependencies())
{
GAV depGav = new GAV(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion());
session.graph().addGav(depGav);
session.graph().addRelation(gav, depGav, new DependencyRelation(dependency.getScope().name(), dependency.getClassifier()));
}
// build dependencies
try
{
Model model = Tools.getParsedPomFileModel(resolved);
for (Plugin plugin : model.getBuild().getPlugins())
{
GAV depGav = new GAV(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion());
session.graph().addGav(depGav);
session.graph().addRelation(gav, depGav, new BuildDependencyRelation());
}
} catch (IllegalArgumentException | SecurityException e)
{
e.printStackTrace();
}
Project projectInfo = new Project(pomFile, resolved, unresolved);
session.projects().add(projectInfo);
session.repositories().add(projectInfo);
log.html("processed project " + projectInfo.getGav() + "<br/>");
}
private static MavenWorkingSession createMavenWorkingSession(WorkingSession workingSession)
{
try
{
String mavenSettingsFilePath = workingSession.getMavenSettingsFilePath();
MavenWorkingSession session = new MavenWorkingSessionImpl();
if (mavenSettingsFilePath != null)
session = new ConfigureSettingsFromFileTask(mavenSettingsFilePath).execute(session);
session = new AddScopedDependenciesTask(ScopeType.COMPILE, ScopeType.IMPORT, ScopeType.SYSTEM, ScopeType.RUNTIME).execute(session);
return session;
} catch (InvalidConfigurationFileException e)
{
return null;
}
}
private ParsedPomFile loadPomFile(WorkingSession workingSession, File pomFile)
{
MavenWorkingSession session = createMavenWorkingSession(workingSession);
if (session == null)
return null;
try
{
session.loadPomFromFile(pomFile);
return session.getParsedPomFile();
} catch (Exception e)
{
return null;
}
}
private MavenProject readPomFile(File pom)
{
Model model = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
try (FileReader reader = new FileReader(pom))
{
model = mavenreader.read(reader);
model.setPomFile(pom);
MavenProject project = new MavenProject(model);
return project;
} catch (IOException | XmlPullParserException e1)
{
return null;
}
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
็ปๅฎไธไธชๅ
ๅซ n ไธชๆดๆฐ็ๆฐ็ป nums ๅไธไธช็ฎๆ ๅผ target๏ผๅคๆญ nums ไธญๆฏๅฆๅญๅจๅไธชๅ
็ด a๏ผb๏ผc ๅ d ๏ผไฝฟๅพ a + b + c + d ็ๅผไธ target ็ธ็ญ๏ผๆพๅบๆๆๆปก่ถณๆกไปถไธไธ้ๅค็ๅๅ
็ปใ
ๆณจๆ๏ผ
็ญๆกไธญไธๅฏไปฅๅ
ๅซ้ๅค็ๅๅ
็ปใ
็คบไพ๏ผ
็ปๅฎๆฐ็ป nums = [1, 0, -1, 0, -2, 2]๏ผๅ target = 0ใ
ๆปก่ถณ่ฆๆฑ็ๅๅ
็ป้ๅไธบ๏ผ
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
*/
public class Question18 {
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
int length = nums.length;
if (length < 4){
return ans;
}
Arrays.sort(nums);
if (nums[0] == 0 && nums[length-1]==0 && target == 0){
List<Integer> oneanswer = new ArrayList<>();
oneanswer.add(0);
oneanswer.add(0);
oneanswer.add(0);
oneanswer.add(0);
ans.add(oneanswer);
return ans;
}
for (int i = 0; i < length - 3; i++){
for (int j = i + 1; j < length - 2; j++){
int sum2 = nums[i] + nums[j];
int left = j + 1, right = length - 1;
while (left < right){
if ((nums[left]+nums[right]) < (target - sum2)){
left++;
}else if ((nums[left]+nums[right]) > (target - sum2)){
right--;
}else {
List<Integer> oneanswer = new ArrayList<>();
oneanswer.add(nums[i]);
oneanswer.add(nums[j]);
oneanswer.add(nums[left]);
oneanswer.add(nums[right]);
left++;
right--;
if (!ans.contains(oneanswer)){
ans.add(oneanswer);
}
}
}
}
}
return ans;
}
public static void main(String[] args) {
int[] nums= {-2, -1, 1, 2};
System.out.println(fourSum(nums, 0));
}
}
|
// import java.io.*;
// import java.util.*;
// // ์๊ฑฐ๋ solved ์๋๋ ์ฃผ์ํ์๊ฒ
// class baek__16161 {
// public static void main(String[] args) throws IOException {
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// int n = Integer.parseInt(br.readLine());
// int[] arr = new int[n + 1];
// String[] temp = br.readLine().split(" ");
// for (int i = 0; i < n; i++) {
// arr[i] = Integer.parseInt(temp[i]);
// }
// arr[n] = 1000000001;
// int ans = 1;
// int p = 0;
// int c1 = 0;
// int c2 = 0;
// while (p < n) {
// if (arr[p] < arr[p + 1]) {
// p++;
// c1 = c2 = p;
// } else if (arr[p] == arr[p + 1]) {
// p++;
// c2 = p;
// ans = Math.max(ans, c2 - c1 + 1);
// } else {
// if (c1 - (p + 1 - c2) >= 0 && arr[c1 - (p + 1 - c2)] == arr[p + 1]) {
// p++;
// ans = Math.max(ans, (p - c2) * 2 + c2 - c1 + 1);
// } else {
// p++;
// }
// }
// }
// System.out.print(ans);
// }
// }
|
package ui.game;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import cards.Card;
import core.client.GamePanel;
import core.player.PlayerCardZone;
import listeners.game.CardOnHandListener;
import ui.game.interfaces.CardRackUI;
import ui.game.interfaces.CardUI;
/**
* card rack (cards on hand) gui
*
* @author Harry
*
*/
public class CardRackGui extends JPanel implements CardOnHandListener, CardRackUI {
private static final long serialVersionUID = -7373800552773539354L;
public static final int WIDTH = GamePanelGui.WIDTH - EquipmentRackGui.WIDTH - HeroGui.WIDTH - LifebarGui.WIDTH;
public static final int HEIGHT = 200;
private final ActionListener listener;
private List<CardGui> cards;
public CardRackGui(GamePanel panel, PlayerCardZone zone) {
setLayout(null);
setSize(WIDTH, HEIGHT);
setLocation(EquipmentRackGui.WIDTH, GamePanelGui.HEIGHT - HEIGHT);
cards = new ArrayList<CardGui>();
this.listener = e -> panel.getCurrentOperation().onSelectionPaneCardClicked((CardGui) e.getSource(), zone);
}
public CardRackGui(GamePanel panel) {
setLayout(null);
setSize(WIDTH, HEIGHT);
setLocation(EquipmentRackGui.WIDTH, GamePanelGui.HEIGHT - HEIGHT);
cards = new ArrayList<CardGui>();
this.listener = e -> panel.getCurrentOperation().onCardClicked((CardGui) e.getSource());
}
@Override
public void onCardAdded(Card card) {
addCardGui(new CardGui(card), false);
}
@Override
public synchronized void onCardRemoved(Card card) {
for (int i = 0; i < cards.size(); i++) {
if (cards.get(i).getCard().equals(card)) {
remove(cards.remove(i));
resetLocations();
repaint();
break;
}
}
}
public synchronized void addCardGui(CardGui cardGui, boolean enabled) {
cardGui.setEnabled(enabled);
cardGui.addActionListener(listener);
cards.add(cardGui);
add(cardGui, 0);
resetLocations();
repaint();
}
@Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
for (CardGui c : cards)
c.paintComponents(g);
}
/**
* subtract offset from card's alpha values
*
* @param offset
* : amount of change, from 0 to 1
*/
protected void fadeCards(float offset) {
for (CardGui c : cards)
c.fade(offset);
}
protected synchronized void clearRack() {
removeAll();
cards.clear();
repaint();
}
public synchronized void setCardSelected(Card card, boolean selected) {
for (CardGui c : cards) {
if (c.getCard().equals(card)) {
if (selected) {
c.select();
} else {
c.unselect();
}
return;
}
}
}
public synchronized void setCardSelectable(Card card, boolean selectable) {
for (CardGui c : cards) {
if (c.getCard().equals(card)) {
c.setEnabled(selectable);
repaint();
return;
}
}
}
private void resetLocations() {
int totalLength = cards.size() * CardGui.WIDTH;
int stepLength;
if (totalLength <= getWidth())
stepLength = CardGui.WIDTH;
else
stepLength = (getWidth() - CardGui.WIDTH) / (cards.size() - 1);
int size = cards.size();
for (int i = 0; i < size; i++) {
cards.get(i).setLocation(i * stepLength, 0);
}
}
@Override
public List<? extends CardUI> getCardUIs() {
return cards;
}
}
|
package com.barnettwong.view_library.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.barnettwong.view_library.R;
/**
* Created by tiankui on 7/6/17.
*/
public class MyListItemSwitchButton extends LinearLayout {
private MySwitchButton switchButton;
public MyListItemSwitchButton(Context context) {
super(context);
initView(null);
}
public MyListItemSwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
initView(attrs);
}
private void initView(AttributeSet attrs) {
inflate(getContext(), R.layout.switch_button_list_item, this);
switchButton = (MySwitchButton) findViewById(R.id.switch_button);
TextView rce_list_item_title = (TextView) findViewById(R.id.tv_title);
if (attrs != null) {
TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.swb_list_item);
CharSequence title = attributes.getText(R.styleable.swb_list_item_swb_list_item_title);
rce_list_item_title.setText(title);
attributes.recycle();
}
}
public void setSwitchButtonChangedListener(CompoundButton.OnCheckedChangeListener checkedChangeListener) {
switchButton.setOnCheckedChangeListener(checkedChangeListener);
}
public void setChecked(boolean checked){
switchButton.setChecked(checked);
}
public boolean isChecked(){
return switchButton.isChecked();
}
public void setCheckedImmediately(boolean checked){
switchButton.setCheckedImmediately(checked);
}
}
|
import java.util.Random;
import java.util.Scanner;
public class TryThis{
private static boolean running = true;
public static void main(String[] arg) {
Character juku=new Character();
Character kati=new Character();
juku.move();
kati.changeDirection(Direction.UP);
kati.move();
juku.changeDirection(Direction.UP);
String command;
Obstacles room = new Obstacles();
System.out.println(room);
while(running = true) {
System.out.println(juku);
System.out.println(kati);
System.out.println(juku.distance(kati));
Scanner reader= new Scanner(System.in);
System.out.println("juku's direction ([l]eft, [r]ight, [u]p, [d]own)");
String input=reader.nextLine();
if(input.equals("l")) {
juku.changeDirection(Direction.LEFT);
}
if(input.equals("r")) {
juku.changeDirection(Direction.RIGHT);
}
if(input.equals("u")) {
juku.changeDirection(Direction.UP);
}
if(input.equals("d")) {
juku.changeDirection(Direction.DOWN);
}
System.out.println("juku liigub...");
if(juku.distance(kati) == 0) {
System.out.println("M6lemad on samal kohal!");
break;
}
if(juku.x == room.x && juku.y == room.y) {
Random r = new Random();
juku.x = r.nextInt(15 - 1) + 1;
kati.x = r.nextInt(15 - 1) + 1;
}
juku.move();
juku.distance(kati);
command = reader.nextLine();
System.out.println("kati's direction ([l]eft, [r]ight, [u]p, [d]own)");
if(command.equals("r")){
kati.changeDirection(Direction.RIGHT);
}else if(command.equals("l")){
kati.changeDirection(Direction.LEFT);
}else if(command.equals("u")){
kati.changeDirection(Direction.UP);
}else if(command.equals("d")){
kati.changeDirection(Direction.DOWN);
}
if(kati.x == room.x && kati.y == room.y) {
Random r = new Random();
juku.x = r.nextInt(15 - 1) + 1;
kati.x = r.nextInt(15 - 1) + 1;
}
System.out.println("kati liigub...");
kati.move();
kati.distance(juku);
if(kati.distance(juku) == 0){
System.out.println("M6lemad on samal kohal!");
break;
}
}
}
}
|
package com.training.servlets;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.TreeSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.training.entity.Contact;
import com.training.entity.ContactList;
import com.training.utils.ContactDAO;
import com.training.utils.ContactDAOImplementation;
import com.training.utils.DbConnections;
/**
* Servlet implementation class viewCategoryWise
*/
public class viewCategoryWise extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public viewCategoryWise() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
ClassLoader clsLdr=Thread.currentThread().getContextClassLoader();
InputStream inStream=clsLdr.getResourceAsStream("JDBC.properties");
Connection conn=DbConnections.getConnection(inStream);
ContactDAO dao=new ContactDAOImplementation(conn);
RequestDispatcher dispatcher=request.getRequestDispatcher("categoryWiseView.jsp");
try {
TreeSet<Contact> contacts=dao.findAll();
ContactList contactList=new ContactList(contacts);
request.setAttribute("friendList", contactList.getFriends());
request.setAttribute("relativeList", contactList.getRelatives());
request.setAttribute("officeList", contactList.getOffice());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dispatcher.forward(request, response);
}
}
|
package blazeplus;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.asm.SideOnly;
import net.minecraft.src.Enchantment;
import net.minecraft.src.EnchantmentHelper;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityArrow;
import net.minecraft.src.EntityLiving;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.EntityPlayerSP;
import net.minecraft.src.Item;
import net.minecraft.src.ItemBow;
import net.minecraft.src.ItemStack;
import net.minecraft.src.ModLoader;
import net.minecraft.src.World;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.ArrowLooseEvent;
public class BlazeItemBow extends ItemBow{
public BlazeItemBow(int itemId, int maxDamage) {
super(itemId);
maxStackSize = 1;
setMaxDamage(maxDamage);
setTextureFile(DefaultProps.TEXTURE_PATH);
this.setCreativeTab(BlazePlus.blazeTabs);
}
@Override
public boolean hitEntity(ItemStack par1ItemStack,
EntityLiving par2EntityLiving, EntityLiving par3EntityLiving) {
par1ItemStack.damageItem(2, par3EntityLiving);
return true;
}
@Override
public int getDamageVsEntity(Entity par1Entity) {
if (par1Entity instanceof EntityLiving) {
par1Entity.setFire(2);
}
return super.getDamageVsEntity(par1Entity);
}
@Override
@SideOnly(Side.CLIENT)
public int getIconFromDamage(int par1) {
EntityPlayer entitiPlayer = ModLoader.getMinecraftInstance().thePlayer;
if(entitiPlayer.getItemInUse() != null && entitiPlayer.getItemInUse().getItem() instanceof ItemBow) {
int j = entitiPlayer.getItemInUseDuration();
if(j >= 18){
return 14;
} else if(j >= 13) {
return 13;
} else if(j > 0) {
return 12;
}
}
return 11;
}
@Override
public void onPlayerStoppedUsing(ItemStack par1ItemStack, World par2World,
EntityPlayer par3EntityPlayer, int par4) {
int var6 = this.getMaxItemUseDuration(par1ItemStack) - par4;
ArrowLooseEvent event = new ArrowLooseEvent(par3EntityPlayer, par1ItemStack, var6);
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled())
{
return;
}
var6 = event.charge;
boolean var5 = par3EntityPlayer.capabilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, par1ItemStack) > 0;
if (var5 || par3EntityPlayer.inventory.hasItem(Item.arrow.shiftedIndex))
{
float var7 = (float)var6 / 20.0F;
var7 = (var7 * var7 + var7 * 2.0F) / 3.0F;
if ((double)var7 < 0.1D)
{
return;
}
if (var7 > 1.0F)
{
var7 = 1.0F;
}
EntityArrow var8 = new EntityArrow(par2World, par3EntityPlayer, var7 * 2.0F);
if (var7 == 1.0F)
{
var8.setIsCritical(true);
}
int var9 = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, par1ItemStack);
if (var9 > 0)
{
var8.setDamage(var8.getDamage() + (double)var9 * 0.5D + 0.5D);
}
int var10 = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, par1ItemStack);
if (var10 > 0)
{
var8.setKnockbackStrength(var10);
}
//if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, par1ItemStack) > 0)
//{
var8.setFire(100);
//}
par1ItemStack.damageItem(1, par3EntityPlayer);
par2World.playSoundAtEntity(par3EntityPlayer, "random.bow", 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + var7 * 0.5F);
if (var5)
{
var8.canBePickedUp = 2;
}
else
{
par3EntityPlayer.inventory.consumeInventoryItem(Item.arrow.shiftedIndex);
}
if (!par2World.isRemote)
{
par2World.spawnEntityInWorld(var8);
}
}
}
}
|
/*
* 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.github.edgar615.cache;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by edgar on 16-4-1.
*/
public class LinkedHashMapTest {
public static void main(String[] args) {
//LinkedHashMap็ไธไธชๆ้ ๅฝๆฐ๏ผๅฝๅๆฐaccessOrderไธบtrueๆถ๏ผๅณไผๆ็
ง่ฎฟ้ฎ้กบๅบๆๅบ๏ผๆ่ฟ่ฎฟ้ฎ็ๆพๅจๆๅ๏ผๆๆฉ่ฎฟ้ฎ็ๆพๅจๅ้ข
Map<String, String> map = new LinkedHashMap<>();
map.put("a", "a");
map.put("b", "b");
map.get("b");
System.out.println(map); //{a=a, b=b}
map.get("b");
map.get("b");
map.get("b");
System.out.println(map);//{a=a, b=b}
//ๆฏๆฌกๆทปๅ ้ฝไผๅ ้ค
map = new LinkedHashMap<String, String>() {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return true;
}
};
map.put("a", "a");
System.out.println(map); //{}
map.put("b", "b");
System.out.println(map); //{}
//ๅง็ปๅ ้คๆๆฉ็
map = new LinkedHashMap<String, String>(2, 0.75f, false) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > 2;
}
};
map.put("a", "a");
map.put("b", "b");
System.out.println(map); //{a=a, b=b}
map.get("a");
map.get("a");
map.get("a");
map.get("a");
map.put("c", "c");
System.out.println(map); //{b=b, c=c}
//ๅง็ปๅ ้ค่ฎฟ้ฎๆๅฐ็
map = new LinkedHashMap<String, String>(2, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > 2;
}
};
map.put("a", "a");
map.put("b", "b");
System.out.println(map); //{a=a, b=b}
map.get("a");
map.get("a");
map.get("a");
map.get("a");
map.put("c", "c");
System.out.println(map); //{a=a, c=c}
}
}
|
package com.example.restapi3;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import org.jetbrains.annotations.NotNull;
public class ProfileFragment extends Fragment {
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @org.jetbrains.annotations.NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container,false);
}
public static String Base_URL2 = "https://github.com/Sirius-aa7";
private static Retrofit retrofit;
public static Retrofit getClient2(){
if (retrofit==null) {
retrofit = new Retrofit.Builder().baseUrl(Base_URL2).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
|
package webapp;
/**
* @author simetrias
*/
public class DatasetCanvasItemModel extends AbstractCanvasItemModel {
}
|
package com.juannarvaez.taskworkout.model.Internet;
public interface TaskWorkoutCallBack<T>{
void tareaCorrecta (T respuesta);
void tareaError (Exception exception);
}
|
package com.toni.programming.data;
public abstract class LifeBeing implements IAction, IRender {
protected Status status;
protected String typeOfToy;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getTypeOfToy() {
return typeOfToy;
}
public void setTypeOfToy(String typeOfToy) {
this.typeOfToy = typeOfToy;
}
}
|
package com.arthur.leetcode;
import org.omg.PortableInterceptor.INACTIVE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* @program: leetcode
* @description: ๆๅฐ็kไธชๆฐ
* @title: JZoffer40
* @Author hengmingji
* @Date: 2022/1/2 16:34
* @Version 1.0
*/
public class JZoffer40 {
// public int[] getLeastNumbers(int[] arr, int k) {
// Arrays.sort(arr);
// ArrayList<Integer> list = new ArrayList<>();
// for (int i = 0; i < k; i++) {
// list.add(arr[i]);
// }
// return list.stream().mapToInt(Integer::valueOf).toArray();
// }
public int[] getLeastNumbers(int[] arr, int k) {
PriorityQueue<Integer> stack = new PriorityQueue<>(k);
for (int i : arr) {
stack.add(i);
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < k; i++) {
list.add(stack.poll());
}
return list.stream().mapToInt(Integer::valueOf).toArray();
}
}
|
package app.akeorcist.deviceinformation.dialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.ms.square.android.etsyblur.BlurDialogFragmentHelper;
import app.akeorcist.deviceinformation.R;
import app.akeorcist.deviceinformation.model.AppData;
/**
* Created by Akexorcist on 3/14/15 AD.
*/
public class AppDialog extends DialogFragment {
private static final String KEY_NAME = "title";
private static final String KEY_PACKAGE = "description";
private static final String KEY_VERSION_CODE = "version_code";
private static final String KEY_VERSION_NAME = "version_name";
private static final String KEY_PERMISSION = "permission";
private static final String KEY_ICON_RESOURCE = "icon_resource";
private TextView tvAppName = null;
private TextView tvAppPackage = null;
private TextView tvAppVersionCode = null;
private TextView tvAppVersionName = null;
private TextView tvAppPermission = null;
private ImageView ivAppIcon = null;
private LinearLayout layoutAppPermission = null;
private BlurDialogFragmentHelper blurHelper = null;
public static AppDialog newInstance(AppData appData) {
AppDialog dialog = new AppDialog();
Bundle bundle = new Bundle();
bundle.putString(KEY_NAME, appData.getName());
bundle.putString(KEY_PACKAGE, appData.getPackage());
bundle.putString(KEY_VERSION_CODE, appData.getVersionCode());
bundle.putString(KEY_VERSION_NAME, appData.getVersionName());
bundle.putInt(KEY_ICON_RESOURCE, appData.getIconResource());
if(appData.getPermissions().size() > 0) {
String strPermission = "";
for (String permission : appData.getPermissions()) {
strPermission += permission + "\n\n";
}
strPermission = strPermission.trim();
bundle.putString(KEY_PERMISSION, strPermission);
} else {
bundle.putString(KEY_PERMISSION, "");
}
dialog.setArguments(bundle);
return dialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
blurHelper = new BlurDialogFragmentHelper(this);
blurHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
Bundle bundle = getArguments();
View rootView = inflater.inflate(R.layout.dialog_app_detail, container, false);
ivAppIcon = (ImageView) rootView.findViewById(R.id.iv_app_icon);
int resIcon = bundle.getInt(KEY_ICON_RESOURCE);
String pack = bundle.getString(KEY_PACKAGE);
if(resIcon != 0) {
Uri uri = Uri.parse("android.resource://" + pack + "/" + resIcon);
Glide.with(getActivity()).load(uri).into(ivAppIcon);
} else {
Glide.with(getActivity()).load(R.drawable.ic_app_default).into(ivAppIcon);
}
tvAppName = (TextView) rootView.findViewById(R.id.tv_app_name);
tvAppName.setText(bundle.getString(KEY_NAME));
tvAppPackage = (TextView) rootView.findViewById(R.id.tv_app_package);
tvAppPackage.setText(pack);
tvAppVersionCode = (TextView) rootView.findViewById(R.id.tv_app_version_code);
tvAppVersionCode.setText(bundle.getString(KEY_VERSION_CODE));
tvAppVersionName = (TextView) rootView.findViewById(R.id.tv_app_version_name);
tvAppVersionName.setText(bundle.getString(KEY_VERSION_NAME));
tvAppPermission = (TextView) rootView.findViewById(R.id.tv_app_permission);
layoutAppPermission = (LinearLayout) rootView.findViewById(R.id.layout_app_permission);
String permission = bundle.getString(KEY_PERMISSION);
if(!permission.equals("")) {
tvAppPermission.setText(permission);
} else {
layoutAppPermission.setVisibility(View.GONE);
}
setCancelable(true);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
blurHelper.onViewCreated(view, savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
blurHelper.onStart();
}
@Override
public void onCancel(DialogInterface dialog) {
blurHelper.onCancel(dialog);
super.onCancel(dialog);
}
@Override
public void onStop() {
blurHelper.onCancel(getDialog());
super.onStop();
}
} |
package resources;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import frames.HelpFrame;
public class AllImage {
public static final Icon RECORDS=new ImageIcon(AllImage.class.getResource("/image/Records.png"));
public static final Icon TETRIS=new ImageIcon(AllImage.class.getResource("/image/Tetris.png"));
public static final Icon SNAKE=new ImageIcon(AllImage.class.getResource("/image/Snake.png"));
public static final Icon STRIKE=new ImageIcon(AllImage.class.getResource("/image/Strike.png"));
public static final Icon BRICK=new ImageIcon(AllImage.class.getResource("/image/brick.jpg"));
public static final Icon FIRE=new ImageIcon(AllImage.class.getResource("/image/Bamboo.jpg"));
public static final Icon BARK=new ImageIcon(AllImage.class.getResource("/image/Bark.jpg"));
public static final Icon METAL=new ImageIcon(AllImage.class.getResource("/image/Metal.jpg"));
public static final Icon VOLUME=new ImageIcon(AllImage.class.getResource("/image/volume.png"));
public static final Icon MUTE=new ImageIcon(AllImage.class.getResource("/image/mute.png"));
public static final Icon HELP=new ImageIcon(AllImage.class.getResource("/image/help.png"));
public static final Icon engineOptimalSel=new ImageIcon(AllImage.class.getResource("/help.png"));
public static final Icon HERO_TANK=new ImageIcon(AllImage.class.getResource("/image/Tank.png"));
public static final Icon SHELL = new ImageIcon(AllImage.class.getResource("/image/Shell.png"));
/*public static final Icon PICI[]= {
new ImageIcon(AllImage.class.getResource("/image/O/pici.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici6.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici1.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici3.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici8.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici2.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici7.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici4.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici5.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici9.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici10.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici11.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici12.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici13.pcp")),
new ImageIcon(AllImage.class.getResource("/image/O/pici14.pcp")),
};*/
/*public static final Icon PICI[]= {
new ImageIcon(AllImage.class.getResource("/image/I/pici.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici6.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici1.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici3.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici8.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici2.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici7.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici4.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici5.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici9.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici10.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici11.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici12.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici13.pcp")),
new ImageIcon(AllImage.class.getResource("/image/I/pici14.pcp")),
};*/
public static final Icon PICI[]= {
new ImageIcon(AllImage.class.getResource("/image/D/1.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/2.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/3.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/4.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/5.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/6.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/7.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/8.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/9.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/10.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/11.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/12.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/13.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/14.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/15.jpg")),
new ImageIcon(AllImage.class.getResource("/image/D/16.jpg")),
};
}
|
package io.github.futurewl.imooc.java.authority.management.param;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* ๅ่ฝๆ่ฟฐ๏ผ
*
* @author weilai create by 2019-04-18:16:12
* @version 1.0
*/
@Getter
@Setter
public class TestVo {
@NotBlank
private String msg;
@NotNull(message = "idไธๅฏไปฅไธบ็ฉบ")
@Max(value = 10, message = "ID ไธ่ฝๅคงไบ็ญไบ10")
@Min(value = 0, message = "ID ่ณๅฐๅคงไบ็ญไบ0")
private Integer id;
// @NotEmpty
private List<String> str;
}
|
package intersection;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by eprijilevschi on 5/29/2017.
*/
public class IntersectionTest {
private Intersection intersection = new Intersection();
@Test
public void testEmptyString(){
String inputString = "";
String expected = "ะะตัะตัะตัะตะฝะธั ะฝะตั";
String actual = intersection.findAll(inputString);
Assert.assertEquals("The string is empty!", expected, actual);
}
@Test
public void testTwoIntersections(){
String inputString = "ะะฐัะะตัะธะพะดะฐ1,ะะฐัะะตัะธะพะดะฐ2,ะะพะฝะะตัะธะพะดะฐ1, ะะพะฝะะตัะธะพะดะฐ2";
String expected = "ะะฐัะะตัะธะพะดะฐ2, ะะพะฝะะตัะธะพะดะฐ1";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There are 2 intersections", expected, actual);
}
@Test
public void testNoIntersections(){
String inputString = "ะะฐัะะตัะธะพะดะฐ1,ะะพะฝะะตัะธะพะดะฐ1,ะะฐัะะตัะธะพะดะฐ2, ะะพะฝะะตัะธะพะดะฐ2";
String expected = "ะะตัะตัะตัะตะฝะธั ะฝะตั";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There are no intersections", expected, actual);
}
@Test
public void testMinusInfinity(){
String inputString = " ะะฐัะะตัะธะพะดะฐ4,ะะพะฝะะตัะธะพะดะฐ3,ะะพะฝะะตัะธะพะดะฐ4";
String expected = "-ะฑะตัะบะพะฝะตัะฝะพััั";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There is -infinity", expected, actual);
}
@Test
public void testPlusInfinity(){
String inputString = "ะะฐัะะตัะธะพะดะฐ5, ะะพะฝะะตัะธะพะดะฐ5,ะะฐัะะตัะธะพะดะฐ6";
String expected = "+ะฑะตัะบะพะฝะตัะฝะพััั";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There is +infinity", expected, actual);
}
@Test
public void testNestedPeriods(){
String inputString = "ะะฐัะะตัะธะพะดะฐ1,ะะฐัะะตัะธะพะดะฐ2,ะะพะฝะะตัะธะพะดะฐ2, ะะพะฝะะตัะธะพะดะฐ1";
String expected = "ะะฐัะะตัะธะพะดะฐ2, ะะพะฝะะตัะธะพะดะฐ2";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There are 2 intersections", expected, actual);
}
@Test
public void testMultiplePeriods(){
String inputString = "ะะฐัะะตัะธะพะดะฐ1,ะะพะฝะะตัะธะพะดะฐ1, ะะฐัะะตัะธะพะดะฐ2,ะะฐัะะตัะธะพะดะฐ3,ะะฐัะะตัะธะพะดะฐ4,ะะพะฝะะตัะธะพะดะฐ3,ะะพะฝะะตัะธะพะดะฐ4, ะะพะฝะะตัะธะพะดะฐ2";
String expected = "ะะฐัะะตัะธะพะดะฐ3, ะะฐัะะตัะธะพะดะฐ4, ะะพะฝะะตัะธะพะดะฐ3, ะะพะฝะะตัะธะพะดะฐ4";
String actual = intersection.findAll(inputString);
Assert.assertEquals("There are 4 intersections", expected, actual);
}
}
|
package com.vipvideo.ui.reader;
import android.support.design.widget.AppBarLayout;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.lixh.base.BasePageView;
import com.lixh.ireader.R;
import com.lixh.view.UToolBar;
import butterknife.Bind;
import static android.view.View.GONE;
/**
* Created by LIXH on 2018/11/19.
* email lixhVip9@163.com
* des
*/
public class ReadTopView extends BasePageView {
@Bind(R.id.read_tv_brief)
TextView readTvBrief;
@Bind(R.id.read_tv_community)
TextView readTvCommunity;
@Bind(R.id.toolbar)
UToolBar toolbar;
@Bind(R.id.read_abl_top_menu)
AppBarLayout readAblTopMenu;
private Animation mTopInAnim;
private Animation mTopOutAnim;
public ReadTopView(ReadActivityNew readActivityNew, FrameLayout topView) {
super(readActivityNew, topView);
}
@Override
public int getLayoutId() {
return R.layout.read_top_layout;
}
@Override
public void init() {
mTopInAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_top_in);
mTopOutAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_top_out);
//้ๅบ็้ๅบฆ่ฆๅฟซ
mTopOutAnim.setDuration(200);
}
public void toggleMenu() {
if (root.getVisibility() == View.VISIBLE) {
//ๅ
ณ้ญ
root.startAnimation(mTopOutAnim);
root.setVisibility(GONE);
} else {
root.startAnimation(mTopInAnim);
root.setVisibility(View.VISIBLE);
}
}
public boolean isVisible() {
return root.getVisibility() == View.VISIBLE;
}
}
|
package fr.aresrpg.tofumanchou.domain.data.entity;
import fr.aresrpg.dofus.structures.Orientation;
import fr.aresrpg.dofus.structures.game.Effect;
import java.util.Set;
/**
*
* @since
*/
public interface Entity {
long getUUID();
Set<Effect> getEffects();
int getCellId();
void setCellId(int cellid);
int getScaleX();
int getLife();
void setLife(int life);
int getPa();
void setPa(int pa);
boolean isDead();
void setDead(boolean dead);
int getPm();
void setPm(int pm);
int getScaleY();
Orientation getOrientation();
}
|
package org.vanilladb.comm.protocols.totalorderappl;
import java.io.Serializable;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.Direction;
import net.sf.appia.core.Event;
import net.sf.appia.core.Session;
public class TotalOrderMessages extends Event {
private Serializable[] messages;
private long messageSerialNumberStart;
public TotalOrderMessages(Channel channel, Session src, Serializable[] messages,
long messageSerialNumberStart) throws AppiaEventException {
super(channel, Direction.UP, src);
this.messages = messages;
this.messageSerialNumberStart = messageSerialNumberStart;
}
public Serializable[] getMessages() {
return messages;
}
public long getMessageSerialNumberStart() {
return messageSerialNumberStart;
}
}
|
package presentation.controller;
import common.ResultMessage;
/**
* @ author lienming
* @ version 2016-11-27
* @ description
*/
public interface RegisterViewControllerService {
/**
* ๆณจๅ่ดฆๅท
* @return id:String (or "FAIL")
* @author lienming
* @version 2016-11-27
*/
public String register(String memberName,String password);
public ResultMessage modify(String id,String newPassword);
}
|
public class TheKingsArmyDiv2 {
public int getNumber(String[] state) {
boolean happy = false;
for(int i = 0; i < state.length; ++i) {
for(int j = 0; j < state[i].length(); ++j) {
if(state[i].charAt(j) == 'H') {
happy = true;
if(j + 1 < state[i].length() && state[i].charAt(j + 1) == 'H') {
return 0;
}
if(i + 1 < state.length && state[i + 1].charAt(j) == 'H') {
return 0;
}
}
}
}
if(happy) {
return 1;
}
return 2;
}
} |
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(Iotman)็ฝๅ
ณ็ฎก็
//generate by redcloud,2020-07-24 19:59:20
public class Iotman implements Serializable {
private static final long serialVersionUID = 31L;
// ่ชๅขID
private Long id ;
// ่ฎพๅคๅ็งฐ
private String title ;
// ่ฎพๅคๆ่ฟฐ
private String equdes ;
// ่ฎพๅคIP
private String equip ;
// ๅๅ
private String factory ;
// ๆๅ้ไฟกๆถ้ด
private Long lasttime ;
// ๅทฅไฝๆถ้ฟ
private String workdur ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getEqudes() {
return equdes ;
}
public void setEqudes(String equdes) {
this.equdes = equdes;
}
public String getEquip() {
return equip ;
}
public void setEquip(String equip) {
this.equip = equip;
}
public String getFactory() {
return factory ;
}
public void setFactory(String factory) {
this.factory = factory;
}
public Long getLasttime() {
return lasttime ;
}
public void setLasttime(Long lasttime) {
this.lasttime = lasttime;
}
public String getWorkdur() {
return workdur ;
}
public void setWorkdur(String workdur) {
this.workdur = workdur;
}
}
|
package n.db;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import n.models.Area;
import n.models.Match;
import n.models.TravelAreas;
import n.models.Central;
import n.models.North;
import n.models.Qualification;
import n.models.Referee;
import n.models.South;
/**
* This class is responsible for storing the Referee objects within the Referee
* array called 'referees' and Match objects in an array 'matches'. All other
* objects manipulating data in these array have a reference to this class.
*/
public class DataSource {
/** Name of text file for inputing referee data */
public static final String INPUT_REFEREE_FILE = "RefereesIn.txt";
/** Name of text file for outputting referee data */
public static final String OUTPUT_REFEREE_FILE = "RefereesOut.txt";
/** Name of text file for outputting match allocations */
public static final String OUTPUT_MATCH_FILE = "MatchAllocs.txt";
/** Maximum number of referee objects */
public static final short MAX_REFEREES = 12;
/** Referee objects array is instantiated to null */
private Referee[] referees = null;
/** Match objects array is instantiated to null */
private Match[] matches = null;
/**
* The constructor reads a list of referees in from the INPUT_REFEREE_FILE
* file and populates the referees array.
*/
public DataSource() {
this.referees = readIn();
}
/**
* Getter for matches
* @return matches
*/
public Match[] getMatches() {
return matches;
}
/**
* Setter for matches
* @param matches
*/
public void setMatches(Match[] matches) {
this.matches = matches;
}
/**
* Adds a match to the matches array.
* @param match
* @return whether add has been successful
*/
public boolean add(Match match) {
if (search(match) == null) {
List<Match> matchList = null;
if (matches==null) {
matches = new Match[]{match};
} else {
matchList = new ArrayList<Match>(Arrays.asList(matches));
matchList.add(match);
matches = matchList.toArray(new Match[matchList.size()]);
}
return true;
} else {
return false;
}
}
/**
* Removes a match from the matches array.
* @param match
* @return whether successful
*/
public boolean remove(Match match) {
//Create a List data structure that copies the content of the match array
List<Match> matchesList = new ArrayList<Match>(Arrays.asList(matches));
boolean found = false;
int position = 0;
//Iterate through the matches array
for(int i=0;i<matches.length;i++) {
if (matches[i].getWeek() == match.getWeek()) {
found = true;
position = i;
break;
}
}
if (found) {
//Removes the match object from the array list
matchesList.remove(position);
//Initialises the matches array to the array list after removing referee
matches = matchesList.toArray(new Match[matchesList.size()]);
}
return found;
}
/**
* Searches the matches array.
* @param match
* @return match or null
*/
public Match search(Match match) {
//create a local match variable and assign it to null
Match exists = null;
if (matches==null) {
return exists;
}
//iterate over matches array and check if a match exists
for (Match m : matches) {
if (m.getWeek() == match.getWeek()) {
return m;
}
}
return exists;
}
/**
* Getter for referees array.
* @return
*/
public Referee[] getReferees() {
return referees;
}
/**
* Setter for referees array.
* @param referees
*/
public void setReferees(Referee[] referees) {
this.referees = referees;
}
/**
* Removes a referee from the referees array.
* @param referee
* @return whether successful
*/
public boolean remove(Referee referee) {
//Create a List data structure that copies the content of the referee array
List<Referee> refereeList = new ArrayList<Referee>(Arrays.asList(referees));
boolean found = false;
int position = 0;
//Iterate through the referees array
for(int i=0;i<referees.length;i++) {
if (referees[i].getId().equals(referee.getId())) {
found = true;
position = i;
break;
}
}
if (found) {
//Removes referee object from the array list
refereeList.remove(position);
//Initialises the referees array to the array list after removing referee
referees = refereeList.toArray(new Referee[refereeList.size()]);
}
return found;
}
/**
* Replaces an existing referees object with the parameter object.
* @param referee
* @return if successful
*/
public boolean update(Referee referee) {
// calls the search method of this class to test if referee object is not null
if (search(referee) != null) {
//call on the remove method within this class to remove a referee
remove(referee);
// call on the add method of this class to add a new referee object to the array
return add(referee);
//if the referee object being passed in does not exist then return false
} else {
return false;
}
}
/**
* Adds a new referee to the referees array if the array size does not
* exceed MAX_REFEREES.
* @param referee
* @return whether successful
*/
public boolean add(Referee referee) {
// checks if the number of referee objects in the array is less than the max number (12).
if (referees.length < DataSource.MAX_REFEREES) {
// check to ensure the referee does not already exist by calling the search method
if (search(referee) == null) {
//create a local referee arrayList using the contents of the current referees object array
List<Referee> refereeList = new ArrayList<Referee>(Arrays.asList(referees));
//add the new referee object (being passed into this method) to the array list
refereeList.add(referee);
//update the referees object array by assigning it to the new arraylist with the newly added object
referees = refereeList.toArray(new Referee[refereeList.size()]);
//sort Referee objects in the referees array
Arrays.sort(referees);
return true; // returns true once the new referee object has been added to the array
} else {
return false; // returns false if the referee object already exists
}
} else {
return false; //returns false if the number of referee objects in array exceeds 12
}
}
/**
* Searches the referees array.
* @param firstName
* @param lastName
* @return a referee if found or a null
*/
public Referee search(String firstName, String lastName) {
//create a local referee variable and assign it to null
Referee referee = null;
//loop through the referees array and check each referee object against the first name and last name parameter
for (Referee ref : referees) {
if (ref.getFirstName().equals(firstName)
&& ref.getLastName().equals(lastName)) {
referee = ref;
break;
}
}
return referee;
}
/**
* Searches referees array using object id.
* @param referee
* @return a referee if found or null.
*/
public Referee search(Referee referee) {
Referee exists = null;
//loop through the referees array checking each Referee object
for (Referee ref : referees) {
//if there is an id match, then assign the local Referee object to the current ref object within the array
if (referee.idMatch(ref)) {
exists = ref;
//if match is found at current referee object, break out the array
break;
}
}
return exists;
}
/**
* Returns a 2D array that is used with the table object in n.gui.Referees
* class.
* @return the referees array in 2D or null if referees is empty.
*/
public Object[][] getRefereesData() {
if (referees != null && referees.length > 0) {
Object[][] refereesData = new Object[referees.length][Referee.FIELD_NAMES.length];
for (int i = 0; i < referees.length; i++) {
Referee referee = referees[i];
refereesData[i][0] = referee.getId();
refereesData[i][1] = referee.getFirstName();
refereesData[i][2] = referee.getLastName();
refereesData[i][3] = referee.getQualification();
refereesData[i][4] = referee.getAllocations();
refereesData[i][5] = referee.getHomeArea();
refereesData[i][6] = referee.getTravelAreas();
}
return refereesData;
} else {
return null;
}
}
/**
* A convenience method to return a referee id which uses overloading to
* delegate a part of the job to another method.
* @param referee
* @return referee id
*/
public String getRefereeId(Referee referee) {
return getRefereeId(referee.getFirstName(),referee.getLastName());
}
/**
* A convenience method that returns a unique referee id.
* @param firstName
* @param lastName
* @return referee id
*/
public String getRefereeId(String firstName,String lastName) {
String initials = firstName.substring(0,1) + lastName.substring(0,1);
int id = 1;
for (Referee referee : referees) {
if (referee.getId().substring(0,2).equals(initials)) {
int refereeId = Integer.parseInt(referee.getId().substring(2,3));
if (refereeId >= id) {
id = refereeId + 1;
}
}
}
return initials + id;
}
/**
* Increases allocation count for the selected employee..
* @param selected
*/
public void increaseRefereeAllocation (Referee[] selected) {
if (selected != null) {
for (int r=0;r<selected.length;r++) {
for (int i=0;i<referees.length;i++) {
if (referees[i].idMatch(selected[r])) {
referees[i].increaseAllocations();
}
}
}
}
}
/**
* Decreases allocation count for the selected employee..
* @param selected
*/
public void decreaseRefereeAllocation (Referee[] selected) {
if (selected != null) {
for (int r=0;r<selected.length;r++) {
for (int i=0;i<referees.length;i++) {
if (referees[i].idMatch(selected[r])) {
referees[i].decreaseAllocations();
}
}
}
}
}
/**
* This method reads in the INPUT_REFEREE_FILE and turns the results into
* an array.
* @return referees
*/
private Referee[] readIn() {
//create a local Referee object list and call on the readIn method to input the contents of the file and store it in the list
List<Referee> refereeList = readIn(DataSource.INPUT_REFEREE_FILE);
//check to ensure the local refereeList has been populated using the contents of the file
if (refereeList != null) {
//instantiate a new local Referee objects array and initialise this to the referee list(by converting this to an array)
// and setting this to the size of the populated referee list size
Referee[] referees = refereeList.toArray(new Referee[refereeList.size()]);
//call the sort method on the referees array
Arrays.sort(referees);
//return the referees array contain Referee objects
return referees;
} else {
//otherwise if the refereeList has not been populated then return null
return null;
}
}
/**
* Reads in filename as specified in INPUT_FILE_NAME and
* return an ArrayList of Referee object or null
* @param filename
* @return referees as ArrayList
*/
public List<Referee> readIn(String filename) {
// a local 'referees' object list is created to store Referee objects
List<Referee> referees = new ArrayList<Referee>();
try {
//instantiate FileReader and Scanner objects and set them to null
FileReader fr = null;
Scanner s = null;
try {
fr = new FileReader(filename);
s = new Scanner(fr);
//create a String array 'line' for each line that is input from the text file - filename
String[] line = null;
// loop through the contents of the file as long as it has a next line
while (s.hasNextLine()) {
// populate the contents of the array by tokenizing each line into separate words
line = s.nextLine().split("[\\s]+");
/*
* .trim() on other than the first and the last token
* would be redundant as .split() removes the
* white spaces between tokens
*/
String id = line[0].trim(); //assign variable id as the first position of the line array
String firstName = line[1]; //assign variable firstName as the second position of the line array
String lastName = line[2]; //assign variable lastName as the third position of the line array
/*instantiate a Qualification object and pass in the fourth position of the line array as a parameter
* which would be the qualification parameter */
Qualification qualification = new Qualification(line[3]);
// parse the fifth position of the line array into an integer and assign it to the variable allocations
int allocations = Integer.parseInt(line[4]);
/* instantiate an Area object and perform a check to see whether the area is North, Central and South,
* then create a new object accordingly based on the check */
Area homeArea = line[5].equals("North") ? new North(true) :
line[5].equals("Central") ? new Central(true) :
line[5].equals("South") ? new South(true) : null;
/* assign variable to travels, north, central and south based on the contents read from the file
* and stored in the line array */
String travels = line[6].trim();
North north = travels.substring(0,1).equals("Y") ? new North(true) : new North();
Central central = travels.substring(1,2).equals("Y") ? new Central(true) : new Central() ;
South south = travels.substring(2,3).equals("Y") ? new South(true) : new South() ;
//instantiate a TravelAreas object and pass in the areas read in from the file as parameters
TravelAreas travelAreas = new TravelAreas(north,central,south);
/* create a new Referee object passing as parameters all the variables created above which were
* read in from the file */
Referee referee = new Referee(id,firstName,lastName
,qualification,allocations,homeArea,travelAreas);
//add the new Referee (referee) object to the referees list
referees.add(referee);
}
} finally { //if the files were opened successfully then close them
if (fr != null) { fr.close(); };
if (s != null) { s.close(); };
}
} catch (FileNotFoundException e) { //if the files were not found then catch this exception and print an error
e.printStackTrace();
} catch (IOException e) { //if there was an error reading the contents from the file then print an error
e.printStackTrace();
}
return referees;
}
/**
* Outputs sorted referees array to OUTPUT_REFEREE_FILE.
*/
public void writeReferees() {
if (referees == null) {
return;
}
Arrays.sort(referees);
try {
// create file writer object
FileWriter fw = null;
try {
// instantiate file writer object
fw = new FileWriter(DataSource.OUTPUT_REFEREE_FILE);
String header = String.format(Referee.FILE_RECORD_FORMAT,
Referee.FIELD_ID,Referee.FIELD_FIRST_NAME
,Referee.FIELD_LAST_NAME,Referee.FIELD_QUALIFICATION
,Referee.FIELD_ALLOCATIONS,Referee.FIELD_HOME_AREA
,Referee.FIELD_TRAVEL_AREA);
fw.write(header + System.lineSeparator());
for (Referee referee : referees) {
fw.write(referee
.printRefereeRecord(Referee.FILE_RECORD_FORMAT)
+ System.lineSeparator());
}
} finally {
if (fw != null)
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Outputs the match report to OUTPUT_MATCH_FILE.
*/
public void writeReport() {
if (matches == null) {
return;
}
try {
FileWriter fw = null;
try {
fw = new FileWriter(DataSource.OUTPUT_MATCH_FILE);
String header = String.format(Match.REPORT_DISPLAY_FORMAT,
Match.FIELD_WEEK,Match.FIELD_GROUP,Match.FIELD_AREA,
Match.FIELD_REFEREE1,Match.FIELD_REFEREE2);
fw.write(header + System.lineSeparator());
for (Match match : matches) {
fw.write(match.toReportString() + System.lineSeparator());
}
} finally {
if (fw != null)
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* A convenience method for printing referees array to the console.
*/
public void printReferees() {
if (referees != null) {
for (Referee r : referees) {
System.out.println(r.toString());
}
} else {
System.out.println("No Referees");
}
}
}
|
package com.imooc.article.mapper;
import com.imooc.my.mapper.MyMapper;
import com.imooc.pojo.Article;
public interface ArticleMapper extends MyMapper<Article> {
} |
import java.util.Scanner;
public class Practice1 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int mid;
int end;
int practice;
double avg;
System.out.print("์ค๊ฐ๊ณ ์ฌ ์ ์๋ฅผ ์
๋ ฅํ์์ค : ");
mid = input.nextInt();
System.out.print("๊ธฐ๋ง๊ณ ์ฌ ์ ์๋ฅผ ์
๋ ฅํ์์ค : ");
end = input.nextInt();
System.out.print("์ค์ต ์ ์๋ฅผ ์
๋ ฅํ์์ค : ");
practice = input.nextInt();
avg = (double)(mid+end+practice)/3;
if (avg>=96)
System.out.println("A+");
else if (avg>=91)
System.out.println("A0");
else if (avg>=86)
System.out.println("B+");
else if (avg>=81)
System.out.println("B0");
else if (avg>=76)
System.out.println("C+");
else if (avg>=71)
System.out.println("C0");
else if (avg>=66)
System.out.println("D+");
else if (avg>=61)
System.out.println("D0");
else
System.out.println("F");
}
}
|
package sort;
import java.util.Random;
/**
* @author leeray
* @version ๅๅปบๆถ้ด๏ผ2019ๅนด3ๆ23ๆฅ ไธๅ11:24:24 <br>
* ๆ่ฟฐ๏ผๆๅ
ฅๆๅบ<br>
*/
public class InsertSort {
public static void main(String[] args) {
int a[] = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = new Random().nextInt(50);
System.out.print(a[i] + "/");
}
Inser_Sort(a, a.length);
System.out.println("///");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "/");
}
}
/**
* ๆๅ
ฅๆๅบ๏ผๅๆฒปๆณ,ๆถ้ดๅคๆๅบฆไธบO(n^2)ใ
*
* @param a:ๅพ
ๆๆฐ็ป
* @param n๏ผ่ฆๆๅบ็ๆๅคง่ๅด
*/
static void Inser_Sort(int[] a, int n) {
for (int i = 0; i < n; i++) {
int ins = a[i];// ไฟๅญ่ฆๆๅ
ฅ็ๆฐๆฎ
int j = i - 1;
while (j >= 0 && ins < a[j]) {
a[j + 1] = a[j];// ๅ็งป
j--;
}
a[j + 1] = ins;//ๆๅ่
พๅบๆฅ็ไฝ็ฝฎ็จไบๆๅ
ฅins
}
}
}
|
package com.example.karam.transportation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class Driver_setting extends AppCompatActivity {
ImageView back_et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_setting);
back_et =(ImageView) findViewById(R.id.back_id);
}
public void back (View v){
Intent i = new Intent(Driver_setting.this,Driver_home_layout.class);
startActivity(i);
}
}
|
package lesson2.hw.acmp;
/**
* ะะปะณะพัะธัะผั_ะธ_ััััะบัััั_ะดะฐะฝะฝัั
_ะฝะฐ_Java.ะะฐะทะพะฒัะนะััั. 24.09.2019 Webinar.
* Teacher: ะคะฐะฝะทะธะปั ะัััะฟะบัะปะพะฒ
* ะฃัะพะบ 1. ะะฑัะธะต ัะฒะตะดะตะฝะธั ะพะฑ ะฐะปะณะพัะธัะผะฐั
ะธ ััััะบัััะฐั
ะดะฐะฝะฝัั
* ะะพะผะฐัะฝัั ัะฐะฑะพัะฐ.
* @author Litvinenko Yuriy
* ะะฐะดะฐัะธ ะฝะฐ http://acmp.ru
* ะขะตะผะฐ. ะะฒัะผะตัะฝัะต ะผะฐััะธะฒั.
* ะะะะะงะ โ802. ะะฐะณะธัะตัะบะธะน ะบะฒะฐะดัะฐั (ะัะตะผั: 1 ัะตะบ. ะะฐะผััั: 16 ะะฑ ะกะปะพะถะฝะพััั: 70%)
* ะะฐะณะธัะตัะบะธะน ะบะฒะฐะดัะฐั - ััะพ ะบะฒะฐะดัะฐัะฝะฐั ัะฐะฑะปะธัะฐ N x N, ะทะฐะฟะพะปะฝะตะฝะฝะฐั N2 ัะธัะปะฐะผะธ ะพั 1 ะดะพ N2 ัะฐะบะธะผ ะพะฑัะฐะทะพะผ,
* ััะพ ััะผะผะฐ ัะธัะตะป ะฒ ะบะฐะถะดะพะน ัััะพะบะต, ะบะฐะถะดะพะผ ััะพะปะฑัะต ะธ ะฝะฐ ะพะฑะตะธั
ะดะธะฐะณะพะฝะฐะปัั
ะพะดะธะฝะฐะบะพะฒะฐ.
* ะัะธ ััะพะผ ัะธัะปะฐ ะฒ ัะฐะฑะปะธัะต ะฝะต ะดะพะปะถะฝั ะฟะพะฒัะพัััััั ะธ ะบะฐะถะดะพะต ะธะท ัะธัะตะป ะพั 1 ะดะพ N^2 ะดะพะปะถะฝะพ ะฒ ะฝะตะน
* ะฟัะธัััััะฒะพะฒะฐัั. ะขัะตะฑัะตััั ะฝะฐะฟะธัะฐัั ะฟัะพะณัะฐะผะผั, ะบะพัะพัะฐั ะฟะพ ะทะฐะดะฐะฝะฝะพะผั N ัััะพะธั ะผะฐะณะธัะตัะบะธะน ะบะฒะฐะดัะฐั.
* ะั
ะพะดะฝัะต ะดะฐะฝะฝัะต:
* ะะพ ะฒั
ะพะดะฝะพะผ ัะฐะนะปะต INPUT.TXT ะทะฐะดะฐะฝะพ ะตะดะธะฝััะฒะตะฝะฝะพะต ะฝะฐัััะฐะปัะฝะพะต
* ัะธัะปะพ N - ัะฐะทะผะตัะฝะพััั ะผะฐะณะธัะตัะบะพะณะพ ะบะฒะฐะดัะฐัะฐ (N โค 1000).
* ะัั
ะพะดะฝัะต ะดะฐะฝะฝัะต:
* ะ ะฒัั
ะพะดะฝะพะน ัะฐะนะป OUTPUT.TXT ะฝะตะพะฑั
ะพะดะธะผะพ ะฒัะฒะตััะธ ะผะฐะณะธัะตัะบะธะน ะบะฒะฐะดัะฐั - ะผะฐััะธัั,
* ัะพััะพัััั ะธะท N ัััะพะบ ะฟะพ N ัะปะตะผะตะฝัะพะฒ ะฒ ะบะฐะถะดะพะน. ะัะปะธ ะฒะฐัะธะฐะฝัะพะฒ ัะตัะตะฝะธั ะฝะตัะบะพะปัะบะพ,
* ัะพ ะผะพะถะฝะพ ะฒัะฒะตััะธ ะปัะฑะพะน. ะ ัะพะผ ัะปััะฐะต, ะบะพะณะดะฐ ัะตัะตะฝะธะต ะฝะต ัััะตััะฒัะตั, ัะปะตะดัะตั ะฒัะฒะตััะธ "Impossible".
* ะัะธะผะตัั:
* 1 >> 1
* 2 >> Impossible
* 3 >> 4 9 2
* 3 5 7
* 8 1 6
* ะคะพัะผะฐะปะธะทะพะฒะฐะฝะฝะฐั ะทะฐะดะฐัะฐ.
*
*/
import java.io.PrintWriter;
import java.util.Scanner;
public class Acmp0802 {
public static void main(String[] args){
int n = 6;
int[][] square = new int[n][n];
int[] lineSums = new int[n];
int count = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
square[i][j] = count++;
}
}
/*for (int i = 0; i < n; i++) {
lineSums[i] = i + 1;
for (int j = 1; j < n / 2; j++) {
lineSums[i] += (j % 2 == 0) ? (n * 2 * j) : (n * 2 * j + 1);
// + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3);
}
// 6 >> 1 .. 36
// 1+12+13+24+25+36=111
// 2+11+14+23+26+35=111
// 3+10+15+22+27+34=111
// 4+ 9+16+21+28+33=111
// 5+ 8+17+20+29+32=111
// 6+ 7+18+19+30+31=111
//
// lineSum = (1) + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3);
// 1 12 13 24 25 36
//int lineSum = (i) + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3) + (n * 2 * 2 + 1);
}*/
/*for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
lineSum = (i) + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3) + (n * 2 * 2 + 1);
}
}*/
//System.out.println(n + ": " + lineSum);
/*Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//ะธะฝะธัะธะธััะตะผ ะฟะตัะตะผะตะฝะฝัั ะฟะตัะธะผะตััะฐ
int perimeter = 0;//ะผะธะฝะธะผะฐะปัะฝัะน ัะฐะทะผะตั ะฟะตัะธะผะตััะฐ ะธะท ะพะดะฝะพะน ะบะปะตัะบะธ
int cellSize = 1;
//ะฟัะธะฝะธะผะฐะตะผ ะบะพะปะธัะตััะฒะพ ะฒัะฟะตะปะตะฝะฝัั
ััะตะตะบ
int num = in.nextInt();
//ะธะฝะธัะธะธััะตะผ ะผะฐััะธะฒ ะดะปั ะบะพะพัะดะธะฝะฐั ััะตะตะบ
int[][] holes = new int[num][2];
//ะฟัะธะฝะธะผะฐะตะผ ะฒ ัะธะบะปะต ะบะพะพัะดะธะฝะฐัั ััะตะตะบ ะธ ะทะฐะฟะพะปะฝัะตะผ ะผะฐััะธะฒ
for (int i = 0; i < holes.length; i++) {
for (int j = 0; j < holes[0].length; j++) {
holes[i][j] = in.nextInt();
}
}
//ะฒััะธัะปัะตะผ ะดะปะธะฝั ะผะฐะบัะธะผะฐะปัะฝะพ ะฒะพะทะผะพะถะฝะพะณะพ ะฟะตัะธะพะดะฐ
perimeter = num * cellSize * 4;
//ะปะธััะฐะตะผ ะผะฐััะธะฒ ััะฐะฒะฝะธะฒะฐะตะผ ัะตะบััะธะน ัะปะตะผะตะฝั
for (int i = 0; i < holes.length; i++) {
//ะปะธััะฐะตะผ ะผะฐััะธะฒ ััะฐะฒะฝะธะฒะฐะตะผ ั ะพััะฐะปัะฝัะผะธ ัะปะตะผะตะฝัะฐะผะธ
for (int j = 0; j < holes.length; j++) {
//ะฟัะพะฒะตััะตะผ ะฝะต ัะฒะพั ะปะธ ััะตะนะบะฐ
if(i != j){
//ะธ ะตััั ะปะธ ัะพัะตะด ัะฒะตัั
ั(ะบะพะปะพะฝะบะธ ัะฐะฒะฝั,
if(holes[i][1] == holes[j][1]) {
//ะฐ ัััะพะบะฐ ะผะตะฝััะต ะฝะฐ 1)
if (holes[i][0] - holes[j][0] == 1) {
//ะตัะปะธ ะฝะตั ัะพัะตะดะฐ, ัะฒะตะปะธัะธะฒะฐะตะผ ะฟะตัะธะผะตัั ะฝะฐ ะฒะตะปะธัะธะฝั ััะพัะพะฝั
perimeter -= cellSize;
}
//ะฟัะพะฒะตััะตะผ ะตััั ะปะธ ัะพัะตะด ัะฝะธะทั(ะบะพะปะพะฝะบะธ ัะฐะฒะฝั, ะฐ ัััะพะบะฐ ะฑะพะปััะต ะฝะฐ 1)
if(holes[j][0] - holes[i][0] == 1){
//ะตัะปะธ ะฝะตั ัะพัะตะดะฐ, ัะฒะตะปะธัะธะฒะฐะตะผ ะฟะตัะธะผะตัั ะฝะฐ ะฒะตะปะธัะธะฝั ััะพัะพะฝั
perimeter -= cellSize;
}
}
//ะธ ะตััั ะปะธ ัะพัะตะด ัะปะตะฒะฐ(ัััะพะบะธ ัะฐะฒะฝั,
if(holes[i][0] == holes[j][0]) {
//ะฐ ะบะพะปะพะฝะบะฐ ะผะตะฝััะต ะฝะฐ 1)
if (holes[i][1] - holes[j][1] == 1) {
//ะตัะปะธ ะฝะตั ัะพัะตะดะฐ, ัะฒะตะปะธัะธะฒะฐะตะผ ะฟะตัะธะผะตัั ะฝะฐ ะฒะตะปะธัะธะฝั ััะพัะพะฝั
perimeter -= cellSize;
}
//ะฟัะพะฒะตััะตะผ ะตััั ะปะธ ัะพัะตะด ัะฟัะฐะฒะฐ(ัััะพะบะธ ัะฐะฒะฝั, ะฐ ะบะพะปะพะฝะบะฐ ะฑะพะปััะต ะฝะฐ 1)
if(holes[j][1] - holes[i][1] == 1){
//ะตัะปะธ ะฝะตั ัะพัะตะดะฐ, ัะฒะตะปะธัะธะฒะฐะตะผ ะฟะตัะธะผะตัั ะฝะฐ ะฒะตะปะธัะธะฝั ััะพัะพะฝั
perimeter -= cellSize;
}
}
}
}
}
out.println(perimeter);
out.flush();*/
}
}
/*
3 >> 4 9 2
* 3 5 7
* 8 1 6
1+9+5=15
2+7+6=15
3+8+4=15
*/
//4 >> 1 .. 16
// 1+16+2+15=34
// 3+14+4+13=34
// 5+12+6+11=34
// 7+10+8+9=34
//05 09 02 __
//03 06 __ __
//__ 01 07 __
//__ 10 __ 08
// 26 ^<26
/*
5 >> 1 .. 25
1+10+11+20+21=63
2+ 9+12+19+22=64
3+ 8+13+18+23=65 average
4+ 7+14+17+24=66
5+ 6+15+16+25=67
1+25+ 6+20+11=63
2+24+ 7+19+12=64
3+23+ 8+18+13=65 average
4+22+ 9+17+14=66
5+21+10+16+15=67
Impossible?
*/
/*
6 >> 1 .. 36
1+12+13+24+25+36=111
2+11+14+23+26+35=111
3+10+15+22+27+34=111
4+ 9+16+21+28+33=111
5+ 8+17+20+29+32=111
6+ 7+18+19+30+31=111
lineSum = (1) + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3);
1 12 13 24 25 36
*/
/*
7 >> 1 .. 49
1+12+13+24+25+36=111
2+11+14+23+26+35=111
3+10+15+22+27+34=111
4+ 9+16+21+28+33=111
5+ 8+17+20+29+32=111
6+ 7+18+19+30+31=111
int lineSum = (1) + (n * 2 * 1) + (n * 2 * 1 + 1) + (n * 2 * 2) + (n * 2 * 2 + 1) + (n * 2 * 3) + (n * 2 * 2 + 1)
1 14 15 28 29 42 43
7: 158
*/
//TODO ะฒัะตะผะตะฝะฝะพ
//out.println("holes.length: " + holes.length);
//out.println("holes[0].length: " + holes[0].length);
//TODO ะฒัะตะผะตะฝะฝะพ
/*for (int[] h : holes) {
for (int c: h) {
out.print(c + " ");
}
out.println();
}*/ |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C1IOtest {
public static void main(String[] args) /*throws IOException*/{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try{
while(true)
{
String name = in.readLine();
if(name.equals("n"))
break;
System.out.println(name);
}
}
catch(IOException e){
}
/* InputStreamReader in = new InputStreamReader(System.in);
try{
while(true)
{
System.out.println("input");
char ch = (char)in.read();
if(ch=='.')break;
System.out.println(ch);
}char p;
while( (p=(char) in.read())!='.')
{
System.out.println("p");
}
}catch(IOException e){
System.out.println(e);
}*/
}
}
|
package kr.ac.kopo.day12.homework;
import java.util.Scanner;
public class GameMeun {
public static int totalWin;
public static int totalLose;
public static int totalDraw;
Scanner sc = new Scanner(System.in);
//๊ฒ์ ์ ํ ๋ฐ ์ ์ฒด ๊ฒ์ ์งํ
public void selectGame() {
System.out.println("๊ฒ์์ ์ ํํ์ธ์");
System.out.println("A. ๊ฐ์๋ฐ์๋ณด\nB. ์ฃผ์ฌ์ ๊ฐ ๋ง์ถ๊ธฐ\nC. ์ข
๋ฃ");
String str = sc.nextLine();
if (str.equals("A") || str.equals("B") || str.equals("C")) {
Game g;
int you;
int result;
switch (str) {
case "A":
g = new ScissorsRockPaper();
you = g.getYourNum();
result = g.startGame(you);
checkResult(result);
break;
case "B":
g = new Dice();
you = g.getYourNum();
result = g.startGame(you);
checkResult(result);
break;
case "C":
System.out.println("๊ฒ์์ ์ข
๋ฃํฉ๋๋ค.\n๋น์ ์ ๊ฒ์ ์ ์ ์ "
+ GameMeun.getTotalWin() + "์น " + GameMeun.getTotalLose()
+ "ํจ " + GameMeun.getTotalDraw() + "๋ฌด์
๋๋ค.");
break;
}
} else {
System.out.println("๋ค์ ์
๋ ฅํ์ธ์");
selectGame();
}
}
//์ฌ์ฉ์์๊ฒ ์ซ์ ๋ฐ๊ธฐ
public int inputInt(String msg) {
System.out.println(msg);
int you = sc.nextInt();
sc.nextLine();
return you;
}
//์นํจ ๊ฒฐ๊ณผ ์ฒดํฌ
private void checkResult(int result) {
if (result == 1) {
System.out.println("You win");
GameMeun.totalWin++;
} else if (result == -1) {
System.out.println("You lose");
GameMeun.totalLose++;
} else if (result == 0) {
System.out.println("Draw");
GameMeun.totalDraw++;
}
selectGame();
}
// getter&setter
public static int getTotalWin() {
return totalWin;
}
public static int getTotalLose() {
return totalLose;
}
public static int getTotalDraw() {
return totalDraw;
}
}
|
package ch.mitti.geometrische_figuren;
import java.awt.geom.*; //Alle Klassen des Geometrie-Pakets
public class Linie extends Figur {
public int xEnde;
public int yEnde;
// Konstruktor
public Linie() {
super(10,10,"black");
this.xEnde=100;
this.yEnde=100;
this.draw();
}
public Linie(int xPosition,int yPosition,int xEnde,int yEnde, String color ) {
super(xPosition, yPosition, color);
this.xEnde=xEnde;
this.yEnde=yEnde;
this.draw();
}
// Dienste
public void draw(){ //mit private und public ausprobieren
Canvas canvas = Canvas.getCanvas();
canvas.draw(this, super.getColor() , "Line", new Line2D.Double(super.getxPosition(), super.getyPosition(), xEnde, yEnde ));
}
}
|
package com.project;
public enum DamageType {
}
|
package pl.edu.wszib.springhelloworld.configurations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
@RestController
@RequestMapping("/Errory")
public class Errory {
@GetMapping
public String test() {
int liczba = new Random().nextInt(3);
if (liczba == 0) throw new RuntimeException1();
else if (liczba == 1) throw new RuntimeException2();
else throw new RuntimeException3();
}
@ExceptionHandler(RuntimeException1.class)
public String exception(){
return "ERROR1";
}
@ExceptionHandler(RuntimeException2.class)
public String exception1(){
return "Error2";
}
@ExceptionHandler(RuntimeException3.class)
public String exception2(){
return "ERROR3";
}
}
|
package edu.weber.cs3230.assignment1.Chart;
import java.util.ArrayList;
/**
* Created by Scott on 9/15/2014.
*/
public class Chart {
private double loanAmmount;
private double interestRate;
private int numYears;
private double monthlyPayment;
private double loanBalance;
private double totalPrinciple;
private double totalInterest;
public double getLoanAmmount() {
return loanAmmount;
}
public void setLoanAmmount(double loanAmmount) {
this.loanAmmount = loanAmmount;
}
public double getInterestRate() {
return interestRate;
}
public void setInterestRate(double interestRate) {
this.interestRate = interestRate;
}
public double getNumYears() {
return numYears;
}
public void setNumYears(int numYears) {
this.numYears = numYears;
}
/**
* Find the total number of payments for the loan in months
* @return number of months of payment
*/
public int totalNumberOfPayments(){
return numYears *12;
}
/**
* Annual interest calc in months
* @return
*/
public double monthlyInterest(){
return (interestRate/12)/100;
}
/**
* find the monthly payment for the loan
* @return
*/
public double calcMonthlyPayment(){
double interest = monthlyInterest();
int numPayments = totalNumberOfPayments();
double subNumber = (double)Math.pow ((1+interest), numPayments);
monthlyPayment = (interest *loanAmmount * subNumber)/(subNumber -1);
return monthlyPayment;
}
public double calcInterestPayment(double balance){
return balance*monthlyInterest();
}
public double calcPriciplePayment(double interestPayment){
return monthlyPayment - interestPayment;
}
public double mortgageBalance(double principlePayment){
return loanBalance = loanBalance - principlePayment;
}
/**
* Format the calc object
* @return
*/
public String buildChart(){
loanBalance = loanAmmount;
double currentPrinciple, currentInterest, currentBalance;
StringBuilder stringChart = new StringBuilder();
for (int i = 0; i < totalNumberOfPayments(); i++) {
currentPrinciple = calcPriciplePayment((calcInterestPayment(loanBalance)));
currentInterest = calcInterestPayment(loanBalance);
currentBalance = (mortgageBalance(calcPriciplePayment(calcInterestPayment(loanBalance))));
totalPrinciple+= currentPrinciple;
totalInterest+=currentInterest;
String numPayments = (String.valueOf(i + 1));
String currentPrinc = (String.valueOf(String.format("\t\t\t$%1$.2f\t\t", (currentPrinciple))));
String currentInt = (String.valueOf(String.format("$%1$.2f\t\t", (currentInterest))));
String totalPrinc = (String.valueOf(String.format("$%1$.2f\t\t\t", (totalPrinciple))));
String totalInt = (String.valueOf(String.format("$%1$.2f\t\t\t\t\t", (totalInterest))));
String currentBal = (String.valueOf(String.format("$%1$.2f\n", (currentBalance))));
stringChart
.append(numPayments)
.append(currentPrinc)
.append(currentInt)
.append(totalPrinc)
.append(totalInt)
.append(currentBal);
}
return stringChart.toString();
}
}
|
package org.apache.helix.controller.changedetector.trimmer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixProperty;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
/**
* An abstract class that contains the common logic to trim HelixProperty by removing unnecessary
* fields.
*/
public abstract class HelixPropertyTrimmer<T extends HelixProperty> {
/**
* The possible Helix-aware field types in the HelixProperty.
*/
enum FieldType {
SIMPLE_FIELD, LIST_FIELD, MAP_FIELD
}
/**
* @param property
* @return a map contains the field keys of all non-trimmable fields that need to be kept.
*/
protected abstract Map<FieldType, Set<String>> getNonTrimmableFields(T property);
/**
* @param property
* @return a copy of the property that has been trimmed.
*/
public abstract T trimProperty(T property);
/**
* Return a ZNrecord as the trimmed copy of the original property.
* Note that we are NOT doing deep copy to avoid performance impact.
* @param originalProperty
*/
protected ZNRecord doTrim(T originalProperty) {
ZNRecord trimmedZNRecord = new ZNRecord(originalProperty.getId());
for (Map.Entry<FieldType, Set<String>> fieldEntry : getNonTrimmableFields(
originalProperty).entrySet()) {
FieldType fieldType = fieldEntry.getKey();
Set<String> fieldKeySet = fieldEntry.getValue();
if (null == fieldKeySet || fieldKeySet.isEmpty()) {
continue;
}
switch (fieldType) {
case SIMPLE_FIELD:
fieldKeySet.stream().forEach(fieldKey -> {
String value = originalProperty.getRecord().getSimpleField(fieldKey);
if (null != value) {
trimmedZNRecord.setSimpleField(fieldKey, value);
}
});
case LIST_FIELD:
fieldKeySet.stream().forEach(fieldKey -> {
List<String> values = originalProperty.getRecord().getListField(fieldKey);
if (null != values) {
trimmedZNRecord.setListField(fieldKey, values);
}
});
case MAP_FIELD:
fieldKeySet.stream().forEach(fieldKey -> {
Map<String, String> valueMap = originalProperty.getRecord().getMapField(fieldKey);
if (null != valueMap) {
trimmedZNRecord.setMapField(fieldKey, valueMap);
}
});
default:
break;
}
}
return trimmedZNRecord;
}
}
|
package com.unistudent.app.unistudentappv2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.unistudent.app.unistudentappv2.adapters.CommentListAdapter;
import com.unistudent.app.unistudentappv2.models.Comment;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CommentListActivity extends AppCompatActivity {
private RecyclerView mRecycleView;
private RecyclerView.LayoutManager mLayoutManager;
private List<Comment> commentList;
private CommentListAdapter commentListAdapter;
String[] names = {"question 1", "question 2", "question 1", "question 2",
"question 1", "question 2", "question 1", "question 2", "question 1", "question 2"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_list);
mRecycleView = (RecyclerView) findViewById(R.id.recycler_view_comment);
if(mRecycleView != null){
mRecycleView.setHasFixedSize(true);
}
mLayoutManager = new LinearLayoutManager(this);
mRecycleView.setLayoutManager(mLayoutManager);
commentList = new ArrayList<>();
for (int i = 0; i< names.length; i++){
Date date = new Date();
Comment comment = new Comment(names[i], date);
this.commentList.add(comment);
}
commentListAdapter = new CommentListAdapter(commentList);
mRecycleView.setAdapter(commentListAdapter);
commentListAdapter.notifyDataSetChanged();
}
} |
package com.rudolfschmidt.amr;
import org.junit.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class IncluderTest {
private static final String templatesDirectory = "src/test/resources/includer";
private static Amr engine;
@BeforeClass
public static void beforeClass() {
engine = new Amr(templatesDirectory, false);
}
@AfterClass
public static void afterClass() {
}
@After
public void after() {
}
@Before
public void before() {
}
@Test
public void a() throws Exception {
test("a");
}
@Test
public void b() throws Exception {
test("b");
}
@Test
public void c() throws Exception {
test("c");
}
private void test(String dir) throws IOException {
final String expected = new String(Files.readAllBytes(Paths.get(templatesDirectory, dir, "out.html")));
final String actual = engine.render(dir + "/in.html");
assertEquals(format(expected), actual);
}
private static String format(String html) {
return html.replaceAll("(?<=>)\\s+?(?=<)", "");
}
} |
package FirstProject.src;
public class Child extends Parent{
public void displayMessage(){
System.out.println("displayMessage() method of Child invoked");
}
}
|
package com.micHon.messager;
import com.micHon.forecast.WeatherForecast;
public class TVNews implements Observer {
public void updateForecast(WeatherForecast weatherForecast) {
System.out.println("TV News: Temp: " + weatherForecast.getTemperature() + " Pressure: " + weatherForecast.getPressure());
}
}
|
/**
* The MIT License (MIT)
* Copyright (c) 2012-present ้ญ่ฝฏ็งๆ(mingsoft.net)
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.mingsoft.cms.action;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.base.util.SqlInjectionUtil;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.cms.bean.ContentBean;
import net.mingsoft.cms.biz.ICategoryBiz;
import net.mingsoft.cms.biz.IContentBiz;
import net.mingsoft.cms.entity.CategoryEntity;
import net.mingsoft.cms.entity.ContentEntity;
import net.mingsoft.mdiy.biz.IModelBiz;
import net.mingsoft.mdiy.entity.ModelEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ๆ็ซ ็ฎก็ๆงๅถๅฑ
* @author ้ญ้ฃๅผๅๅข้
* ๅๅปบๆฅๆ๏ผ2019-11-28 15:12:32<br/>
* ๅๅฒไฟฎ่ฎข๏ผ<br/>
*/
@Api(tags={"ๅ็ซฏ-ๅ
ๅฎนๆจกๅๆฅๅฃ"})
@Controller("cmsContentAction")
@RequestMapping("/${ms.manager.path}/cms/content")
public class ContentAction extends BaseAction {
/**
* ๆณจๅ
ฅๆ็ซ ไธๅกๅฑ
*/
@Autowired
private IContentBiz contentBiz;
@Autowired
private ICategoryBiz categoryBiz;
@Resource(name="mdiyModelBizImpl")
private IModelBiz modelBiz;
/**
* ่ฟๅไธป็้ขindex
*/
@ApiIgnore
@GetMapping("/index")
public String index(){
return "/cms/content/index";
}
/**
* ่ฟๅไธป็้ขmain
*/
@ApiIgnore
@GetMapping("/main")
public String main(){
return "/cms/content/main";
}
/**
* ๆฅ่ฏขๆ็ซ ๅ่กจ
* @param content ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "ๆฅ่ฏขๆ็ซ ๅ่กจๆฅๅฃ")
@ApiImplicitParams({
@ApiImplicitParam(name = "contentTitle", value = "ๆ็ซ ๆ ้ข", required =false,paramType="query"),
@ApiImplicitParam(name = "categoryId", value = "ๆๅฑๆ ็ฎ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentType", value = "ๆ็ซ ็ฑปๅ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDisplay", value = "ๆฏๅฆๆพ็คบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentAuthor", value = "ๆ็ซ ไฝ่
", required =false,paramType="query"),
@ApiImplicitParam(name = "contentSource", value = "ๆ็ซ ๆฅๆบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDatetime", value = "ๅๅธๆถ้ด", required =false,paramType="query"),
})
@RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
@RequiresPermissions("cms:content:view")
public ResultData list(@ModelAttribute @ApiIgnore ContentBean content) {
// ๆฃๆฅSQLๆณจๅ
ฅ
SqlInjectionUtil.filterContent(content.getCategoryId());
BasicUtil.startPage();
List contentList = contentBiz.queryContent(content);
return ResultData.build().success(new EUListBean(contentList,(int) BasicUtil.endPage(contentList).getTotal()));
}
/**
* ่ฟๅ็ผ่พ็้ขcontent_form
*/
@GetMapping("/form")
public String form(@ModelAttribute ContentEntity content, ModelMap model){
model.addAttribute("appId", BasicUtil.getApp().getAppId());
return "/cms/content/form";
}
/**
* ่ทๅๆ็ซ
* @param content ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "่ทๅๆ็ซ ่ฏฆๆ
ๆฅๅฃ")
@ApiImplicitParam(name = "id", value = "็ผๅท", required =true,paramType="query")
@GetMapping("/get")
@ResponseBody
@RequiresPermissions("cms:content:view")
public ResultData get(@ModelAttribute @ApiIgnore ContentEntity content){
if(content.getId()==null) {
return ResultData.build().error();
}
ContentEntity _content = contentBiz.getById(content.getId());
return ResultData.build().success(_content);
}
/**
* ่ทๅๆ็ซ
* @param content ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "ๆ นๆฎๅฐ้ข่ทๅๆ็ซ ๅ่กจๆฅๅฃ")
@ApiImplicitParam(name = "categoryId", value = "ๅ็ฑป็ผๅท", required =true,paramType="query")
@GetMapping("/getFromFengMian")
@ResponseBody
public ResultData getFromFengMian(@ModelAttribute @ApiIgnore ContentEntity content){
if(content.getCategoryId() == null) {
return ResultData.build().error();
}
List<ContentEntity> list = contentBiz.lambdaQuery().eq(ContentEntity::getCategoryId, content.getCategoryId()).list();
if (list.size() > 1) {
LOG.error("่ทๅๅฐ้ขๆ็ซ ๅผๅธธ");
}
return ResultData.build().success(list.size() > 0 ? list.get(0) : null);
}
/**
* ไฟๅญๆ็ซ
* @param content ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "ไฟๅญๆ็ซ ๅ่กจๆฅๅฃ")
@ApiImplicitParams({
@ApiImplicitParam(name = "contentTitle", value = "ๆ็ซ ๆ ้ข", required =true,paramType="query"),
@ApiImplicitParam(name = "categoryId", value = "ๆๅฑๆ ็ฎ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentType", value = "ๆ็ซ ็ฑปๅ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDisplay", value = "ๆฏๅฆๆพ็คบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentAuthor", value = "ๆ็ซ ไฝ่
", required =false,paramType="query"),
@ApiImplicitParam(name = "contentSource", value = "ๆ็ซ ๆฅๆบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDatetime", value = "ๅๅธๆถ้ด", required =true,paramType="query"),
@ApiImplicitParam(name = "contentSort", value = "่ชๅฎไน้กบๅบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentImg", value = "ๆ็ซ ็ผฉ็ฅๅพ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDescription", value = "ๆ่ฟฐ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentKeyword", value = "ๅ
ณ้ฎๅญ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDetails", value = "ๆ็ซ ๅ
ๅฎน", required =false,paramType="query"),
@ApiImplicitParam(name = "contentUrl", value = "ๆ็ซ ่ทณ่ฝฌ้พๆฅๅฐๅ", required =false,paramType="query"),
})
@PostMapping("/save")
@ResponseBody
@LogAnn(title = "ไฟๅญๆ็ซ ", businessType = BusinessTypeEnum.INSERT)
@RequiresPermissions("cms:content:save")
public ResultData save(@ModelAttribute @ApiIgnore ContentEntity content) {
//้ช่ฏ็ผฉ็ฅๅพๅๆฐๅผๆฏๅฆๅๆณ
if (content.getContentImg()==null || !content.getContentImg().matches("^\\[.{1,}]$")){
content.setContentImg("");
}
//้ช่ฏๆ็ซ ๆ ้ข็ๅผๆฏๅฆๅๆณ
if(StringUtil.isBlank(content.getContentTitle())){
return ResultData.build().error(getResString("err.empty", this.getResString("content.title")));
}
if(!StringUtil.checkLength(content.getContentTitle()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.title"), "0", "200"));
}
if(!StringUtil.checkLength(content.getContentAuthor()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.author"), "0", "200"));
}
if(!StringUtil.checkLength(content.getContentSource()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.source"), "0", "200"));
}
//้ช่ฏๅๅธๆถ้ด็ๅผๆฏๅฆๅๆณ
if(StringUtil.isBlank(content.getContentDatetime())){
return ResultData.build().error(getResString("err.empty", this.getResString("content.datetime")));
}
contentBiz.save(content);
return ResultData.build().success(content);
}
/**
* @param contents ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "ๆน้ๅ ้คๆ็ซ ๅ่กจๆฅๅฃ")
@ApiImplicitParams({
@ApiImplicitParam(name = "contents", value = "ๆ็ซ ้ๅ", allowMultiple = true, dataType = "ContentEntity", required = true)
})
@PostMapping("/delete")
@ResponseBody
@LogAnn(title = "ๅ ้คๆ็ซ ", businessType = BusinessTypeEnum.DELETE)
@RequiresPermissions("cms:content:del")
public ResultData delete(@RequestBody List<ContentEntity> contents) {
List<String> ids = new ArrayList<>();
for(int i = 0;i<contents.size();i++){
ids.add(contents.get(i).getId());
//่ทๅๆ ็ฎๅฎไฝ
CategoryEntity categoryEntity = categoryBiz.getById(contents.get(i).getCategoryId());
//ๅฆๆๆ ็ฎ็ปๅฎ็ๆจกๅIDไธบ็ฉบ
if (StringUtils.isBlank(categoryEntity.getMdiyModelId())){
continue;
}
//่ทๅๅฐ้
็ฝฎๆจกๅๅฎไฝ
ModelEntity modelEntity = modelBiz.getById(categoryEntity.getMdiyModelId());
//ๅ ้คๆจกๅ่กจ็ๆฐๆฎ
Map<String, String> map = new HashMap<>();
map.put("link_id", contents.get(i).getId());
modelBiz.deleteBySQL(modelEntity.getModelTableName(), map);
}
contentBiz.removeByIds(ids);
return ResultData.build().success();
}
/**
* ๆดๆฐๆ็ซ ๅ่กจ
* @param content ๆ็ซ ๅฎไฝ
*/
@ApiOperation(value = "ๆดๆฐๆ็ซ ๅ่กจๆฅๅฃ")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "็ผๅท", required =true,paramType="query"),
@ApiImplicitParam(name = "contentTitle", value = "ๆ็ซ ๆ ้ข", required =true,paramType="query"),
@ApiImplicitParam(name = "categoryId", value = "ๆๅฑๆ ็ฎ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentType", value = "ๆ็ซ ็ฑปๅ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDisplay", value = "ๆฏๅฆๆพ็คบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentAuthor", value = "ๆ็ซ ไฝ่
", required =false,paramType="query"),
@ApiImplicitParam(name = "contentSource", value = "ๆ็ซ ๆฅๆบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDatetime", value = "ๅๅธๆถ้ด", required =true,paramType="query"),
@ApiImplicitParam(name = "contentSort", value = "่ชๅฎไน้กบๅบ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentImg", value = "ๆ็ซ ็ผฉ็ฅๅพ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDescription", value = "ๆ่ฟฐ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentKeyword", value = "ๅ
ณ้ฎๅญ", required =false,paramType="query"),
@ApiImplicitParam(name = "contentDetails", value = "ๆ็ซ ๅ
ๅฎน", required =false,paramType="query"),
@ApiImplicitParam(name = "contentUrl", value = "ๆ็ซ ่ทณ่ฝฌ้พๆฅๅฐๅ", required =false,paramType="query"),
})
@PostMapping("/update")
@ResponseBody
@LogAnn(title = "ๆดๆฐๆ็ซ ", businessType = BusinessTypeEnum.UPDATE)
@RequiresPermissions("cms:content:update")
public ResultData update(@ModelAttribute @ApiIgnore ContentEntity content) {
//้ช่ฏ็ผฉ็ฅๅพๅๆฐๅผๆฏๅฆๅๆณ
if (content.getContentImg()==null || !content.getContentImg().matches("^\\[.{1,}]$")){
content.setContentImg("");
}
//้ช่ฏๆ็ซ ๆ ้ข็ๅผๆฏๅฆๅๆณ
if(StringUtil.isBlank(content.getContentTitle())){
return ResultData.build().error(getResString("err.empty", this.getResString("content.title")));
}
if(!StringUtil.checkLength(content.getContentTitle()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.title"), "0", "200"));
}
if(!StringUtil.checkLength(content.getContentAuthor()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.author"), "0", "200"));
}
if(!StringUtil.checkLength(content.getContentSource()+"", 0, 200)){
return ResultData.build().error(getResString("err.length", this.getResString("content.source"), "0", "200"));
}
//้ช่ฏๅๅธๆถ้ด็ๅผๆฏๅฆๅๆณ
if(StringUtil.isBlank(content.getContentDatetime())){
return ResultData.build().error(getResString("err.empty", this.getResString("content.datetime")));
}
contentBiz.saveOrUpdate(content);
return ResultData.build().success(content);
}
}
|
package org.point85.domain.dto;
import org.point85.domain.proficy.ProficySource;
public class ProficySourceDto extends CollectorDataSourceDto {
private Integer uaaHttpPort;
private Boolean validateCertificate;
private Integer httpsPort;
public ProficySourceDto(ProficySource source) {
super(source);
this.uaaHttpPort = source.getUaaHttpPort();
this.validateCertificate = source.getValidateCertificate();
this.httpsPort = source.getHttpsPort();
}
public Integer getUaaHttpPort() {
return uaaHttpPort;
}
public void setUaaHttpPort(Integer uaaHttpPort) {
this.uaaHttpPort = uaaHttpPort;
}
public Boolean getValidateCertificate() {
return validateCertificate;
}
public void setValidateCertificate(Boolean validateCertificate) {
this.validateCertificate = validateCertificate;
}
public Integer getHttpsPort() {
return httpsPort;
}
public void setHttpsPort(Integer httpsPort) {
this.httpsPort = httpsPort;
}
}
|
package com.gxtc.huchuan.data;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.huchuan.bean.ChooseClassifyBean;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.MineApi;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.seriesclassify.SeriesClassifyContract;
import java.util.HashMap;
import java.util.List;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Describe:
* Created by ALing on 2017/3/29 .
*/
public class SeriesClassifyRepository extends BaseRepository implements SeriesClassifyContract.Source {
@Override
public void destroy() {
}
@Override
public void getChatSeriesTypeList(HashMap<String, String> map, ApiCallBack<List<ChooseClassifyBean>> callBack) {
addSub(MineApi.getInstance().getChatSeriesTypeList(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<ChooseClassifyBean>>>(callBack)));
}
@Override
public void addSeriesClassify(HashMap<String, String> map, ApiCallBack<List<ChooseClassifyBean>> callBack) {
addSub(MineApi.getInstance().saveChatSeriesType(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<ChooseClassifyBean>>>(callBack)));
}
@Override
public void editClassifyName(HashMap<String, String> map, ApiCallBack<List<ChooseClassifyBean>> callBack) {
addSub(MineApi.getInstance().saveChatSeriesType(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<ChooseClassifyBean>>>(callBack)));
}
@Override
public void delSeriseClassify(HashMap<String, String> map, ApiCallBack<List<ChooseClassifyBean>> callBack) {
addSub(MineApi.getInstance().deleteChatSeriesType(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<ChooseClassifyBean>>>(callBack)));
}
}
|
package com.example.jpm.offthestreets.ui;
import android.Manifest;
import android.content.pm.PackageManager;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.jpm.offthestreets.R;
import com.example.jpm.offthestreets.model.HomelessShelter;
import com.example.jpm.offthestreets.model.ShelterCollection;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Boolean mLocationPermissionsGranted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private Spinner spGender;
private Spinner spAgeRange;
private EditText etShelterName;
ShelterCollection shelter = ShelterCollection.INSTANCE;
public HomelessShelterListActivity list = new HomelessShelterListActivity();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
getLocationPermission();
spGender = findViewById(R.id.spinnerGender);
String[] genders = {"", "Men", "Women", "Both"};
ArrayAdapter<String> gendersAdapter = new ArrayAdapter<String>(this,
R.layout.support_simple_spinner_dropdown_item, genders);
spGender.setAdapter(gendersAdapter);
spAgeRange = findViewById(R.id.spinnerAgeRange);
String[] ageRanges = {"", "Families with newborns", "Children", "Young Adults", "Anyone"};
ArrayAdapter<String> ageAdapter = new ArrayAdapter<String>(this,
R.layout.support_simple_spinner_dropdown_item, ageRanges);
spAgeRange.setAdapter(ageAdapter);
etShelterName = findViewById(R.id.etShelterName);
}
private void initMap(){
Log.d("TAG", "initmap is ready");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapButton);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onMapReady: on map ready");
mMap = googleMap;
//Adds pin based on lat and lon
LatLng Atl = new LatLng(33.777175,-84.396543);
//Displays data when clicked
mMap.addMarker(new MarkerOptions().position(Atl).title("Atlanta"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Atl));
}
private void getLocationPermission(){
Log.d("TAG", "getLocationPermissions Ready");
String [] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
}
else{
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d("TAG", "OnRequestPermissions called");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i <grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d("TAG", "onRequestPermission Failed");
return;
}
}
Log.d("TAG", "onRequestPermission Granted");
mLocationPermissionsGranted = true;
// initialize map
initMap();
}
}
}
}
// private void getDeviceLocation(){
// Log.d("TAG", "get device location: getting current device location");
//
// }
}
|
package formularios;
import java.awt.Color;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.table.DefaultTableModel;
public class ModeloTabla extends DefaultTableModel {//mostrarรก las tablas
public ModeloTabla(ResultSet rs) {
try {
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();//con este meteodo sabemos el numero de columnas que encesitamos.
//Hacemos un bucle recorriendo las col de la bbdd
for (int i = 1; i <= cols; i++) {
addColumn(rsmd.getColumnName(i));
}
while(rs.next()) {
//irรก creando una fila en esta tabla con los datos
Object[] row = new Object[cols];//array para con elnumero de columnas que esta en cols
for(int i = 1; i <= cols; i++) {
//Metemos cada eemento en una columna de esta fila
row [i - 1] = rs.getObject(i);//el primer elemento que guarde serรก en i - 1, osea 0. Sino darรก indexautobound exception porque terminaria antes que el array
}
addRow(row);
UIManager.put("Table.gridColor", new ColorUIResource(Color.gray));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean isCellEditable(int row, int column) {//evitamos que la tabla sea editable
return false;
}
}
|
package net.xiaolanglang.web.exception.account;
/**
* Token้ช่ฏๅคฑ่ดฅ
* Created by gaoyang on 14/11/26.
*/
public class TokenErrorException extends Exception {
}
|
package com.zantong.mobilecttx.car.fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.umeng.analytics.MobclickAgent;
import com.zantong.mobilecttx.R;
import com.zantong.mobilecttx.base.fragment.BaseExtraFragment;
import com.zantong.mobilecttx.common.Config;
import com.zantong.mobilecttx.common.PublicData;
import com.zantong.mobilecttx.utils.rsa.RSAUtils;
import com.zantong.mobilecttx.weizhang.activity.ViolationResultAcitvity;
import com.zantong.mobilecttx.weizhang.dto.ViolationDTO;
import butterknife.Bind;
import butterknife.OnClick;
/**
* ๅทฒ็ป็ปๅฎ็่ฝฆ่พ
*/
@SuppressLint("ValidFragment")
public class BindCarFragment extends BaseExtraFragment {
String mCarNum;
String mCarType;
String mEngineNum;
String times;
String money;
String points;
public BindCarFragment() {
}
@SuppressLint("ValidFragment")
public BindCarFragment(String carnum, String cartype, String enginenum, String times, String money, String points) {
this.mCarNum = carnum;
this.mCarType = cartype;
this.mEngineNum = enginenum;
this.times = times;
this.money = money;
this.points = points;
}
@Bind(R.id.bindcar_card)
TextView mCard;
@Bind(R.id.fragment_bindercar_amt)
TextView mAmt;
@Bind(R.id.fragment_bindercar_cent)
TextView mCent;
@Bind(R.id.fragment_bindercar_count)
TextView mCount;
@Bind(R.id.fragment_bindcar_layout)
View mFragmentLayout;
@Override
protected int getLayoutResId() {
return R.layout.main_fragment_bindcar;
}
@Override
public void initView(View view) {
}
@Override
public void initData() {
mCard.setText(mCarNum);
mCent.setText(points);
mCount.setText(times);
mAmt.setText(money);
// if (!times.equals("0")){
// mAmt.setTextColor(getResources().getColor(R.color.red));
// mCent.setTextColor(getResources().getColor(R.color.red));
// mCount.setTextColor(getResources().getColor(R.color.red));
// }
}
@OnClick(R.id.fragment_bindcar_layout)
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.fragment_bindcar_layout:
MobclickAgent.onEvent(this.getActivity(), Config.getUMengID(1));
PublicData.getInstance().mHashMap.put("IllegalViolationName", mCarNum);
PublicData.getInstance().mHashMap.put("carnum", mCarNum);
PublicData.getInstance().mHashMap.put("enginenum", mEngineNum);
PublicData.getInstance().mHashMap.put("carnumtype", mCarType);
ViolationDTO dto = new ViolationDTO();
dto.setCarnum(RSAUtils.strByEncryption(mCarNum, true));
dto.setEnginenum(RSAUtils.strByEncryption(mEngineNum, true));
dto.setCarnumtype(mCarType);
Intent intent = new Intent(this.getActivity(), ViolationResultAcitvity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("params", dto);
intent.putExtras(bundle);
intent.putExtra("plateNum", mCarNum);
startActivity(intent);
break;
}
}
}
|
/*
* 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 livraria.gui;
import livraria.bo.ReservaBO;
import livraria.bo.Formulario;
import livraria.gui.tablemodel.ReservaTableModel;
import livraria.vo.Reserva;
/**
*
* @author Nilliam
*/
public class ConReservaView extends javax.swing.JDialog {
private ReservaBO reservaBO;
private boolean isJanela;
/**
* Creates new form Login
*/
public ConReservaView(java.awt.Frame parent, boolean modal, boolean isJanela) {
super(parent, modal);
initComponents();
Formulario.fixLocation(this);
this.reservaBO = new ReservaBO();
this.isJanela = isJanela;
lblLegenda.setVisible(isJanela);
populaTb();
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tbDados = new javax.swing.JTable();
btnDelete = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnNovo = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
jLabel18 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
lblLegenda = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Consulta de Reservas");
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setLayout(null);
tbDados.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tbDados.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
editar(evt);
}
});
jScrollPane1.setViewportView(tbDados);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(20, 20, 530, 370);
btnDelete.setBackground(new java.awt.Color(255, 255, 255));
btnDelete.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/livraria/image/dlt.png"))); // NOI18N
btnDelete.setBorder(null);
btnDelete.setContentAreaFilled(false);
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
jPanel1.add(btnDelete);
btnDelete.setBounds(160, 405, 40, 43);
btnEdit.setBackground(new java.awt.Color(255, 255, 255));
btnEdit.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/livraria/image/pen-small.png"))); // NOI18N
btnEdit.setBorder(null);
btnEdit.setContentAreaFilled(false);
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
jPanel1.add(btnEdit);
btnEdit.setBounds(90, 405, 43, 43);
btnNovo.setBackground(new java.awt.Color(255, 255, 255));
btnNovo.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/livraria/image/add.png"))); // NOI18N
btnNovo.setBorder(null);
btnNovo.setContentAreaFilled(false);
btnNovo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNovoActionPerformed(evt);
}
});
jPanel1.add(btnNovo);
btnNovo.setBounds(20, 405, 40, 43);
btnSair.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
btnSair.setForeground(new java.awt.Color(102, 102, 102));
btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/livraria/image/exit_icon.png"))); // NOI18N
btnSair.setBorder(null);
btnSair.setContentAreaFilled(false);
btnSair.setVerticalAlignment(javax.swing.SwingConstants.TOP);
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
jPanel1.add(btnSair);
btnSair.setBounds(500, 405, 48, 40);
jLabel18.setFont(new java.awt.Font("Verdana", 1, 10)); // NOI18N
jLabel18.setForeground(new java.awt.Color(102, 102, 102));
jLabel18.setText("Sair");
jPanel1.add(jLabel18);
jLabel18.setBounds(520, 450, 30, 14);
jLabel7.setFont(new java.awt.Font("Verdana", 1, 10)); // NOI18N
jLabel7.setForeground(new java.awt.Color(102, 102, 102));
jLabel7.setText("Excluir");
jPanel1.add(jLabel7);
jLabel7.setBounds(162, 450, 40, 14);
jLabel8.setFont(new java.awt.Font("Verdana", 1, 10)); // NOI18N
jLabel8.setForeground(new java.awt.Color(102, 102, 102));
jLabel8.setText("Novo");
jPanel1.add(jLabel8);
jLabel8.setBounds(25, 450, 30, 14);
jLabel9.setFont(new java.awt.Font("Verdana", 1, 10)); // NOI18N
jLabel9.setForeground(new java.awt.Color(102, 102, 102));
jLabel9.setText("Editar");
jPanel1.add(jLabel9);
jLabel9.setBounds(93, 450, 34, 14);
lblLegenda.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
lblLegenda.setForeground(new java.awt.Color(51, 51, 51));
lblLegenda.setText("Legenda: Duplo clique para selecionar o registro.");
jPanel1.add(lblLegenda);
lblLegenda.setBounds(20, 480, 290, 15);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
excluir();
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int index;
if ((index = tbDados.getSelectedRow()) != -1) {
reservaBO.setSelected(index);
editar();
} else {
Formulario.alertar("Selecione o registro!");
}
}//GEN-LAST:event_btnEditActionPerformed
private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
novo();
}//GEN-LAST:event_btnNovoActionPerformed
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
dispose();
}//GEN-LAST:event_btnSairActionPerformed
private void editar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editar
if (evt.getClickCount() == 2) {
handle();
}
}//GEN-LAST:event_editar
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnNovo;
private javax.swing.JButton btnSair;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblLegenda;
private javax.swing.JTable tbDados;
// End of variables declaration//GEN-END:variables
private void populaTb() {
tbDados.setModel(new ReservaTableModel(reservaBO.getAll()));
}
private void handle() {
int index;
if ((index = tbDados.getSelectedRow()) != -1) {
reservaBO.setSelected(index);
if (isJanela) {
dispose();
} else {
editar();
}
} else {
Formulario.alertar("Selecione o registro!");
}
}
private void excluir() {
int index;
if ((index = tbDados.getSelectedRow()) != -1) {
if (reservaBO.removeSelected(index)) {
Formulario.alertar("Registro excluรญdo com sucesso!");
populaTb();
} else {
Formulario.alertar("Falha ao excluir registro!");
}
} else {
Formulario.alertar("Selecione o registro a excluir!");
}
}
private void novo() {
reservaBO.setUpdate(false);
CadReservaView cadReservaView = new CadReservaView(null, true, reservaBO);
populaTb();
}
public Reserva getSelected() {
return reservaBO.getReserva();
}
private void editar() {
reservaBO.setUpdate(true);
new CadReservaView(null, true, reservaBO);
populaTb();
}
}
|
/*
* Copyright 2002-2022 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.transaction;
/**
* Exception that represents a transaction failure caused by a heuristic
* decision on the side of the transaction coordinator.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 17.03.2003
*/
@SuppressWarnings("serial")
public class HeuristicCompletionException extends TransactionException {
/**
* Unknown outcome state.
*/
public static final int STATE_UNKNOWN = 0;
/**
* Committed outcome state.
*/
public static final int STATE_COMMITTED = 1;
/**
* Rolledback outcome state.
*/
public static final int STATE_ROLLED_BACK = 2;
/**
* Mixed outcome state.
*/
public static final int STATE_MIXED = 3;
public static String getStateString(int state) {
return switch (state) {
case STATE_COMMITTED -> "committed";
case STATE_ROLLED_BACK -> "rolled back";
case STATE_MIXED -> "mixed";
default -> "unknown";
};
}
/**
* The outcome state of the transaction: have some or all resources been committed?
*/
private final int outcomeState;
/**
* Constructor for HeuristicCompletionException.
* @param outcomeState the outcome state of the transaction
* @param cause the root cause from the transaction API in use
*/
public HeuristicCompletionException(int outcomeState, Throwable cause) {
super("Heuristic completion: outcome state is " + getStateString(outcomeState), cause);
this.outcomeState = outcomeState;
}
/**
* Return the outcome state of the transaction state,
* as one of the constants in this class.
* @see #STATE_UNKNOWN
* @see #STATE_COMMITTED
* @see #STATE_ROLLED_BACK
* @see #STATE_MIXED
*/
public int getOutcomeState() {
return this.outcomeState;
}
}
|
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class CreeperWatcher extends InsentientWatcher
{
public CreeperWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isIgnited()
{
return (boolean) getData(MetaIndex.CREEPER_IGNITED);
}
public boolean isPowered()
{
return (boolean) getData(MetaIndex.CREEPER_POWERED);
}
public void setIgnited(boolean ignited)
{
setData(MetaIndex.CREEPER_IGNITED, ignited);
sendData(MetaIndex.CREEPER_IGNITED);
}
public void setPowered(boolean powered)
{
setData(MetaIndex.CREEPER_POWERED, powered);
sendData(MetaIndex.CREEPER_POWERED);
}
}
|
package rso.dfs.dummy.server;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TServer.Args;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import rso.dfs.dummy.generated.NamingService;
/**
* @author Adam Papros <adam.papros@gmail.com>
*
* */
public class NameServer {
static NameHandler handler;
static NamingService.Processor procesor;
static final int portNumber = 9090;
public static void main(String[] args) {
try {
handler = new NameHandler();
procesor = new NamingService.Processor(handler);
Runnable simple = new Runnable() {
@Override
public void run() {
simple(procesor);
}
};
new Thread(simple).start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void simple(NamingService.Processor processor) {
try {
TServerTransport serverTransport = new TServerSocket(portNumber);
TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
System.out.println("Starting Naming server...");
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package controliteration;
public class PIValue {
private static final String PI_POET = "Nem a rรฉgi s durva kรถzelรญtรฉs,\n" +
"Mi szรณtรณl szรณig รญgy kijรถn\n" +
"Betลฑiket szรกmlรกlva.\n" +
"Ludolph eredmรฉnye mรกr,\n" +
"Ha itt vรฉgezzรผk hรบsz jegyen.\n" +
"De rendre kijล mรฉg tรญz pontosan,\n" +
"Azt is bรญzvรกst รญgรฉrhetem.\n";
public String getPIValue() {
String piValue = "";
int counter = 0;
for (int i = 0; i < PI_POET.length(); i++) {
if (Character.isAlphabetic(PI_POET.charAt(i))) {
counter++;
} else {
piValue += (piValue.length() == 1 ? "," : "") + (counter > 0 ? counter : "");
counter = 0;
}
}
return piValue;
}
}
|
package com.example.student.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class XuLySVActivity extends AppCompatActivity {
EditText edtma, edtten;
Spinner spmon;
ArrayList<SinhVien> arrSv;
public static final int GOITRALAI=200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xu_ly_sv);
anhxa();
Intent insv = getIntent();
Intent intent = getIntent();
if (intent.getSerializableExtra("SINHVIENSUA") != null) {
SinhVien sv = (SinhVien) insv.getSerializableExtra("SINHVIENSUA");
edtma.setText(sv.getMa());
edtten.setText(sv.getTen());
//spmon.setSelection(sv.getMon());
//spmon.getSelectedItemPosition(Integer.parseInt(sv.getMon()));
}
}
private void anhxa() {
edtma = findViewById(R.id.edt_ma);
edtten = findViewById(R.id.edt_ten);
spmon = findViewById(R.id.sp_mon);
}
public void Sua(View view) {
Intent insv = getIntent();
SinhVien sv = (SinhVien) insv.getSerializableExtra("SINHVIENSUA");
//SinhVienModel.updateSinhVien(R.drawable.ic_flag_thailand, sv.setTen(edtten.getText().toString()),sv.setMon(spmon.getSelectedItem().toString()));
sv.setTen(edtten.getText().toString());
sv.setMon(spmon.getSelectedItem().toString());
sv.setImg_id(R.drawable.ic_flag_singapore);
Toast.makeText(this,"Cแบญp nhแบญt thร nh cรดng!",Toast.LENGTH_SHORT).show();
Intent inTraLai = new Intent();
setResult(GOITRALAI,inTraLai );
finish();
}
}
|
package org.vincent.event;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* @author PengRong
* @package org.vincent.event
* @ClassName StartUp.java
* @date 2019/8/7 - 20:41
* @ProjectName JavaAopLearning
* @Description: ไบไปถ็ๅฌ่
๏ผไบไปถๆถ่ดน่
ๅฟ
้กปๆณจๅไธบSpring Bean
*/
@Component
public class StartUp implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println(" start Spring App");
}
}
|
package functionalTesting.companyManagement.independently.jobList;
import functionalTesting.companyManagement.independently.companyList.AddCompanyTest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import pageObject.Login;
import utility.Constant;
import utility.ExcelUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @Author by XuLiang
* @Date 2017/12/14 9:38
* @Email stanxu526@gmail.com
*/
public class AddJobTest {
static {
System.setProperty("webdriver.gecko.driver","C:\\SeleniumGecko\\geckodriver.exe");
}
private final static Log log = LogFactory.getLog(AddCompanyTest.class);
WebDriverWait wait = new WebDriverWait(Login.driver, 10);
@Test
public void addJob(){
Login.login("http://10.103.0.4:8080/web/user/login");
String companyName = null;
String departmentName = null;
String jobTitle = null;
String detailsOfJob = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTimestamp = sdf.format(new Date());
try {
ExcelUtils.setExcelFile(Constant.Path_TestData,Constant.File_TestData);
//This is to get the values from Excel sheet
List<String> parameterList = ExcelUtils.getParametersViaCaseName("TrainScheduling_ltrailways_addJob", 9);
if(parameterList != null && parameterList.size() > 0){
companyName = parameterList.get(0);
departmentName = parameterList.get(1);
jobTitle = parameterList.get(2);
detailsOfJob = parameterList.get(3);
}else {
log.info("can not get correct parameters from excel !");
}
} catch (Exception e) {
e.printStackTrace();
}
jobTitle = jobTitle + "_" + currentTimestamp;
detailsOfJob = detailsOfJob + "_" + currentTimestamp;
if(this.getCompanyManagementElement() != null){
this.getCompanyManagementElement().click();
this.getJobListElement().click();
this.getAddJobButton().click();
this.selectCompany(companyName);
this.selectDepartment(departmentName);
this.getJobTitleElement().sendKeys(jobTitle);
this.getDetailsOfJobElement().sendKeys(detailsOfJob);
this.getConfirmAddButton().click();
this.getCloseButton().click();
}else {
log.info("can not open company management tab !");
}
if(this.getAddedJobTitle() != null && this.getAddedJobTitle().getText().equals(companyName)){
String remindingMessage = this.getAddedJobTitle().getText().equals(companyName) ? "job added successfully !" : "job added failed !";
Assert.assertEquals(remindingMessage, companyName, this.getAddedJobTitle().getText());
log.info(this.getAddedJobTitle().getText().toString());
}
}
/**
* Get company management element on the left navigation list
* @return the WebElement
*/
private WebElement getCompanyManagementElement(){
WebElement companyManagement = wait.until( ExpectedConditions.presenceOfElementLocated(By.cssSelector("#accordion > li:nth-child(2) > a")));
return companyManagement;
}
/**
* Get job list sub element under company management tab
* @return the WebElement
*/
private WebElement getJobListElement(){
WebElement jobList = Login.driver.findElement(By.cssSelector("#collapseOne > ul > li:nth-child(3) > a"));
return jobList;
}
/**
* Get add job button in company list page
* @return the WebElement
*/
private WebElement getAddJobButton(){
WebElement addDepartment = Login.driver.findElement(By.cssSelector(".dment-fn > button"));
return addDepartment;
}
/**
* select a company from company drop down list on 'add_job_details' overlay.
* @param company a value of company drop down list
*/
private void selectCompany(String company){
Select companyList = new Select(Login.driver.findElement(By.id("add-position-company-select")));
if(companyList != null){
companyList.selectByValue(company);
}else {
log.info("there is no any company can be selected !");
}
}
/**
* select a department from department drop down list on 'add_job_details' overlay.
* @param department a value of department drop down list
*/
private void selectDepartment(String department){
Select departmentList = new Select(Login.driver.findElement(By.id("add-position-department-select")));
if(departmentList != null){
departmentList.selectByValue(department);
}else {
log.info("there is no any department can be selected !");
}
}
/**
* Get job title element on 'add_job_details' overlay.
* @return the WebElement
*/
private WebElement getJobTitleElement(){
WebElement jobTitle = Login.driver.findElement(By.id("add-position-name"));
return jobTitle;
}
/**
* Get details of job element on 'add_job_details' overlay.
* @return the WebElement
*/
private WebElement getDetailsOfJobElement(){
WebElement detailsOfJob = Login.driver.findElement(By.id("add-position-desc"));
return detailsOfJob;
}
/**
* Get confirm add button on add_details_of_job overlay
* @return the WebElement
*/
private WebElement getConfirmAddButton(){
WebElement confirmAddButton = Login.driver.findElement(By.cssSelector("#myModal-add > div > div > div:nth-child(3) > button:nth-child(2)"));
return confirmAddButton;
}
/**
* Get the job title which just added before in job list table, normally pick up the first record of job list table
* @return the WebElement
*/
private WebElement getAddedJobTitle(){
WebElement addedJobTitle = Login.driver.findElement(By.cssSelector("#position_tbody > tr:nth-child(1) > td:nth-child(2)"));
return addedJobTitle;
}
/**
* get close button on add_details_of_job overlay
* @return the WebElement
*/
private WebElement getCloseButton(){
WebElement closeButton = Login.driver.findElement(By.cssSelector("#myModal-add > div > div > div:nth-child(3) > button:nth-child(1)"));
return closeButton;
}
}
|
/*
* (C) Copyright 2010 Marvell International Ltd.
* All Rights Reserved
*
* MARVELL CONFIDENTIAL
* Copyright 2008 ~ 2010 Marvell International Ltd All Rights Reserved.
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell International Ltd
* or its suppliers and licensors. The Material contains trade secrets and
* proprietary and confidential information of Marvell or its suppliers and
* licensors. The Material is protected by worldwide copyright and trade secret
* laws and treaty provisions. No part of the Material may be used, copied,
* reproduced, modified, published, uploaded, posted, transmitted, distributed,
* or disclosed in any way without Marvell's prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
package com.marvell.cmmb.common;
public interface Action {
public static final String ACTION_NETWORKCONNECT_FAILED = "com.marvell.cmmb.NETWORKCONNECT_FAILED";
public static final String ACTION_LOADING_FINISH = "com.marvell.cmmb.LOADING_FINISH";
public static final String ACTION_MODE_CHANGED = "com.marvell.cmmb.MODE_CHANGED";
public static final String ACTION_ESG_UPDATED = "com.marvell.cmmb.ESG_UPDATED";
public static final String ACTION_SG_UPDATING = "com.marvell.cmmb.SG_UPDATING";
public static final String ACTION_SG_UPDATED = "com.marvell.cmmb.SG_UPDATED";
public static final String ACTION_PARSESG_FINISHED = "com.marvell.cmmb.PARSESG_FINISHED";
public static final String ACTION_ST_UPDATED = "com.marvell.cmmb.ST_UPDATED";
public static final String ACTION_PARSEST_FINISHED = "com.marvell.cmmb.PARSEST_FINISHED";
public static final String ACTION_SCAN_START = "com.marvell.cmmb.SCAN_START";
public static final String ACTION_SCAN_FINISHED = "com.marvell.cmmb.SCAN_FINISHED";
public static final String ACTION_SCAN_FAILED = "com.marvell.cmmb.SCAN_FAILED";
public static final String ACTION_GBA_INIT = "com.marvell.cmmb.GBA_INIT";
public static final String ACTION_AUTHORIZE_STARTED = "com.marvell.cmmb.AUTHORIZE_STARTED";
public static final String ACTION_AUTHORIZED = "com.marvell.cmmb.AUTHORIZED";
public static final String ACTION_INQUIRIED = "com.marvell.cmmb.INQUIRIED";
public static final String ACTION_PARSEINQUIRY_FINISHED = "com.marvell.cmmb.PARSEINQUIRY_FINISHED";
public static final String ACTION_SUBSCRIBE_FINISH = "com.marvell.cmmb.SUBSCRIBE_FINISH";
public static final String ACTION_UNSUBSCRIBE_FINISH = "com.marvell.cmmb.UNSUBSCRIBE_FINISH";
public static final String ACTION_SERVICE_STARTED = "com.marvell.cmmb.SERVICE_STARTED";
public static final String ACTION_SERVICE_DESTROED = "com.marvell.cmmb.SERVICE_DESTROED";
public static final String ACTION_EBMESSAGE = "com.marvell.cmmb.EB_MESSAGE";
public static final String ACTION_SIGNAL_SERVICE_DESTROY = "com.marvell.cmmb.SIGNAL_SERVICE_DESTROY_ACTION";
public static final String ACTION_VIEW_PROGRAM_ACTION = "com.marvell.cmmb.VIEW_PROGRAM_ACTION";
public static final String ACTION_VIEW_SCHEDULE_ACTION = "com.marvell.cmmb.VIEW_SCHEDULE_ACTION";
public static final String ACTION_VIEW_DETAIL_ACTION = "com.marvell.cmmb.VIEW_DETAIL_ACTION";
public static final String ACTION_VIEW_SEARCH_ACTION = "com.marvell.cmmb.VIEW_SEARCH_ACTION";
public static final String ACTION_ON_PLAYSTATE_CHANGE = "com.marvell.cmmb.PLAYSTATE_CHANGE";
public static final String ACTION_SG_PARSED = "com.marvell.cmmb.SGPARSED";
public static final String ACTION_ESG_PARSED = "com.marvell.cmmb.ESGPARSED";
public static final String ACTION_MODE_CMMB = "com.marvell.cmmb.MODE_CMMB";
public static final String ACTION_MODE_MBBMS = "com.marvell.cmmb.MODE_MBBMS";
public static final String ACTION_SET_APN = "com.marvell.cmmb.SET_APN";
public static final String ACTION_SIMCARD_OUT = "com.marvell.cmmb.SIMCARD_OUT";
public static final String ACTION_DISMISS_CANCELDIALOG = "com.marvell.cmmb.DISMISS_CANCELDIALOG";
public static final String ACTION_VIEW_PROGRAME_BY_ID_FREQ = "com.marvell.cmmb.VIEW_PROGRAME_BY_ID_FREQ";
public static final String ACTION_VIEW_EBMESSAGE = "com.marvell.cmmb.VIEW_EBMESSAGE";
public static final String ACTION_LOADING_ERROR_QUIT = "com.marvell.cmmb.LOADING_ERROR_QUIT";
public static final String ACTION_BINDER_DIED = "com.marvell.cmmb.BINDER_DIED";
public static final String ACTION_SHOW_BINDER_DIED_DIALOG = "com.marvell.cmmb.SHOW_BINDER_DIED_DIALOG";
public static final String ACTION_START_CONNECT_NET = "com.marvell.cmmb.START_CONNECT_NET";
public static final String ACTION_BINDER_DIED_EXIT = "com.marvell.cmmb.BINDER_DIED_EXIT";
public static final String ACTION_UPDATE_EXTERNAL_SG = "com.marvell.cmmb.UPDATE_EXTERNAL_SG";
public static final String ACTION_RESET_FINISHED = "com.marvell.cmmb.ACTION_RESET_FINISHED";
}
|
import p1.button1;
import p1.coffee;
import java.awt.*;
import javax.swing.*;
class TabbedPaneExample extends JFrame
{
private JTabbedPane tabbedPane;
public TabbedPaneExample()
{
Container c=this.getContentPane();
c.setLayout( new BorderLayout() );
button1 bt=new button1();
coffee cf=new coffee();
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Page 1", bt );
tabbedPane.addTab( "Page 2", cf );
c.add( tabbedPane);
}
// Main method to get things started
public static void main( String args[] )
{
TabbedPaneExample mainFrame = new TabbedPaneExample();
mainFrame.setTitle( "Tabbed Pane Application" );
mainFrame.setSize( 300, 200 );
mainFrame.setBackground( Color.gray );
mainFrame.setVisible( true );
}
}
|
package io.core9.plugin.widgets.widget;
import java.util.List;
public interface WidgetProvider {
List<Widget> getWidgets();
}
|
package ac.a14ehsr.platform;
import java.io.IOException;
import java.util.Arrays;
import ac.a14ehsr.exception.TimeoutException;
import ac.a14ehsr.platform.visualizer.Visualizer;
import ac.a14ehsr.player.Player;
public abstract class Game {
protected int numberOfPlayers;
protected int numberOfGames;
protected long timelimit;
protected Player[] players;
protected boolean isVisible;
protected int outputLevel;
protected Visualizer visualizer;
private static final int CONTINUE = 0;
private static final int FINISH = 1;
public Game(int numberOfPlayers, int numberOfGames, long timelimit, boolean isVisible, int outputLevel, Player[] players){
this.numberOfGames = numberOfGames;
this.numberOfPlayers = numberOfPlayers;
this.timelimit = timelimit;
this.players = players;
this.isVisible = isVisible;
this.outputLevel = outputLevel;
visualizer = null;
}
public void setVisualizerName() {
if(visualizer != null) {
visualizer.setName(Arrays.stream(players).map(Player::getName).toArray(String[]::new));
}
}
/**
* @param visualizer the visualizer to set
*/
public void setVisualizer(Visualizer visualizer) {
this.visualizer = visualizer;
}
/**
* ใฒใผใ ใ้ๅงใใๆใฎไธ็ชๆๅใฎๅฆ็
* ใฒใผใ ใใจใซๅคใใใใฌใคใคใผใซๆธกใในใๆ
ๅ ฑใใใใฐใใใซๅบๅใๅ ใใ
*/
abstract void initialize() throws IOException;
/**
* ใฒใผใ ็ถๆณใๅบๅใใ
*/
abstract void show();
/**
* ใฒใผใ ็ตไบๆใฎ็ถๆณใๅบๅ
*/
abstract void showGameResult();
/**
* ใฟใผใณๅฆ็
*/
abstract void play();
/**
* ้ ไฝไปใใ่กใ๏ผใใใซๅใใใใใคใณใใไปไธใใ
*/
void gameRank() {
}
/**
* ใฒใผใ ็ตไบๆใฎplayerใฎgamePointใใ็ฎๅบใใใใคใณใใsumPointใซๅ ็ฎ
*/
abstract void calcGameResult();
/**
* @return the numberOfGames
*/
public int getNumberOfGames() {
return numberOfGames;
}
/**
* @return the numberOfPlayers
*/
public int getNumberOfPlayers() {
return numberOfPlayers;
}
/**
* @param numberOfGames the numberOfGames to set
*/
public void setNumberOfGames(int numberOfGames) {
this.numberOfGames = numberOfGames;
}
/**
* @param numberOfPlayers the numberOfPlayers to set
*/
public void setNumberOfPlayers(int numberOfPlayers) {
this.numberOfPlayers = numberOfPlayers;
}
/**
* playerใฎsumPointใฎ้ซใ้ ใซ้ ไฝใไปไธใใฆ
* Resultใชใใธใงใฏใใ่ฟใ
*/
Result result() {
Result result = new Result(players);
if(outputLevel > 0) {
result.show();
}
return result;
}
void sendGameInfo() throws IOException {
for(Player player : players) {
player.sendNum(numberOfPlayers);
player.sendNum(numberOfGames);
player.sendNum((int)timelimit);
player.sendNum(player.getCode());
try{
player.setName(player.receiveMes(1000, 1000));
}catch(Exception e) {
System.err.println("SEND GAME INFO ERROR");
e.printStackTrace();
}
}
}
void showPlayers() {
if (outputLevel > 0) {
System.out.println("players : " + String.join(" vs ",Arrays.stream(players).map(Player::getName).toArray(String[]::new)));
}
}
/**
* ใฒใผใ ใ็ตไบใใฆใใใชใfalse
*/
abstract boolean isContinue();
void sendGameFinish() throws IOException {
for(Player player : players) {
if(player.getStatus() == 0) continue;
player.sendNum(FINISH);
}
}
void sendGameContinue() throws IOException {
for(Player player : players) {
if(player.getStatus() == 0) continue;
player.sendNum(CONTINUE);
}
}
void dispose() {
if(visualizer != null) {
visualizer.dispose();
}
}
void visualizerReset() {
if(visualizer != null) {
visualizer.reset();
}
}
} |
package org.kuali.ole.deliver.batch;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.log4j.Logger;
import org.kuali.ole.OLEConstants;
import org.kuali.ole.OLEParameterConstants;
import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
import org.kuali.ole.deliver.processor.LoanProcessor;
import org.kuali.ole.describe.bo.OleLocation;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.KRADServiceLocator;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: ?
* Date: 12/31/12
* Time: 5:30 PM
* To change this template use File | Settings | File Templates.
*/
public class OleDeliverBatchServiceImpl {
private LoanProcessor loanProcessor;
private Font boldFont = new Font(Font.TIMES_ROMAN, 15, Font.BOLD);
private Font ver_15_normal = FontFactory.getFont("VERDANA", 15, 0);
private static final Logger LOG = Logger.getLogger(OleDeliverBatchServiceImpl.class);
/**
* This method initiate LoanProcessor.
*
* @return LoanProcessor
*/
private LoanProcessor getLoanProcessor() {
if (loanProcessor == null) {
loanProcessor = new LoanProcessor();
}
return loanProcessor;
}
private void getHTMLHeader(StringBuffer stringBuffer, String title) throws Exception {
stringBuffer.append("<HTML>");
stringBuffer.append("<TITLE>" + title + "</TITLE>");
stringBuffer.append("<HEAD></HEAD>");
stringBuffer.append("<BODY>");
}
private void getTemplateHeader(OleNoticeBo noticeBo, StringBuffer stringBuffer) throws Exception {
stringBuffer.append("<TABLE></BR></BR>");
stringBuffer.append("<TR><TD>Patron Name :</TD><TD>" + noticeBo.getPatronName() + "</TD></TR>");
stringBuffer.append("<TR><TD>Address :</TD><TD>" + noticeBo.getPatronAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>EMAIL :</TD><TD>" + noticeBo.getPatronEmailAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>Phone Number :</TD><TD>" + ( noticeBo.getPatronPhoneNumber()!=null ? noticeBo.getPatronPhoneNumber() : "") + "</TD></TR>");
stringBuffer.append("</TABLE>");
}
private void getTemplateBody(StringBuffer stringBuffer, String title, String body) throws Exception {
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR>");
stringBuffer.append("<TABLE width=\"100%\">");
stringBuffer.append("<TR><TD><CENTER>" + title + "</CENTER></TD></TR>");
stringBuffer.append("<TR><TD><p>" + body + "</p></TD></TR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR></TABLE>");
}
/*private void getTemplateFooter(OleNoticeBo noticeBo, StringBuffer stringBuffer) throws Exception {
stringBuffer.append("<TABLE><TR><TD>Circulation Location/Library Name :</TD><TD>" + noticeBo.getCirculationDeskName() + "</TD><TD> </TD><TD>Title :</TD><TD>" + noticeBo.getTitle() + "</TD></TR>");
stringBuffer.append("<TR><TD>Address :</TD><TD>" + noticeBo.getPatronAddress() + "</TD><TD> </TD><TD>Author :</TD><TD>" + noticeBo.getAuthor() + "</TD></TR>");
stringBuffer.append("<TR><TD>Email :</TD><TD>" + noticeBo.getPatronEmailAddress() + "</TD><TD> </TD><TD>Volume/Issue/Copy Number :</TD><TD>" + noticeBo.getVolumeNumber() + "</TD></TR>");
stringBuffer.append("<TR><TD>Phone Number :</TD><TD>" + noticeBo.getPatronPhoneNumber() + "</TD><TD> </TD><TD>Library shelving location :</TD><TD>" + noticeBo.getItemShelvingLocation() + "</TD></TR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD><TD> </TD><TD>Call Number :</TD><TD>" + noticeBo.getItemCallNumber() + "</TD></TR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD><TD> </TD><TD>Item Barcode :</TD><TD>" + noticeBo.getItemId() + "</TD></TR>");
if (noticeBo.getNoticeName().equalsIgnoreCase("Overdue")) {
stringBuffer.append("<TR><TD> </TD><TD> </TD><TD> </TD><TD>Item was due :</TD><TD>" + noticeBo.getDueDate() + "</TD></TR>");
}
if (noticeBo.getNoticeName().equalsIgnoreCase("Recall")) {
stringBuffer.append("<TR><TD> </TD><TD> </TD><TD> </TD><TD>Original due date:</TD><TD>" + noticeBo.getOriginalDueDate() + "</TD></TR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD><TD> </TD><TD>New due date:</TD><TD>" + noticeBo.getNewDueDate() + "</TD></TR>");
}
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR>");
}*/
public BusinessObjectService getBusinessObjectService() {
BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
return businessObjectService;
}
private String itemShelvingLocationName(String code) {
Map<String, String> criteria = new HashMap<String, String>();
criteria.put("locationCode", code);
List<OleLocation> oleLocation = (List<OleLocation>) getBusinessObjectService().findMatching(OleLocation.class, criteria);
return oleLocation.size() == 1 ? oleLocation.get(0).getLocationName() : "";
}
private void getTemplateFooter(OleNoticeBo noticeBo, StringBuffer stringBuffer) throws Exception {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
stringBuffer.append("<table>");
if (!noticeBo.getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_RECALL)) {
stringBuffer.append("<TR><TD>Circulation Location/Library Name :</TD><TD>" + (noticeBo.getCirculationDeskName() != null ? noticeBo.getCirculationDeskName() : "") + "</TD></TR>");
}
stringBuffer.append("<TR><TD>Title :</TD><TD>" + (noticeBo.getTitle()!=null ? noticeBo.getTitle() : "") + "</TD></TR>");
stringBuffer.append("<TR><TD>Author :</TD><TD>" + (noticeBo.getAuthor()!=null ? noticeBo.getAuthor() : "") + "</TD></TR>");//noticeBo.getVolumeIssueCopyNumber()
stringBuffer.append("<TR><TD>Volume/Issue/Copy Number :</TD><TD>" + (noticeBo.getVolumeIssueCopyNumber()!=null ? noticeBo.getVolumeIssueCopyNumber() : "") + "</TD></TR>");
stringBuffer.append("<TR><TD>Library shelving location :</TD><TD>" + (itemShelvingLocationName(noticeBo.getItemShelvingLocation())!=null ? itemShelvingLocationName(noticeBo.getItemShelvingLocation()) : "" )+ "</TD></TR>");
stringBuffer.append("<TR><TD>Call Number :</TD><TD>" +(noticeBo.getItemCallNumber()!=null ? noticeBo.getItemCallNumber() : "") + "</TD></TR>");
stringBuffer.append("<TR><TD>Item Barcode :</TD><TD>" +(noticeBo.getItemId()!=null ? noticeBo.getItemId() : "") + "</TD></TR>");
if (noticeBo.getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
stringBuffer.append("<TR><TD>Item was due :</TD><TD>" +( noticeBo.getDueDate()!=null ? noticeBo.getDueDate() : "" )+ "</TD></TR>");
}
if (noticeBo.getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_RECALL)) {
stringBuffer.append("<TR><TD>Original due date:</TD><TD>" + (noticeBo.getOriginalDueDate()!=null ? df.format(noticeBo.getOriginalDueDate()) : "") + "</TD></TR>");
stringBuffer.append("<TR><TD>New due date:</TD><TD>" + (noticeBo.getNewDueDate()!=null ? df.format(noticeBo.getNewDueDate()) : "") + "</TD></TR>");
}
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR>");
stringBuffer.append("</table>");
}
private void getPickUpLocationTemplate(OleNoticeBo noticeBo, StringBuffer stringBuffer) throws Exception {
stringBuffer.append("<TR><TD>Pick up location :</TD><TD></TD></TR>");
if (!noticeBo.getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_RECALL)) {
stringBuffer.append("<TR><TD>Circulation Location/Library Name :</TD><TD>" + (noticeBo.getCirculationDeskName() != null ? noticeBo.getCirculationDeskName() : "") + "</TD></TR>");
}
stringBuffer.append("<TR><TD>Address :</TD><TD>" + (noticeBo.getCirculationDeskAddress()!=null ? noticeBo.getCirculationDeskAddress() : "" )+ "</TD></TR>");
stringBuffer.append("<TR><TD>Email :</TD><TD>" + (noticeBo.getCirculationDeskEmailAddress()!=null ? noticeBo.getCirculationDeskEmailAddress() : "" )+ "</TD></TR>");
stringBuffer.append("<TR><TD>Phone Number :</TD><TD>" +( noticeBo.getCirculationDeskPhoneNumber()!=null ? noticeBo.getCirculationDeskPhoneNumber() : "") + "</TD></TR>");
stringBuffer.append("<TR><TD>Item will be held until</TD><TD>" +( noticeBo.getDueDate()!=null ? noticeBo.getDueDate() : "") + "</TD></TR>");
}
private void getHTMLFooter(StringBuffer stringBuffer) throws Exception {
String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
stringBuffer.append("<TABLE width=\"100%\">\"<TR><TD><CENTER><a href =\""+url+ "/portal.do?channelTitle=MyAccount&channelUrl=" + url + "/ole-kr-krad/myaccountcontroller?viewId=RenewalItemView&methodToCall=start\">"+"My Account"+"</a></CENTER></TD></TR></TABLE>");
stringBuffer.append("</TABLE></BODY></HTML>");
LOG.info("MAIL HTML CONTENT : "+stringBuffer.toString());
}
private Map getSMSTemplate(List<OleNoticeBo> noticeBo) throws Exception {
List<OleNoticeBo> overDueNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> onHoldNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> recallNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredRequiredNoticeList = new ArrayList<OleNoticeBo>();
Map smsMap = new HashMap();
for (int temp = 0; temp < noticeBo.size(); temp++) {
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
overDueNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_ONHOLD)) {
onHoldNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.OleDeliverRequest.RECALL)) {
recallNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
expiredNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST)) {
expiredRequiredNoticeList.add(noticeBo.get(temp));
}
}
Map overdue = new HashMap();
if (overDueNoticeList != null && overDueNoticeList.size() > 0) {
overdue = getOverDueList(overdue, overDueNoticeList);
}
Map hod = new HashMap();
if (onHoldNoticeList != null && onHoldNoticeList.size() > 0) {
hod = getHoldList(hod, onHoldNoticeList);
}
Map recl = new HashMap();
if (recallNoticeList != null && recallNoticeList.size() > 0) {
recl = getRecallList(recl, recallNoticeList);
}
Map exp = new HashMap();
if (expiredNoticeList != null && expiredNoticeList.size() > 0) {
exp = getExpiredList(exp, expiredNoticeList);
}
Map expReq = new HashMap();
if (expiredRequiredNoticeList != null && expiredRequiredNoticeList.size() > 0) {
expReq = getExpiredRequiredList(expReq, expiredRequiredNoticeList);
}
smsMap.put("OVERDUE", overdue);
smsMap.put("HOLD", hod);
smsMap.put("RECALL", recl);
smsMap.put("EXPIRED", exp);
smsMap.put("EXPIREDREQ", expReq);
return smsMap;
}
private Map getExpiredRequiredList(Map expReq, List expiredRequiredNoticeList) throws Exception {
String smsExpiredReq = "";
LoanProcessor loanProcessor = getLoanProcessor();
for (int exReq = 0; exReq < expiredRequiredNoticeList.size(); exReq++) {
OleNoticeBo oleNoticeBo = (OleNoticeBo) expiredRequiredNoticeList.get(exReq);
smsExpiredReq = loanProcessor.getParameter("EXP_REQ_TITLE") + " " + "Circulation Location/Library Name :" + oleNoticeBo.getCirculationDeskName() + ",Address :" + oleNoticeBo.getCirculationDeskAddress() + ",Title :" + oleNoticeBo.getTitle() + ",Call Number :" + oleNoticeBo.getItemCallNumber() + ",Item was due :" + oleNoticeBo.getDueDate();
expReq.put(exReq, smsExpiredReq);
}
return expReq;
}
private Map getExpiredList(Map expire, List expiredNoticeList) throws Exception {
String smsExpire = "";
LoanProcessor loanProcessor = getLoanProcessor();
for (int exp = 0; exp < expiredNoticeList.size(); exp++) {
OleNoticeBo oleNoticeBo = (OleNoticeBo) expiredNoticeList.get(exp);
smsExpire = loanProcessor.getParameter(OLEParameterConstants.EXPIRED_TITLE) + " " + "Circulation Location/Library Name :" + oleNoticeBo.getCirculationDeskName() + ",Address :" + oleNoticeBo.getCirculationDeskAddress() + ",Title :" + oleNoticeBo.getTitle() + ",Call Number :" + oleNoticeBo.getItemCallNumber() + ",Item was due :" + oleNoticeBo.getDueDate();
expire.put(exp, smsExpire);
}
return expire;
}
private Map getRecallList(Map rcall, List recallNoticeList) throws Exception {
String smsRecall = "";
LoanProcessor loanProcessor = getLoanProcessor();
for (int recall = 0; recall < recallNoticeList.size(); recall++) {
OleNoticeBo oleNoticeBo = (OleNoticeBo) recallNoticeList.get(recall);
smsRecall = loanProcessor.getParameter(OLEParameterConstants.RECALL_TITLE) + " " + "Circulation Location/Library Name :" + oleNoticeBo.getCirculationDeskName() + ",Address :" + oleNoticeBo.getCirculationDeskAddress() + ",Title :" + oleNoticeBo.getTitle() + ",Call Number :" + oleNoticeBo.getItemCallNumber() + ",Original due date :" + oleNoticeBo.getDueDate() + ",New due date: " + oleNoticeBo.getNewDueDate();
rcall.put(recall, smsRecall);
}
return rcall;
}
private Map getHoldList(Map hod, List onHoldNoticeList) throws Exception {
String smsHod = "";
LoanProcessor loanProcessor = getLoanProcessor();
for (int hold = 0; hold < onHoldNoticeList.size(); hold++) {
OleNoticeBo oleNoticeBo = (OleNoticeBo) onHoldNoticeList.get(hold);
smsHod = loanProcessor.getParameter(OLEParameterConstants.ONHOLD_TITLE) + " " + "Circulation Location/Library Name :" + oleNoticeBo.getCirculationDeskName() + ",Address :" + oleNoticeBo.getCirculationDeskAddress() + ",Title :" + oleNoticeBo.getTitle() + ",Call Number :" + oleNoticeBo.getItemCallNumber() + ",Item will be held until :" + oleNoticeBo.getDueDate() + ",Pick up location:" + oleNoticeBo.getCirculationDeskName() + ",Pick up location Address :" + oleNoticeBo.getCirculationDeskAddress();
hod.put(hold, smsHod);
}
return hod;
}
private Map getOverDueList(Map overdue, List overDueNoticeList) throws Exception {
String smsDue = "";
LoanProcessor loanProcessor = getLoanProcessor();
for (int due = 0; due < overDueNoticeList.size(); due++) {
OleNoticeBo oleNoticeBo = (OleNoticeBo) overDueNoticeList.get(due);
smsDue = loanProcessor.getParameter(OLEParameterConstants.OVERDUE_TITLE) + " " + "Circulation Location/Library Name :" + oleNoticeBo.getCirculationDeskName() + ",Address :" + oleNoticeBo.getCirculationDeskAddress() + ",Title :" + oleNoticeBo.getTitle() + ",Call Number :" + oleNoticeBo.getItemCallNumber() + ",Item was due :" + oleNoticeBo.getDueDate();
overdue.put(due, smsDue);
}
return overdue;
}
private List getTemplate(List<OleNoticeBo> noticeBo) throws Exception {
StringBuffer stringBuffer = new StringBuffer();
List templateForNoticeList = new ArrayList();
List<OleNoticeBo> overDueNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> onHoldNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> recallNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredRequiredNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> courtesyNoticeList = new ArrayList<OleNoticeBo>();
for (int temp = 0; temp < noticeBo.size(); temp++) {
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
overDueNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_ONHOLD)) {
onHoldNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase("RecallNotice")) {
recallNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
expiredNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST)) {
expiredRequiredNoticeList.add(noticeBo.get(temp));
}
if (noticeBo.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_COURTESY)) {
courtesyNoticeList.add(noticeBo.get(temp));
}
}
LoanProcessor loanProcessor = getLoanProcessor();
if (overDueNoticeList != null && overDueNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.OVERDUE_TITLE));
getTemplateHeader(overDueNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.OVERDUE_TITLE), loanProcessor.getParameter(OLEParameterConstants.OVERDUE_BODY));
for (int overdue = 0; overdue < overDueNoticeList.size(); overdue++) {
getTemplateFooter(noticeBo.get(overdue), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
if (onHoldNoticeList != null && onHoldNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.ONHOLD_TITLE));
getTemplateHeader(onHoldNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.ONHOLD_TITLE), loanProcessor.getParameter(OLEParameterConstants.ONHOLD_BODY));
for (int onHold = 0; onHold < onHoldNoticeList.size(); onHold++) {
getTemplateFooter(noticeBo.get(onHold), stringBuffer);
getPickUpLocationTemplate(noticeBo.get(onHold), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
if (recallNoticeList != null && recallNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.RECALL_TITLE));
getTemplateHeader(recallNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.RECALL_TITLE), loanProcessor.getParameter(OLEParameterConstants.RECALL_BODY));
for (int recall = 0; recall < recallNoticeList.size(); recall++) {
getTemplateFooter(noticeBo.get(recall), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
if (expiredNoticeList != null && expiredNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.EXPIRED_TITLE));
getTemplateHeader(expiredNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.EXPIRED_TITLE), loanProcessor.getParameter(OLEParameterConstants.EXPIRED_BODY));
for (int exp = 0; exp < expiredNoticeList.size(); exp++) {
getTemplateFooter(noticeBo.get(exp), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
if (expiredRequiredNoticeList != null && expiredRequiredNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_TITLE));
getTemplateHeader(expiredRequiredNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_TITLE), loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_BODY));
for (int exReq = 0; exReq < expiredRequiredNoticeList.size(); exReq++) {
getTemplateFooter(noticeBo.get(exReq), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
if (courtesyNoticeList != null && courtesyNoticeList.size() > 0) {
getHTMLHeader(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.COURTESY_TITLE));
getTemplateHeader(courtesyNoticeList.get(0), stringBuffer);
getTemplateBody(stringBuffer, loanProcessor.getParameter(OLEParameterConstants.COURTESY_TITLE), loanProcessor.getParameter(OLEParameterConstants.COURTESY_BODY));
for (int exReq = 0; exReq < courtesyNoticeList.size(); exReq++) {
getTemplateFooter(noticeBo.get(exReq), stringBuffer);
}
getHTMLFooter(stringBuffer);
}
templateForNoticeList.add(stringBuffer);
return templateForNoticeList;
}
private OutputStream getPdfHeader(Document document, OutputStream outputStream, String title, String itemId) throws Exception {
StringBuffer stringBuffer = new StringBuffer();
String pdfLocationSystemParam = getLoanProcessor().getParameter(OLEParameterConstants.PDF_LOCATION);
if (LOG.isInfoEnabled()) {
LOG.info("System Parameter for PDF_Location --> " + pdfLocationSystemParam);
}
if (pdfLocationSystemParam == null || pdfLocationSystemParam.trim().isEmpty()) {
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("staging.directory") + "/";
if (LOG.isInfoEnabled()) {
LOG.info("System Parameter for PDF_Location staging dir--> " + pdfLocationSystemParam);
}
} else {
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("homeDirectory") + "/" + pdfLocationSystemParam + "/";
}
boolean locationExist = new File(pdfLocationSystemParam).exists();
boolean fileCreated = false;
if (LOG.isInfoEnabled()) {
LOG.info("Is directory Exist ::" + locationExist);
}
try {
if (!locationExist) {
fileCreated = new File(pdfLocationSystemParam).mkdirs();
if (!fileCreated) {
throw new RuntimeException("Not Able to create directory :" + pdfLocationSystemParam);
}
}
} catch (Exception e) {
LOG.error("Exception occured while creating the directory : " + e.getMessage(), e);
throw e;
}
if (title == null || title.trim().isEmpty()) {
title = OLEConstants.ITEM_TITLE;
}
title = title.replaceAll(" ", "_");
if (itemId == null || itemId.trim().isEmpty()) {
itemId = OLEConstants.ITEM_ID;
}
String fileName = pdfLocationSystemParam + title + "_" + itemId + "_" + new Date(System.currentTimeMillis()) + ".pdf";
if (LOG.isInfoEnabled()) {
LOG.info("File Created :" + title + "file name ::" + fileName + "::");
}
outputStream = new FileOutputStream(fileName);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
Font boldFont = new Font(Font.TIMES_ROMAN, 15, Font.BOLD);
Font ver_15_normal = FontFactory.getFont("VERDANA", 15, 0);
document.open();
document.newPage();
Paragraph paraGraph = new Paragraph();
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(new Chunk(title, boldFont));
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
return outputStream;
}
public void createPdfForIntransitRequest(OleDeliverRequestBo oleDeliverRequestBo, HttpServletResponse response) {
LOG.debug("Creating pdf for intransit request");
String title = "InTransit Request";
OutputStream outputStream = null;
/*String pdfLocationSystemParam = getLoanProcessor().getParameter("PDF_LOCATION");
if (LOG.isInfoEnabled()) {
LOG.info("System Parameter for PDF_Location --> " + pdfLocationSystemParam);
}
if (pdfLocationSystemParam == null || pdfLocationSystemParam.trim().isEmpty()) {
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("staging.directory") + "/";
if (LOG.isInfoEnabled()) {
LOG.info("System Parameter for PDF_Location staging dir--> " + pdfLocationSystemParam);
}
} else{
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("homeDirectory")+ "/" + pdfLocationSystemParam +"/";
}
boolean locationExist = new File(pdfLocationSystemParam).exists();
boolean fileCreated = false;
if (LOG.isInfoEnabled()) {
LOG.info("Is directory Exist ::" + locationExist);
}
try {
if (!locationExist) {
fileCreated = new File(pdfLocationSystemParam).mkdirs();
if (!fileCreated) {
throw new RuntimeException("Not Able to create directory :" + pdfLocationSystemParam);
}
}
} catch (Exception e) {
LOG.error("Exception occured while creating the directory : " + e.getMessage(),e);
} */
String fileName = "IntransitRequestSlip" + "_" + oleDeliverRequestBo.getItemId() + "_" + new Date(System.currentTimeMillis()) + ".pdf";
if (LOG.isInfoEnabled()) {
LOG.info("File Created :" + title + "file name ::" + fileName + "::");
}
try {
String itemTitle = oleDeliverRequestBo.getTitle() != null ? oleDeliverRequestBo.getTitle() : "";
Date dateOfReq = oleDeliverRequestBo.getCreateDate();
String dateOfRequest = dateOfReq != null ? dateOfReq.toString() : "";
String circulationLocation = oleDeliverRequestBo.getCirculationLocationCode() != null ? oleDeliverRequestBo.getCirculationLocationCode() : "";
String itemBarcode = oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "";
String patronBarcode = oleDeliverRequestBo.getBorrowerBarcode() != null ? oleDeliverRequestBo.getBorrowerBarcode() : "";
String requestType = oleDeliverRequestBo.getRequestTypeId() != null ? oleDeliverRequestBo.getRequestTypeId() : "";
boolean inTransitSlip = requestType.equalsIgnoreCase("8");
Document document = this.getDocument(0, 0, 5, 5);
//outputStream = new FileOutputStream(fileName);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
outputStream = response.getOutputStream();
PdfWriter.getInstance(document, outputStream);
Font boldFont = new Font(Font.TIMES_ROMAN, 15, Font.BOLD);
document.open();
document.newPage();
PdfPTable pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
Paragraph paraGraph = new Paragraph();
if (inTransitSlip) {
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(new Chunk("InTransit Request Slip", boldFont));
}
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
if (inTransitSlip) {
pdfTable.addCell(getPdfPCellInJustified("Date/Time "));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(dateOfRequest.toString()));
pdfTable.addCell(getPdfPCellInJustified("Circulation Location"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(circulationLocation));
pdfTable.addCell(getPdfPCellInJustified("Item Barcode"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(itemBarcode));
pdfTable.addCell(getPdfPCellInJustified("Title"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(itemTitle));
pdfTable.addCell(getPdfPCellInJustified("Patron Barcode"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(patronBarcode));
document.add(pdfTable);
}
document.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
LOG.error(e, e);
}
}
private PdfPCell getPdfPCellInJustified(String chunk) {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk)));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
return pdfPCell;
}
private PdfPCell getPdfPCellInLeft(String chunk) {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk)));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
return pdfPCell;
}
public Document getDocument(float f1, float f2, float f3, float f4) {
Document document = new Document(PageSize.A4);
document.setMargins(f1, f2, f3, f4);
return document;
}
private void getPdfTemplateHeader(OleNoticeBo noticeBo, Document document) throws Exception {
LOG.info("Header for the notice" + noticeBo.getNoticeName() + noticeBo.getItemId());
//PdfPTable pdfTable = new PdfPTable(3);
// PdfPCell pdfPCell = new PdfPCell(new Paragraph("Circulation Location / Library Name"));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(":"));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getCirculationDeskName() != null ? noticeBo.getCirculationDeskName() : "")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk("Address")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(":"));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronAddress() != null ? noticeBo.getPatronAddress() : "")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk("Email")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(":"));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronEmailAddress() != null ? noticeBo.getPatronEmailAddress() : "")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk("Phone #")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(":"));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
// pdfTable.addCell(pdfPCell);
// pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronPhoneNumber() != null ? noticeBo.getPatronPhoneNumber() : "")));
// pdfPCell.setBorder(pdfPCell.NO_BORDER);
// pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
// pdfTable.addCell(pdfPCell);
// document.add(pdfTable);
Paragraph paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
paraGraph = new Paragraph();
paraGraph.add(new Chunk("Patron information", boldFont));
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
PdfPTable pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
PdfPCell pdfPCell= new PdfPCell(new Paragraph("Patron Name"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronName() != null ? noticeBo.getPatronName() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Address")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronAddress() != null ? noticeBo.getPatronAddress() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Email")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronEmailAddress() != null ? noticeBo.getPatronEmailAddress() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Phone #")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronPhoneNumber() != null ? noticeBo.getPatronPhoneNumber() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
private void getPdfTemplateBody(Document document, String title, String body) throws Exception {
//Notice Type
LOG.info("Body Content of the notice :" + title);
Paragraph paraGraph = new Paragraph();
paraGraph.add(new Chunk(title, boldFont));
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
//Notice-specific text
paraGraph = new Paragraph();
paraGraph.add(new Chunk(body, boldFont));
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
private void getPdfTemplateFooter(OleNoticeBo noticeBo, Document document) throws Exception {
LOG.info("Footer for the notice : " + noticeBo.getNoticeName() + noticeBo.getItemId());
Paragraph paraGraph = new Paragraph();
paraGraph.add(new Chunk("Title/item information", boldFont));
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
PdfPTable pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
PdfPCell pdfPCell;
if (!noticeBo.getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_RECALL)) {
pdfPCell = new PdfPCell(new Paragraph("Circulation Location / Library Name"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getCirculationDeskName() != null ? noticeBo.getCirculationDeskName() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
}
pdfPCell = new PdfPCell(new Paragraph("Title "));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getTitle() == null ? "" : noticeBo.getTitle())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Author ")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getAuthor() == null ? "" : noticeBo.getAuthor())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Volume/Issue/Copy # ")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getVolumeNumber() == null ? "" : noticeBo.getVolumeNumber())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Library shelving location ")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getItemShelvingLocation() == null ? "" : noticeBo.getItemShelvingLocation())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Call # ")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getItemCallNumber() == null ? "" : noticeBo.getItemCallNumber())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Item barcode")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getItemId() == null ? "" : noticeBo.getItemId())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
if (noticeBo.getExpiredOnHoldDate() != null) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Expiration onHoldDate")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getExpiredOnHoldDate() == null ? "" : df.format(noticeBo.getExpiredOnHoldDate()))));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
}
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
//Information specific text
/* paraGraph = new Paragraph();
paraGraph.add(new Chunk("Information specific text",boldFont));
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);*/
if (noticeBo.getNoticeName().equals(OLEConstants.NOTICE_RECALL)) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
LOG.info("Recall Notice Footer Content : " + noticeBo.getNoticeName() + noticeBo.getItemId());
pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
pdfPCell = new PdfPCell(new Paragraph("Original Due Date"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getOriginalDueDate() == null ? "" : df.format(noticeBo.getOriginalDueDate()))));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("New Due Date")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getNewDueDate() == null ? "" : df.format(noticeBo.getNewDueDate()))));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
} else if (noticeBo.getNoticeName().equals("OnHold")) {
LOG.info("OnHold Notice Footer Content : " + noticeBo.getNoticeName() + noticeBo.getItemId());
pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
pdfPCell = new PdfPCell(new Paragraph("Pick Up Location"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPickUpLocation() != null ? noticeBo.getPickUpLocation() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph("Circulation Location / Library Name"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getCirculationDeskName() != null ? noticeBo.getCirculationDeskName() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Address")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronAddress() != null ? noticeBo.getPatronAddress() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Email")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronEmailAddress() != null ? noticeBo.getPatronEmailAddress() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Phone #")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getPatronPhoneNumber() != null ? noticeBo.getPatronPhoneNumber() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
pdfPCell = new PdfPCell(new Paragraph(new Chunk("Item Will Be Held until")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getOnHoldDueDate() != null ? noticeBo.getOnHoldDueDate().toString() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
} else if (noticeBo.getNoticeName().equals("OverdueNotice")) {
LOG.info("OverdueNotice Footer Content : " + noticeBo.getNoticeName() + noticeBo.getItemId());
pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20,2,30});
pdfPCell = new PdfPCell(new Paragraph("Item was due"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(":"));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getDueDate() == null ? "" : (noticeBo.getDueDate()))));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
}
private void getPdfFooter(Document document, OutputStream outputStream) throws Exception {
ver_15_normal.setColor(Color.blue);
ver_15_normal.setStyle(Font.UNDERLINE);
Anchor anchor = new Anchor("MyAccount", ver_15_normal);
anchor.setName("My Account");
String url = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
anchor.setReference(url + "/portal.do?channelTitle=MyAccount&channelUrl=" + url + "/ole-kr-krad/myaccountcontroller?viewId=RenewalItemView&methodToCall=start");
Paragraph paraGraph = new Paragraph();
paraGraph.add(anchor);
paraGraph.setAlignment(Element.ALIGN_CENTER);
document.add(paraGraph);
outputStream.flush();
document.close();
outputStream.close();
}
public List getPdfNoticeForPatron(List<OleNoticeBo> noticeBoList) throws Exception {
return getPdfTemplate(noticeBoList);
}
private List getPdfTemplate(List<OleNoticeBo> noticeBoList) throws Exception {
List templateForNoticeList = new ArrayList();
LOG.info("In getPdfTemplate()");
try {
Document document = new Document(PageSize.A4);
OutputStream outputStream = null;
List<OleNoticeBo> overDueNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> onHoldNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> recallNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> expiredRequiredNoticeList = new ArrayList<OleNoticeBo>();
List<OleNoticeBo> courtesyNoticeList = new ArrayList<OleNoticeBo>();
for (int temp = 0; temp < noticeBoList.size(); temp++) {
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
overDueNoticeList.add(noticeBoList.get(temp));
}
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_ONHOLD)) {
onHoldNoticeList.add(noticeBoList.get(temp));
}
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_RECALL)) {
recallNoticeList.add(noticeBoList.get(temp));
}
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
expiredNoticeList.add(noticeBoList.get(temp));
}
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST)) {
expiredRequiredNoticeList.add(noticeBoList.get(temp));
}
if (noticeBoList.get(temp).getNoticeName().equalsIgnoreCase(OLEConstants.NOTICE_COURTESY)) {
courtesyNoticeList.add(noticeBoList.get(temp));
}
}
LoanProcessor loanProcessor = getLoanProcessor();
if (overDueNoticeList != null && overDueNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.OVERDUE_TITLE), overDueNoticeList.get(0).getItemId());
getPdfTemplateHeader(overDueNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.OVERDUE_TITLE), loanProcessor.getParameter(OLEParameterConstants.OVERDUE_BODY));
for (int overdue = 0; overdue < overDueNoticeList.size(); overdue++) {
getPdfTemplateFooter(noticeBoList.get(overdue), document);
}
getPdfFooter(document, outputStream);
}
if (onHoldNoticeList != null && onHoldNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.ONHOLD_TITLE), onHoldNoticeList.get(0).getItemId());
getPdfTemplateHeader(onHoldNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.ONHOLD_TITLE), loanProcessor.getParameter(OLEParameterConstants.ONHOLD_BODY));
for (int onHold = 0; onHold < onHoldNoticeList.size(); onHold++) {
getPdfTemplateFooter(noticeBoList.get(onHold), document);
//getPickUpLocationTemplate(noticeBoList.get(onHold),stringBuffer);
}
getPdfFooter(document, outputStream);
}
if (recallNoticeList != null && recallNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.RECALL_TITLE), recallNoticeList.get(0).getItemId());
getPdfTemplateHeader(recallNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.RECALL_TITLE), loanProcessor.getParameter(OLEParameterConstants.RECALL_BODY));
for (int recall = 0; recall < recallNoticeList.size(); recall++) {
getPdfTemplateFooter(noticeBoList.get(recall), document);
}
getPdfFooter(document, outputStream);
}
if (expiredNoticeList != null && expiredNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.EXPIRED_TITLE), expiredNoticeList.get(0).getItemId());
getPdfTemplateHeader(expiredNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.EXPIRED_TITLE), loanProcessor.getParameter(OLEParameterConstants.EXPIRED_BODY));
for (int exp = 0; exp < expiredNoticeList.size(); exp++) {
getPdfTemplateFooter(noticeBoList.get(exp), document);
}
getPdfFooter(document, outputStream);
}
if (expiredRequiredNoticeList != null && expiredRequiredNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_TITLE), expiredRequiredNoticeList.get(0).getItemId());
getPdfTemplateHeader(expiredRequiredNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_TITLE), loanProcessor.getParameter(OLEParameterConstants.EXP_REQ_BODY));
for (int exReq = 0; exReq < expiredRequiredNoticeList.size(); exReq++) {
getPdfTemplateFooter(noticeBoList.get(exReq), document);
}
getPdfFooter(document, outputStream);
}
if (courtesyNoticeList != null && courtesyNoticeList.size() > 0) {
outputStream = getPdfHeader(document, outputStream, loanProcessor.getParameter(OLEParameterConstants.COURTESY_TITLE), courtesyNoticeList.get(0).getItemId());
getPdfTemplateHeader(courtesyNoticeList.get(0), document);
getPdfTemplateBody(document, loanProcessor.getParameter(OLEParameterConstants.COURTESY_TITLE), loanProcessor.getParameter(OLEParameterConstants.COURTESY_BODY));
for (int exReq = 0; exReq < courtesyNoticeList.size(); exReq++) {
getPdfTemplateFooter(noticeBoList.get(exReq), document);
}
getPdfFooter(document, outputStream);
}
} catch (Exception e) {
LOG.error(e, e);
}
// templateForNoticeList.add(stringBuffer);
return templateForNoticeList;
}
public List getNoticeForPatron(List<OleNoticeBo> noticeBo) throws Exception {
return getTemplate(noticeBo);
}
public Map getSMSForPatron(List<OleNoticeBo> noticeBo) throws Exception {
return getSMSTemplate(noticeBo);
}
public String sendMissingNotice(OleNoticeBo oleNoticeBo) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("<HTML>");
stringBuffer.append("<TITLE>" + oleNoticeBo.getNoticeName() + "</TITLE>");
stringBuffer.append("<HEAD><TR><TD><CENTER>" + oleNoticeBo.getNoticeName() + "</CENTER></TD></TR></HEAD>");
stringBuffer.append("<BODY>");
stringBuffer.append("<TABLE></BR></BR>");
stringBuffer.append("<TR><TD>Circulation Location / Library Name :</TD><TD>" + oleNoticeBo.getCirculationDeskName() + "</TD></TR>");
stringBuffer.append("<TR><TD>Address :</TD><TD>" + oleNoticeBo.getCirculationDeskAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>EMAIL :</TD><TD>" + oleNoticeBo.getCirculationDeskEmailAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>PhoneNumber :</TD><TD>" + oleNoticeBo.getCirculationDeskPhoneNumber() + "</TD></TR>");
stringBuffer.append("</TABLE>");
stringBuffer.append("<TABLE></BR></BR>");
stringBuffer.append("<TR><TD>PatronName :</TD><TD>" + oleNoticeBo.getPatronName() + "</TD></TR>");
stringBuffer.append("<TR><TD>Address :</TD><TD>" + oleNoticeBo.getPatronAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>EMAIL :</TD><TD>" + oleNoticeBo.getPatronEmailAddress() + "</TD></TR>");
stringBuffer.append("<TR><TD>PhoneNumber :</TD><TD>" + oleNoticeBo.getPatronPhoneNumber() + "</TD></TR>");
stringBuffer.append("</TABLE>");
stringBuffer.append("<TABLE></BR></BR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR>");
stringBuffer.append("<TABLE width=\"100%\">");
stringBuffer.append("<TR><TD><CENTER>" + oleNoticeBo.getNoticeName() + "</CENTER></TD></TR>");
stringBuffer.append("<TR><TD><p>" + oleNoticeBo.getNoticeSpecificContent() + "</p></TD></TR>");
stringBuffer.append("<TR><TD> </TD><TD> </TD></TR></TABLE>");
stringBuffer.append("<TABLE></BR></BR>");
stringBuffer.append("<TR><TD>Title :</TD><TD>" + oleNoticeBo.getTitle() + "</TD></TR>");
stringBuffer.append("<TR><TD>Author :</TD><TD>" + oleNoticeBo.getAuthor() + "</TD></TR>");
stringBuffer.append("<TR><TD>Volume/Issue/Copy # :</TD><TD>" + oleNoticeBo.getVolumeNumber() + "</TD></TR>");
stringBuffer.append("<TR><TD>Library shelvinglocation :</TD><TD>" + oleNoticeBo.getItemShelvingLocation() + "</TD></TR>");
stringBuffer.append("<TR><TD>Call #:</TD><TD>" + oleNoticeBo.getItemCallNumber() + "</TD></TR>");
stringBuffer.append("<TR><TD>Item barcode :</TD><TD>" + oleNoticeBo.getItemId() + "</TD></TR>");
stringBuffer.append("</TABLE>");
stringBuffer.append("</BODY>");
stringBuffer.append("</HTML>");
return stringBuffer.toString();
}
public void getPdfPickUpNotice(OleNoticeBo noticeBo) throws Exception{
LOG.info("PickUp notice : " + noticeBo.getNoticeName() + noticeBo.getItemId());
Document document = new Document(PageSize.A4);
OutputStream outputStream = null;
outputStream = getPdfHeader(document, outputStream,noticeBo.getNoticeName(), noticeBo.getItemId());
document.setPageCount(3);
PdfPTable pdfTable = new PdfPTable(1);
PdfPCell pdfPCell = new PdfPCell(new Paragraph(Chunk.NEWLINE));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk((noticeBo.getPatronName() != null) ? noticeBo.getPatronName().toString() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk((noticeBo.getPatronAddress() != null) ? noticeBo.getPatronAddress().toString() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk((noticeBo.getPatronEmailAddress() != null) ? noticeBo.getPatronEmailAddress().toString() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk((noticeBo.getPatronPhoneNumber() != null) ? noticeBo.getPatronPhoneNumber().toString() : "")));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
pdfTable = new PdfPTable(1);
pdfTable.setWidths(new int[]{10});
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getNoticeName(),boldFont)));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_CENTER);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(Chunk.NEWLINE));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(new Chunk(noticeBo.getNoticeSpecificContent())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph(Chunk.NEWLINE));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfTable.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Paragraph("Thank you."));
Paragraph paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfTable.addCell(pdfPCell);
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
PdfPTable pdfItemTable = new PdfPTable(3);
pdfItemTable.setWidths(new int[]{10,2,30});
String author=((noticeBo.getAuthor() != null) ? noticeBo.getAuthor().toString() : "");
String title=((noticeBo.getTitle() != null) ? noticeBo.getTitle().toString() : "");
String callNumber=((noticeBo.getItemCallNumber()!=null)?noticeBo.getItemCallNumber().toString():"");
PdfPCell pdfItemCell = new PdfPCell(new Paragraph(new Chunk("Title")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(":")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(title)));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk("Author")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(":")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(author)));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk("Call Number")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(":")));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
pdfItemCell = new PdfPCell(new Paragraph(new Chunk(callNumber)));
pdfItemCell.setBorder(pdfPCell.NO_BORDER);
pdfItemCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
pdfItemTable.addCell(pdfItemCell);
document.add(pdfItemTable);
document.close();
outputStream.close();
}
public String getEmailPickUpNotice(OleNoticeBo noticeBo) throws Exception {
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("<TABLE>");
stringBuffer.append("<TR><TD>");
stringBuffer.append("<TABLE>");
stringBuffer.append("<TR><TD COLSPAN='3'>" + ((noticeBo.getPatronName() != null) ? noticeBo.getPatronName().toString() : "") + " </TD></TR>");
stringBuffer.append("<TR><TD COLSPAN='3'>" + ((noticeBo.getPatronAddress() != null) ? noticeBo.getPatronAddress().toString() : "") + " </TD></TR>");
stringBuffer.append("<TR><TD COLSPAN='3'>" + ((noticeBo.getPatronEmailAddress() != null) ? noticeBo.getPatronEmailAddress().toString() : "") + " </TD></TR>");
stringBuffer.append("<TR><TD COLSPAN='3'>" + ((noticeBo.getPatronPhoneNumber() != null) ? noticeBo.getPatronPhoneNumber().toString() : "") + " </TD></TR>");
stringBuffer.append("</TABLE>");
stringBuffer.append("</TD></TR>");
stringBuffer.append("<TR><TD align='center'>");
stringBuffer.append("<B>"+noticeBo.getNoticeName()+"</B>");
stringBuffer.append("</TD></TR>");
stringBuffer.append("<TR><TD align='left'>");
stringBuffer.append("<P>"+noticeBo.getNoticeSpecificContent()+"</P>");
stringBuffer.append("</TD></TR>");
stringBuffer.append("<TR><TD align='left'>");
stringBuffer.append("<P>Thank you .</P>");
stringBuffer.append("</TD></TR>");
stringBuffer.append("<TR><TD>");
String author = ((noticeBo.getAuthor() != null) ? noticeBo.getAuthor().toString() : "");
String title = ((noticeBo.getTitle() != null) ? noticeBo.getTitle().toString() : "");
String callNumber = ((noticeBo.getItemCallNumber() != null) ? noticeBo.getItemCallNumber().toString() : "");
stringBuffer.append("<TR><TD>");
stringBuffer.append("<TABLE>");
stringBuffer.append("<TR><TD COLSPAN='3'> Title : " + title + " </TD></TR>");
stringBuffer.append("<TR><TD COLSPAN='3'> Author : " + author + " </TD></TR>");
stringBuffer.append("<TR><TD COLSPAN='3'> Call Number :" + callNumber + " </TD></TR>");
stringBuffer.append("</TABLE>");
stringBuffer.append("</TD></TR>");
stringBuffer.append("</TABLE>");
return stringBuffer.toString();
}
} |
package com.valentino.indomie.entitys;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Objects;
@Entity
@Getter @Setter
public class Topings {
@Id
@GeneratedValue(generator = "uuid", strategy = GenerationType.IDENTITY)
@GenericGenerator(name = "uuid", strategy = "uuid")
private String id;
private String name;
private Integer price;
private String descriptions;
public Topings(String name, Integer price, String descriptions) {
this.name = name;
this.price = price;
this.descriptions = descriptions;
}
public Topings(){}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Topings topings = (Topings) o;
return Objects.equals(id, topings.id) &&
Objects.equals(name, topings.name) &&
Objects.equals(price, topings.price) &&
Objects.equals(descriptions, topings.descriptions);
}
@Override
public int hashCode() {
return Objects.hash(id, name, price, descriptions);
}
}
|
package ValtechTest;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Valtest {
public static void main(String[] args) {
}
WebDriver driver;
public void FirefoxSetup() throws Throwable{
driver = new FirefoxDriver();
}
public void GetLatestNews() throws Throwable{
driver.navigate().to("http://www.valtech.com/");
driver.findElements(By.xpath(".//*[@id='container']/div[2]/div[3]/div[1]/header/h2"));
Assert.assertTrue(driver.findElement(By.xpath(".//*[@id='container']/div[2]/div[3]/div[1]/header/h2")).getText().equals("LATEST NEWS"));
}
public void GetCases() throws Throwable{
driver.findElement(By.xpath(".//*[@id='navigation-toggle-button']/div/div/div[1]/i")).click();
driver.findElement(By.xpath(".//*[@id='navigationMenuWrapper']/div/div[1]/ul/li[1]/a")).click();
Assert.assertEquals(driver.getTitle(), "Cases");
}
public void GetServices() throws Throwable{
driver.findElement(By.xpath(".//*[@id='navigation-toggle-button']/div/div/div[1]/i")).click();
driver.findElement(By.xpath(".//*[@id='navigationMenuWrapper']/div/div[1]/ul/li[3]/a")).click();
Assert.assertEquals(driver.getTitle(), "Services");
}
public void GetJobs() throws Throwable{
driver.findElement(By.xpath(".//*[@id='navigation-toggle-button']/div/div/div[1]/i")).click();
driver.findElement(By.xpath(".//*[@id='navigationMenuWrapper']/div/div[2]/ul/li[1]/a")).click();
Assert.assertEquals(driver.getTitle(), "Jobs");
}
public void GetTotalvaltech_office() throws Throwable{
driver.findElement(By.xpath(".//*[@id='contacticon']/div/div/div[1]/i")).click();
System.out.println(driver.findElements(By.xpath(".//*[@id='contactbox']/div/div[1]/h3")).get(0-13));
}
}
|
package com.gaoshin.onsalelocal.slocal.service.impl;
import java.math.BigDecimal;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gaoshin.onsalelocal.api.Offer;
import com.gaoshin.onsalelocal.api.Store;
import com.gaoshin.onsalelocal.api.dao.StoreDao;
import com.gaoshin.onsalelocal.slocal.api.ShoplocalCrawler;
import com.gaoshin.onsalelocal.slocal.api.WebCoupon;
import com.gaoshin.onsalelocal.slocal.dao.SlocalDao;
import com.gaoshin.onsalelocal.slocal.entity.Category;
import common.db.dao.City;
import common.db.dao.GeoDao;
import common.db.entity.Task;
import common.db.task.TaskHandler;
import common.db.task.TaskProcessorCenter;
import common.db.task.TaskStatus;
import common.geo.GeoService;
import common.geo.Location;
import common.geo.google.GoogleGeoService;
import common.util.MD5;
@Service
@Transactional(readOnly=true)
public class SlocalCityCategoryTaskHandler implements TaskHandler {
private static final Logger log = Logger.getLogger(SlocalCityCategoryTaskHandler.class);
public static final String CityCategoryTask = "CityCategoryTask";
@Autowired TaskProcessorCenter taskProcessorCenter;
@Autowired SlocalDao slocalDao;
@Autowired GeoDao geoDao;
@Autowired StoreDao storeDao;
private GeoService geoService = new GoogleGeoService();
private ShoplocalCrawler crawler = new ShoplocalCrawler();
@PostConstruct
public void init() {
taskProcessorCenter.register(CityCategoryTask, this);
}
@Override
@Transactional(readOnly=false, rollbackFor=Throwable.class)
public int processTask(List<Task> tasks) {
for(Task t : tasks) {
try {
processOneTask(t);
t.setStatus(TaskStatus.Succeed);
} catch (Exception e) {
e.printStackTrace();
}
}
return tasks.size();
}
private void processOneTask(Task t) throws Exception {
String categoryId = t.getParam1();
Category category = slocalDao.getEntity(Category.class, categoryId);
Category parentCat = null;
if(category.getParentId() != null) {
parentCat = slocalDao.getEntity(Category.class, category.getParentId());
}
String url = category.getUrl();
String cityId = t.getParam();
City city = geoDao.getCity(cityId);
String location = city.getCity() + "," + city.getState();
log.debug("get offers from shoplocal for " + location);
crawler.changeLocation2(location);
List<WebCoupon> coupons = crawler.getCoupons(url);
for(WebCoupon wc : coupons) {
if(wc == null)
continue;
try {
Offer offer = new Offer();
offer.setSource(com.gaoshin.onsalelocal.api.DataSource.Shoplocal.getValue());
offer.setPhone(wc.getPhone());
offer.setAddress(wc.getAddress());
offer.setCity(wc.getCity());
offer.setState(wc.getState());
offer.setTitle(wc.getTitle());
offer.setDescription(wc.getDescription());
offer.setMerchant(wc.getCompany());
offer.setUrl(crawler.getLocationUrl(wc.getCity() + "," + wc.getState(), wc.getUrl()));
offer.setSourceId(MD5.md5(offer.getUrl()));
offer.setDiscount(wc.getOriginalPrice());
offer.setPrice(wc.getListPrice());
offer.setSmallImg(wc.getImageUrl());
if(parentCat != null) {
offer.setSubcategory(category.getName());
offer.setCategory(parentCat.getName());
}
else {
offer.setCategory(category.getName());
offer.setSubcategory("Others");
}
List<Store> stores = storeDao.getStoresByAddress(wc.getAddress(), wc.getCity(), wc.getState());
if(stores.size() > 0) {
offer.setLatitude(stores.get(0).getLatitude().floatValue());
offer.setLongitude(stores.get(0).getLongitude().floatValue());
if(wc.getPhone() != null && stores.get(0).getPhone() == null) {
stores.get(0).setPhone(wc.getPhone());
storeDao.updateEntity(stores.get(0), "phone");
}
}
else {
String geo = wc.getAddress() + ", " + wc.getCity() + ", " + wc.getState();
Location loc = geoService.geo(geo);
offer.setLatitude(loc.getGeocode().getLatitude());
offer.setLongitude(loc.getGeocode().getLongitude());
Store store = new Store();
store.setLatitude(new BigDecimal(loc.getGeocode().getLatitude()));
store.setLongitude(new BigDecimal(loc.getGeocode().getLongitude()));
store.setName(wc.getCompany());
store.setAddress(wc.getAddress());
store.setCity(wc.getCity());
store.setState(wc.getState());
store.setPhone(wc.getPhone());
storeDao.replace(store);
}
slocalDao.insert(offer, true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package productManager.service.purchase;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase,Long> {
} |
package com.krixon.ecosystem.profiling.web.answer;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.Value;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.core.Relation;
@Value
@EqualsAndHashCode(callSuper = true)
@Relation(value = "answer", collectionRelation = "answers")
class AnswerResource extends ResourceSupport
{
@NonNull Object value;
}
|
package com.tapan.tbd;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SearchWeb
*/
public class SearchWeb extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchWeb() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
|
/*
* Population.java
* Created on Apr 30, 2018 (10:04:25 AM).
*/
package main.algotithm;
import java.util.ArrayList;
import java.util.List;
import main.entity.Book;
import main.entity.Shelf;
import main.shelf.BookIndividual;
/**
* Represents a set of individuals
* @author
*/
public class Population {
private List<Individual> population;
public Population() {
population = new ArrayList<>();
}
public List<Individual> getPopulation() {
return population;
}
public void setPopulation(List<Individual> population) {
this.population = population;
}
public void add(BookIndividual ind) {
this.population.add(ind);
}
public Population generateOffspring(int elite, int tries, List<Book> lb, List<Shelf> ls) {
Population p = new Population();
//elitist algorithms
p.getPopulation().addAll(population);
p.getPopulation().sort((Individual o1, Individual o2) -> {
return (int)(o2.computeFitness()-o1.computeFitness()); //sort individuals descending
});
List<Individual> offsp = p.getPopulation().subList(0, elite);
p.setPopulation(offsp);
int ntries = 0; //number of tries while generating offspring
Individual bestIndividual = offsp.get(0);
double bestFitness = bestIndividual.computeFitness();
boolean accept = false;
BookIndividual ni = null;
while(!accept && ntries < tries) {
Chromosome c = Mutator.generate(p);
//System.out.println(c);
ni = new BookIndividual(lb, ls, c);
if(ni.computeFitness()< offsp.get(0).computeFitness()) {
if(ni.computeFitness()==0) {
//System.out.println("Invalid solution");
} else {
if(ni.computeFitness()>bestFitness) {
bestIndividual = ni;
bestFitness = ni.computeFitness();
}
}
ntries++;
} else {
accept = true;
}
}
//generation finished
if(ni.computeFitness()>0) { //if individual is valid
p.getPopulation().add(ni);
}
return p;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Individual i : population) {
sb.append(i).append(i.computeFitness()).append(";\n");
}
return sb.toString();
}
}
|
package org.itst.service.impl;
import java.util.List;
import org.itst.dao.ClubMemberMapper;
import org.itst.domain.Club;
import org.itst.domain.ClubMember;
import org.itst.service.ClubMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ClubMemberServiceImpl implements ClubMemberService {
@Autowired
private ClubMemberMapper mapper;
public void addClubMember(ClubMember student) {
mapper.addClubMember(student);
}
public ClubMember getClubMemberById(String id) {
return mapper.getClubMemberById(id);
}
public void updateClubMember(ClubMember student) {
mapper.updateClubMember(student);
}
public String getClubMembersJsonByPage(int pageSize, int pageNow) {
List<ClubMember> members = mapper.getClubMembersByPage(pageSize*(pageNow-1),pageSize*pageNow);
String s = "";
for (ClubMember m : members) {
s += "{\"name\":\"" + m.getName()
+ "\",\"stuId\":\"" + m.getStuId()
+ "\",\"sex\":\"" + m.getSex()
+ "\",\"fromAcademy\":\"" + m.getFromAcademy()
+ "\",\"fromClubName\":\"" + m.getFromClubName()
+ "\",\"phoneNumber\":\"" + m.getPhoneNumber()
+ "\"},";
}
if (!s.equals("")) {
s = s.substring(0, s.length() - 1);
}
return "{\"total\":" + mapper.getClubMembersCount() + ",\"rows\":[" + s + "]}";
}
public String getClubMembersJsonBykeyWord(String key,
int pageSize, int pageNow) {
List<ClubMember> members = mapper.getClubStudentsBykeyWord(key,pageSize*(pageNow-1),pageSize*pageNow);
String s = "";
for (ClubMember m : members) {
s += "{\"name\":\"" + m.getName()
+ "\",\"stuId\":\"" + m.getStuId()
+ "\",\"sex\":\"" + m.getSex()
+ "\",\"fromAcademy\":\"" + m.getFromAcademy()
+ "\",\"fromClubName\":\"" + m.getFromClubName()
+ "\",\"phoneNumber\":\"" + m.getPhoneNumber()
+ "\"},";
}
if (!s.equals("")) {
s = s.substring(0, s.length() - 1);
}
return "{\"total\":" + mapper.getKeySearchCount(key) + ",\"rows\":[" + s + "]}";
}
public void deleteClubMemberById(String id) {
mapper.deleteClubMemberById(id);
}
}
|
package com.ui.toto.toto.dao;
// mapper java็ฑป
import org.apache.ibatis.annotations.Mapper;
import com.ui.toto.toto.domain.User;
@Mapper
public interface UserDao {
// ่ฏฅๆนๆณๅจUserMapper.xmlไธญๅฎไน
public User selectUserById(Integer userId);
} |
package com.zer0.possessor;
public class CRC64
{
private static final long POLY = 0xc96c5795d7870f42L;
private static final long[][] LOOKUPTABLE;
static {
long crc;
LOOKUPTABLE = new long[8][256];
for (int n = 0; n < 256; ++n) {
crc = n;
for (int k = 0; k < 8; ++k) {
if ((crc & 1) == 1) {
crc = POLY ^ (crc >>> 1);
}
else {
crc = crc >>> 1;
}
}
LOOKUPTABLE[0][n] = crc;
}
for (int n = 0; n < 256; ++n) {
crc = LOOKUPTABLE[0][n];
for (int k = 1; k < 8; ++k) {
crc = LOOKUPTABLE[0][(int)(crc & 0xff)] ^ (crc >>> 8);
LOOKUPTABLE[k][n] = crc;
}
}
}
private static long dataToLong(final byte[] data)
{
long value = 0;
for (int i = 0; i < data.length; i++) {
value |= ((long)data[i] & 0xffL) << (8 * i);
}
return value;
}
public static long checksum(final byte[] data)
{
long crc = 0;
int len = data.length;
int pos = 0;
crc = ~crc;
//while (len != 0 && (data[pos] & 7) != 0) {
// crc = LOOKUPTABLE[0][(int)((crc ^ (data[pos++])) & 0xff)] ^ (crc >>> 8);
// --len;
// }
while (len >= 8) {
crc ^= dataToLong(new byte[] {data[pos], data[pos+1], data[pos+2], data[pos+3], data[pos+4], data[pos+5], data[pos+6], data[pos+7]});
crc = LOOKUPTABLE[7][(int)(crc & 0x000000ff)] ^
LOOKUPTABLE[6][(int)((crc >>> 8) & 0x000000ff)] ^
LOOKUPTABLE[5][(int)((crc >>> 16) & 0x000000ff)] ^
LOOKUPTABLE[4][(int)((crc >>> 24) & 0x000000ff)] ^
LOOKUPTABLE[3][(int)((crc >>> 32) & 0x000000ff)] ^
LOOKUPTABLE[2][(int)((crc >>> 40) & 0x000000ff)] ^
LOOKUPTABLE[1][(int)((crc >>> 48) & 0x000000ff)] ^
LOOKUPTABLE[0][(int)((crc >>> 56) & 0x000000ff)];
pos += 8;
len -= 8;
}
while (len != 0) {
crc = LOOKUPTABLE[0][(int)((crc ^ data[pos++]) & 0x000000ff)] ^ (crc >>> 8);
--len;
}
return ~crc;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.