text
stringlengths 10
2.72M
|
|---|
package org.celllife.stock.domain.alert;
import java.io.Serializable;
import java.util.Date;
import org.celllife.stock.domain.drug.DrugDto;
import org.celllife.stock.domain.user.UserDto;
public class AlertDto implements Serializable {
private static final long serialVersionUID = 7075188646105441127L;
private Long id;
private Date date;
private Integer level;
private String message;
private AlertStatus status;
private UserDto user;
private DrugDto drug;
public AlertDto() {
}
public AlertDto(Alert alert) {
super();
this.id = alert.getId();
this.date = alert.getDate();
this.level = alert.getLevel();
this.message = alert.getMessage();
this.status = alert.getStatus();
this.user = new UserDto(alert.getUser());
this.drug = new DrugDto(alert.getDrug());
}
public AlertDto(Date date, Integer level, String message, AlertStatus status, UserDto user, DrugDto drug) {
super();
this.date = date;
this.level = level;
this.message = message;
this.status = status;
this.user = user;
this.drug = drug;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public AlertStatus getStatus() {
return status;
}
public void setStatus(AlertStatus status) {
this.status = status;
}
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
public DrugDto getDrug() {
return drug;
}
public void setDrug(DrugDto drug) {
this.drug = drug;
}
@Override
public String toString() {
return "Alert [id=" + id + ", date=" + date + ", level=" + level + ", message=" + message + ", status="
+ status + ", user=" + user + ", drug=" + drug + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AlertDto other = (AlertDto) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package msip.go.kr.board.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import msip.go.kr.board.entity.BoardItemOpn;
/**
* 게시판 게시물 의견 데이터 처리를 위한 DAO 클래스 정의
*
* @author 양준호
* @since 2015.07.27
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.27 양준호 최초작성
* </pre>
*/
@Repository("boardItemOpnDAO")
public class BoardItemOpnDAO {
/**
* @PersistenceContext 어노테이션을 이용하여 컨테이너로부터 EntityManger DI
* @param EntityManager em
*/
@PersistenceContext
private EntityManager em;
/**
* 선택된 id 에 따라 게시판 의견 정보를 데이터베이스에서 삭제
* @param BoardItem entity
* @throws Exception
*/
public void remove(BoardItemOpn entity) throws Exception {
em.remove(em.merge(entity));
}
/**
* 새로운 게시판 게시글 의견 정보를 입력받아 데이터베이스에 저장
* @param BoardItemOpn entity
* @throws Exception
*/
public void persist(BoardItemOpn entity) throws Exception {
this.em.persist(entity);
}
/**
* 전체 듸견 목록을 데이터베이스에서 조회
* @return List<BoardItemOpn> 게시판 게시물 목록
* @throws Exception
*/
public List<BoardItemOpn> findAll() throws Exception {
String hql = "from BoardItemOpn c order by c.id";
List<BoardItemOpn> list = em.createQuery(hql, BoardItemOpn.class).getResultList();
return list;
}
/**
* 게시물별 듸견 전체 목록을 데이터베이스에서 조회
* @return List<BoardItemOpn> 게시판 게시물 목록
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<BoardItemOpn> findAllByItemId(Long itemId) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT id, pid, step, itemid, content, reg_id, reg_nm, reg_disp, reg_date ");
hql.append("FROM board_item_opn ");
hql.append("WHERE itemId = :itemId ");
hql.append("START WITH pid IS NULL CONNECT BY PRIOR id = pid ");
hql.append("ORDER SIBLINGS BY id");
Query query = em.createNativeQuery(hql.toString());
query.setParameter("itemId", itemId);
List<Object[]> result = query.getResultList();
List<BoardItemOpn> list = new ArrayList<BoardItemOpn>();
for(Object[] row : result) {
BigDecimal id = (BigDecimal) row[0];
BigDecimal pid = (BigDecimal) row[1];
Integer step = (Integer) row[2];
String content = (String) row[4];
String regId = (String) row[5];
String regNm = (String) row[6];
String regDisp = (String) row[7];
Date regDate = (Date) row[8];
BoardItemOpn opinion = new BoardItemOpn(id.longValue(), (pid == null) ? null : pid.longValue(), step, itemId, content, regId, regNm, regDisp, regDate);
list.add(opinion);
}
return list;
}
/**
* 수정된 게시판 게시물 의견 정보를 데이터베이스에 반영
* @param BoardItemOpn entity
* @throws Exception
*/
public void merge(BoardItemOpn entity) throws Exception {
em.merge(entity);
}
/**
* 선택된 id에 따라 데이터베이스에서 게시판 게시물 의견 정보를 반환
* @param Long id
* @return BoardItemOpn entity
* @throws Exception
*/
public BoardItemOpn findById(Long id) throws Exception{
return em.find(BoardItemOpn.class, id);
}
/**
* 하위의견 수를 조회하며 반환한다.
* @param id 의견일련번호
* @return
* @throws Exception
*/
public int countByPid(Long id) throws Exception {
String hql = "SELECT count(*) FROM BoardItemOpn WHERE pid = :pid";
Query query = em.createQuery(hql.toString());
query.setParameter("pid", id);
Long result = (Long) query.getSingleResult();
return result.intValue();
}
}
|
package artronics.gsdwn.log;
import org.apache.log4j.Logger;
public interface Log
{
Logger SDWN = Logger.getLogger("sdwn");
Logger PACKET = Logger.getLogger("packet");
Logger FILE = Logger.getLogger("file");
}
|
package com.cm.transaction.declarative.annotation;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.JdbcTransactionObjectSupport;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionOperations;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/**
* @autthor Mchi
* @since 2017/11/10
*/
@Configuration
public class AnnotationConfTransaction {
static {
System.setProperty("hikaricp.configurationFile", "data-access/target/classes/dbconf.properties");
}
public static void main(String[] args) {
AnnotationConfigApplicationContext actx = new AnnotationConfigApplicationContext(AnnotationConfTransaction.class);
TransactionOperations template = actx.getBean(TransactionOperations.class);
List<Person> plist = template.execute((TransactionStatus status) -> {
List<Person> ps = new ArrayList<>();
DefaultTransactionStatus dstatus = (DefaultTransactionStatus) status;
JdbcTransactionObjectSupport transaction = (JdbcTransactionObjectSupport) dstatus.getTransaction();
Connection conn = transaction.getConnectionHolder().getConnection();
try {
conn.setReadOnly(true);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM person ");
Person p = null;
while (rs.next()) {
p = new Person();
p.setId(rs.getLong(1));
p.setName(rs.getString("name"));
ps.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
});
plist.stream().filter(p -> p.getId() > 30).forEach(p -> {
System.out.println(p.getId() + ":" + p.getName());
});
}
public DataSource dataSource() {
return new HikariDataSource();
}
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public TransactionOperations template() {
return new TransactionTemplate(txManager());
}
//-----------------------------------------------------------------------
//equivalent
//-----------------------------------------------------------------------
/**
@Bean public DataSource dataSource(){
return new HikariDataSource();
}
@Bean public PlatformTransactionManager txManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
@Bean public TransactionOperations template(PlatformTransactionManager txManager){
return new TransactionTemplate(txManager);
}
**/
}
class Person {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.microservice.counthvip.services;
import java.util.Map;
import com.microservice.counthvip.model.ClientPerson;
import com.microservice.counthvip.model.CountHvip;
import com.microservice.counthvip.model.Firmante;
import com.microservice.counthvip.model.Movement;
import com.microservice.counthvip.model.Titular;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface CountHvipServices {
public Flux<CountHvip> findAll();
public Mono<CountHvip> findById(String id);
public Mono<CountHvip> save(CountHvip counth);
public Mono<Void> delete(CountHvip counth);
public Flux<CountHvip> findByDniClient(String dni);
public Mono<Map<String, Object>> getMoney(String dni);
public Flux<ClientPerson> findAllClientPerson();
public Mono<ClientPerson> findClientPersonById(String id);
public Flux<ClientPerson> findClientPersonByDni(String dni);
public Flux<ClientPerson> findClientPersonByName(String Name);
public Flux<ClientPerson> findClientPersonByLastname(String lastname);
public Mono<ClientPerson> saveClientPerson(ClientPerson clientperson);
public Mono<Void> deleteClientPerson(String idCliente);
public Flux<Titular> findAllTitular();
public Mono<Titular> findByIdTitular(String id);
public Mono<Titular> saveTitular(Titular titular);
public Mono<Void> deleteTitular(Titular titular);
public Flux<Firmante> findAllFirmante();
public Mono<Firmante> findByIdFirmante(String id);
public Mono<Firmante> saveFirmante(Firmante firmante);
public Mono<Void> deleteFirmante(Firmante firmante);
public Flux<Movement> findAllMove();
public Mono<Movement> findByIdMove(String id);
public Mono<Movement> saveMove(Movement move);
public Mono<Void> deleteMove(Movement move);
}
|
package com.example.contactList;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.example.Class.GetAllParams;
import com.example.Class.Person;
import com.example.firstprogram.R;
import com.example.firstprogram.TopBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
/**
* Created by lenovo on 2015/8/4.
*/
public class CheckEmergencyContactActivity extends Activity {
private String string,string1;
private TopBar topBar;
private Person person;
private GetAllParams c1,c2;
private Context mcontext1;
private JSONObject obj1,obj2;
private JSONArray list1;
double height1 ;
private int type;
double weight1 ;
private RequestQueue requestQueue;
private TextView height,weight,gender,age,occupation,location,nick;
private Button delete_;
Long account1;
private static String httpurl = "http://120.24.208.130:1503/user/get_information";
private static String httpur2 = "http://120.24.208.130:1503/user/relation_manage";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_contact_activity);
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
string = bundle.getString("account");
person = (Person) getApplication();
account1=Long.parseLong(string);
Log.d("TAG","have you get the right account?"+account1);
TextView textView = (TextView) (findViewById(R.id.my_infor_phone_textview));
textView.setText(string);
height =(TextView)findViewById(R.id.my_infor_height_textview);
weight = (TextView) findViewById(R.id.my_infor_weight_textview);
location = (TextView) findViewById(R.id.my_infor_location_textview);
age = (TextView) findViewById(R.id.my_infor_age_textview);
nick = (TextView) findViewById(R.id.my_infor_nick2_textview);
occupation = (TextView)findViewById(R.id.my_infor_occupation_textview);
delete_ = (Button) findViewById(R.id.delete);
gender = (TextView) findViewById(R.id.my_infor_gender_textview);
// Log.d("TAG","person.gender "+person.getGender());
//设置topbar点击事件
topBar = (TopBar) findViewById(R.id.topbar_in_check_contact_activity);
topBar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
@Override
public void leftClick() {
finish();
}
@Override
public void rightClick() throws UnsupportedEncodingException {
}
});
//设置删除好友点击事件
delete_.setOnClickListener(new delete_listener());
requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject map = new JSONObject();
try {
Log.d("TAG","account1111111111111111111111"+account1);
map.put("account", account1);
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST,
httpurl, map, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.d("TAG","JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ"+jsonObject.toString());
try {
//获得住址
if(jsonObject.getString("status") != "500") {
if (jsonObject.getString("location") != null) {
Log.d("TAG", "location exsit?" + jsonObject.getString("location"));
location.setText(jsonObject.getString("location"));
}
//获得昵称
Log.d("TAG","nickkkkkkkkkkkkkkkkkkkkkkkkkk"+jsonObject.getString("nickname"));
nick.setText(jsonObject.getString("nickname"));
//获得年纪
if(String.valueOf(jsonObject.getInt("age"))!=null) {
Log.d("TAG", "ageeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + jsonObject.getInt("age"));
age.setText(String.valueOf(jsonObject.getInt("age")));
}
else
age.setText("0");
//获得职业
if(String.valueOf(jsonObject.getInt("occupation"))!=null) {
Log.d("TAG", "occupationnnnnnnnnnnnnnnnnnnnnnnnnnnn" + jsonObject.getInt("occupation"));
if (jsonObject.getInt("occupation") == 0) {
occupation.setText("学生");
} else if (jsonObject.getInt("occupation") == 1) {
occupation.setText("教师");
} else if (jsonObject.getInt("occupation") == 2) {
occupation.setText("医生");
} else if (jsonObject.getInt("occupation") == 3) {
occupation.setText("程序员");
} else {
occupation.setText("其他");
}
Log.d("TAG", "have occupation set successly?");
}
//获得性别
Log.d("TAG","genderrrrrrrrrrrrrrrrrrrrrrrrrrrr"+jsonObject.getInt("gender"));
if (String.valueOf(jsonObject.getInt("gender")) != null) {
if (jsonObject.getInt("gender") == 0) {
gender.setText("女");
} else {
gender.setText("男");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("TAG", volleyError.toString());
}
});
requestQueue.add(jsonRequest);
} catch (JSONException e) {
e.printStackTrace();
}
// JSONObject temp1 = new JSONObject();
// anwser1 = new JSONObject();
// c1 = new GetAllParams(mcontext1);
// obj1 = new JSONObject();
// try {
// obj1.put("account",account1);
// Log.d("TAG", "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT" + account1);
// temp1 = c1.getList(httpurl, obj1, new GetAllParams.VolleyJsonCallback() {
// // Log.d("TAGG","HAVE YOU ENTERED?");
// @Override
//
// public void onSuccess(JSONObject result) {
//
// Log.d("TAG", "result ----------------------------------------------------> " + result.toString());
// anwser1 = result;
// try {
// //获得住址
// location.setText(anwser1.getString("location"));
// //获得职业
// if (anwser1.getInt("occupation") == 0){
// occupation.setText("学生");
// }else if (anwser1.getInt("occupation") == 1){
// occupation.setText("教师");
// }
// else if (anwser1.getInt("occupation") == 2){
// occupation.setText("医生");
// }
// else if (anwser1.getInt("occupation") == 3){
// occupation.setText("程序员");
// }
// else if (anwser1.getInt("occupation") == 4){
// occupation.setText("其他");
// }
// //获得昵称
// nick.setText(anwser1.getString("nick"));
// //获得年纪
// age.setText(anwser1.getInt("age"));
// //获得性别
// if (anwser1.getInt("gender") == 0) {
// gender.setText("女");
// } else if (anwser1.getInt("gender") == 1) {
// gender.setText("男");
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// }
// });
// } catch (Exception e) {
// e.printStackTrace();
// }
/* // 查询用户身体数据中的身高和体重
JSONObject temp2 = new JSONObject();
anwser2 = new JSONObject();
c2 = new GetAllParams(mcontext2);
obj2 = new JSONObject();
try {
obj1.put("id", ); // 查询用户身体数据中的身高和体重
temp1 = c2.getList(httpurl, obj2, new GetAllParams.VolleyJsonCallback() {
@Override
public void onSuccess(JSONObject result) {
Log.d("TAG", "result -> " + result.toString());
anwser1 = result;
//Log.d("TAG", "list -> " + list.toString());
if(anwser1 != null ) {
try {
list1 = new JSONArray();
list1 = anwser1.getJSONArray("health_list");
//获取health_list中身高最近的一条记录
for (int i = 0; i < list1.length() - 1 ; i++) {
JSONObject jo1 = (JSONObject) list1.get(i);
if(jo1.getInt("type") == 3) { //type 3 表示身高
height1 = jo1.getDouble("value");//获取身高
Log.d("TAG","height1 "+jo1.getDouble("value"));
Log.d("TAG", "height1 " + height1);
height.setText(String.valueOf(height1));
Log.d("TAG","HHHHHHHHHHHHHHHH");
break;
}
}
//获取health_list中体重最近的一条记录
for (int i = 0; i < list1.length() - 1 ; i++) {
JSONObject jo2 = (JSONObject) list1.get(i);
if(jo2.getInt("type") == 4) { //type 4 表示体重
weight1 = jo2.getDouble("value");//获取体重
Log.d("TAG","WWWWWWWWWWWWWWWW");
Log.d("TAG", "weight1 " + weight1);
weight.setText(String.valueOf(weight1));
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
else { //没有修改记录
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
*/
}
//删除按钮的点击事件函数
private class delete_listener implements View.OnClickListener{
@Override
public void onClick(View v) {
//弹出对话框,询问是否确定添加为好友
AlertDialog.Builder dialog = new AlertDialog.Builder(CheckEmergencyContactActivity.this);
dialog.setMessage("是否删除好友?");
dialog.setTitle("提示");
dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//发出添加请求
JSONObject map1 = new JSONObject();
Log.d("TAG","account!!!!!!!!!!!!!!!!!"+account1);
Log.d("TAG","person.getid success?"+person.getId());
try {
map1.put("id", person.getId());
map1.put("user_account", account1);
map1.put("operation",0);
map1.put("type",0);
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST,httpur2 , map1, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject jsonObject1) {
Log.d("TAG", jsonObject1.toString());
try {
Log.d("TAG","delete success????????????????"+jsonObject1.getInt("status"));
if (jsonObject1.getInt("status") == 200) {
Log.d("TAG", "delete success");
Toast.makeText(CheckEmergencyContactActivity.this, "delete success", Toast.LENGTH_SHORT).show();
//写入本地数据库
// db.insert(add_account, add_nickname, add_image);
// Intent mIntent = new Intent();
// mIntent.putExtra("account", String.valueOf(add_account));
// mIntent.putExtra("nickname", add_nickname);
// 设置结果,并进行传送
// CheckContactActivity.this.setResult(1, mIntent);
finish();
} else {
Toast.makeText(CheckEmergencyContactActivity.this, "delete failed", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//添加请求失败
Toast.makeText(CheckEmergencyContactActivity.this, "service connection failed", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonRequest);
}
});
dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.create().show();
}
}
}
|
package test;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.sinodynamic.hkgta.integration.spa.em.AppointmentStatus;
import com.sinodynamic.hkgta.integration.spa.em.CustomPaymentMethod;
import com.sinodynamic.hkgta.integration.spa.em.Gender;
import com.sinodynamic.hkgta.integration.spa.request.AddGuestRequest;
import com.sinodynamic.hkgta.integration.spa.request.AppointmentCancelRequest;
import com.sinodynamic.hkgta.integration.spa.request.AppointmentDetailsRequest;
import com.sinodynamic.hkgta.integration.spa.request.AppointmentListRequest;
import com.sinodynamic.hkgta.integration.spa.request.AvailableRoomsRequest;
import com.sinodynamic.hkgta.integration.spa.request.BookAppointmentRequest;
import com.sinodynamic.hkgta.integration.spa.request.CCPaymentRequest;
import com.sinodynamic.hkgta.integration.spa.request.CashPaymentRequest;
import com.sinodynamic.hkgta.integration.spa.request.GetAppointmentsRequest;
import com.sinodynamic.hkgta.integration.spa.request.GetAvailableTimeSlotsRequest;
import com.sinodynamic.hkgta.integration.spa.request.GetCenterTherapistsRequest;
import com.sinodynamic.hkgta.integration.spa.request.GetPaymentsRequest;
import com.sinodynamic.hkgta.integration.spa.request.GetServiceDetailsRequest;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceCancelRequest;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceDetails;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceDetailsList;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceItemsList;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceRevenueRequest;
import com.sinodynamic.hkgta.integration.spa.request.InvoiceVoidRequest;
import com.sinodynamic.hkgta.integration.spa.request.PaymentByCustomRequest;
import com.sinodynamic.hkgta.integration.spa.request.PaymentsList;
import com.sinodynamic.hkgta.integration.spa.request.QueryStatePKRequest;
import com.sinodynamic.hkgta.integration.spa.request.ServiceInfoItem;
import com.sinodynamic.hkgta.integration.spa.request.ServicesListByCategoryCodeRequest;
import com.sinodynamic.hkgta.integration.spa.request.SubCategoriesListRequest;
import com.sinodynamic.hkgta.integration.spa.request.TherapistRequestType;
import com.sinodynamic.hkgta.integration.spa.request.TherapistsAvailableForServiceRequest;
import com.sinodynamic.hkgta.integration.spa.request.UpdateGuestRequest;
import com.sinodynamic.hkgta.integration.spa.response.AppointmentCancelResponse;
import com.sinodynamic.hkgta.integration.spa.response.AppointmentDatum;
import com.sinodynamic.hkgta.integration.spa.response.AppointmentDetailsResponse;
import com.sinodynamic.hkgta.integration.spa.response.AppointmentServiceCancelResponse;
import com.sinodynamic.hkgta.integration.spa.response.AvailableRoomsResponse;
import com.sinodynamic.hkgta.integration.spa.response.BookAppointmentResponse;
import com.sinodynamic.hkgta.integration.spa.response.CCPaymentResponse;
import com.sinodynamic.hkgta.integration.spa.response.CashPaymentResponse;
import com.sinodynamic.hkgta.integration.spa.response.CountryListResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetAppointmentsResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetAvailableTherapistsResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetAvailableTimeSlotsResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetInvoiceRevenueResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetPaymentsResponse;
import com.sinodynamic.hkgta.integration.spa.response.GetSubcategoriesResponse;
import com.sinodynamic.hkgta.integration.spa.response.GuestAppointmentsListResponse;
import com.sinodynamic.hkgta.integration.spa.response.InvoiceVoidResponse;
import com.sinodynamic.hkgta.integration.spa.response.Payment;
import com.sinodynamic.hkgta.integration.spa.response.PaymentByCustomResponse;
import com.sinodynamic.hkgta.integration.spa.response.QueryCategoryResponse;
import com.sinodynamic.hkgta.integration.spa.response.QueryCenterTherapistsResponse;
import com.sinodynamic.hkgta.integration.spa.response.QueryServiceListResponse;
import com.sinodynamic.hkgta.integration.spa.response.RegistGuestResponse;
import com.sinodynamic.hkgta.integration.spa.response.ServiceDetailsResponse;
import com.sinodynamic.hkgta.integration.spa.response.SetInvoiceDetails;
import com.sinodynamic.hkgta.integration.spa.response.StatePKResponse;
import com.sinodynamic.hkgta.integration.spa.response.UpdateGuestResponse;
import com.sinodynamic.hkgta.integration.spa.service.SpaServcieManager;
import com.sinodynamic.hkgta.integration.util.MMSAPIException;
import com.sinodynamic.hkgta.integration.util.SetInvoiceDetailsDeserializer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/context-test.xml"})
public class SpaServcieManagerTest {
@Autowired
private SpaServcieManager spaServcieManager;
@Test
public void testRegistGuest() throws MMSAPIException {
AddGuestRequest guest = new AddGuestRequest();
guest.setFirstName("Miranda");
guest.setLastName("test for250");
guest.setMobilePhone("5548972251");
guest.setEmail("abc2@250.com");
guest.setGender(Gender.MALE.getCode());
//guest.setGuestCode("0000046");
RegistGuestResponse result = spaServcieManager.registGuest(guest);
System.out.println(result);
}
@Test
public void testUpdateGuest() throws MMSAPIException {
UpdateGuestRequest guest = new UpdateGuestRequest();
guest.setFirstName("Nick1");
guest.setLastName("Xiong");
guest.setMobilePhone("9874 561");
guest.setEmail("xls@163.com");
guest.setGender(Gender.MALE.getCode());
guest.setGuestId("8b955ee1-701b-46ad-9551-6210f2768274");
guest.setZipCode("518000");
guest.setAddress1("add1");
guest.setAddress2("addr2");
guest.setCity("sz");
guest.setCountryId("45");
guest.setStateId("812");
/*guest.setPasswordOld("");
guest.setPasswordNew1("11111111");
guest.setPasswordNew2("11111111");*/
UpdateGuestResponse result = spaServcieManager.updateGuest(guest);
System.out.println(result);
}
@Test
public void categoriesList() throws MMSAPIException {
QueryCategoryResponse result = spaServcieManager.getCategoriesList();
System.out.println(result);
}
@Test
public void testqueryServiceList() throws MMSAPIException {
ServicesListByCategoryCodeRequest request = new ServicesListByCategoryCodeRequest();
request.setCategoryCode("1");
QueryServiceListResponse result = spaServcieManager.getServicesListByCategoryCode(request);
System.out.println(result);
}
@Test
public void testQueyrServiceDetails() throws MMSAPIException {
GetServiceDetailsRequest request = new GetServiceDetailsRequest();
request.setServiceCode("Service1");
ServiceDetailsResponse result = spaServcieManager.queryServiceDetails(request);
System.out.println(result);
}
@Test
public void queryCountryList()throws MMSAPIException {
CountryListResponse result = spaServcieManager.queryCountryList();
System.out.println(result);
}
@Test
public void queryStatePK()throws MMSAPIException {
QueryStatePKRequest request = new QueryStatePKRequest();
request.setCountryCode("CN");
request.setStatename("Hubei Province");
StatePKResponse result = spaServcieManager.queryStatePK(request);
System.out.println(result);
}
@Test
public void queryAvailableRooms() throws Exception {
AvailableRoomsRequest request = new AvailableRoomsRequest();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = df.parse("2015-09-09 10:00:00");
request.setServiceCode("Service1");
request.setStartDate(startDate);
AvailableRoomsResponse result = spaServcieManager.queryAvailableRooms(request);
System.out.println(result);
}
@Test
public void getCenterTherapists() throws Exception {
GetCenterTherapistsRequest request = new GetCenterTherapistsRequest();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date requestDate = df.parse("2015-12-14");
request.setRequestDate(requestDate);
QueryCenterTherapistsResponse result = spaServcieManager.getCenterTherapists(request);
System.out.println(result);
}
@Test
public void bookAppointment() throws Exception {
BookAppointmentRequest parameter = new BookAppointmentRequest();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime = df1.parse("2015-12-26 18:30:00");
Date endTime = df1.parse("2015-12-26 19:00:00");
parameter.setGuestCode("0000001");
parameter.setStartTime(startTime);
List<ServiceInfoItem> serviceInfo = new ArrayList<ServiceInfoItem>();
ServiceInfoItem item1 = new ServiceInfoItem();
item1.setServiceCode("test0001");
item1.setTherapistCode("J001");
//item1.setStartTime(startTime);
//item1.setEndTime(endTime);
item1.setRoomCode("BLSR002");
item1.setTherapistRequestType(TherapistRequestType.MALE);
serviceInfo.add(item1);
/*ServiceInfoItem item2 = new ServiceInfoItem();
item2.setServiceCode("test0001");
item2.setTherapistCode("J001");
//item1.setStartTime(startTime);
//item1.setEndTime(endTime);
item2.setRoomCode("BLSR002");
item2.setTherapistRequestType(TherapistRequestType.MALE);
serviceInfo.add(item2);*/
parameter.setServiceInfo(serviceInfo);
//parameter.setInvoiceNo("442");
BookAppointmentResponse result = spaServcieManager.bookAppointment(parameter);
System.out.println(result);
}
@Test
public void getAvailableTimeSlots() throws Exception {
GetAvailableTimeSlotsRequest parameter = new GetAvailableTimeSlotsRequest();
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime = df2.parse("2015-12-19 07:00:00");
parameter.setStartTime(startTime);
parameter.setTherapistRequestType("2");
parameter.setAdvanceBookingSlots(false);
parameter.setAllAvailableSlots(false);
parameter.setCheckRoomAvailablity(true);
parameter.setTherapistCode("H001");
List<String> serviceCodeList = new ArrayList<String>();
//serviceCodeList.add("Service1");
serviceCodeList.add("test0001");
parameter.setServiceCodeList(serviceCodeList);
GetAvailableTimeSlotsResponse response = spaServcieManager.getAvailableTimeSlots(parameter);
System.out.println(response);
}
@Test
public void cashPayment() throws Exception {
CashPaymentRequest parameter = new CashPaymentRequest();
parameter.setInvoiceNo("553");
parameter.setGuestCode("mms01");
parameter.setAmountPaid(new BigDecimal(500));
//parameter.setTipAmount(new BigDecimal(0));
CashPaymentResponse response = spaServcieManager.cashPayment(parameter);
System.out.println(response);
}
@Test
public void creditCardPayment() throws MMSAPIException {
CCPaymentRequest parameters = new CCPaymentRequest();
parameters.setInvoiceNo("550");
parameters.setGuestCode("mms01");
parameters.setAmountPaid(new BigDecimal(1000));
parameters.setTipAmount(new BigDecimal(0));
parameters.setCCNumber("8888888888");
parameters.setExpiryDate(new Date());
parameters.setCardType("Visa");
parameters.setBankName("BankName");
parameters.setSecurityCode("000");
CCPaymentResponse response = spaServcieManager.creditCardPayment(parameters);
System.out.println(response);
}
@Test
public void subcategoriesList()throws MMSAPIException {
SubCategoriesListRequest request = new SubCategoriesListRequest();
request.setCategoryCode("1");
GetSubcategoriesResponse response = spaServcieManager.getSubCategoriesListByCode(request);
System.out.println(response);
}
@Test
public void SetInvoiceDetails()throws MMSAPIException {
InvoiceItemsList obj = new InvoiceItemsList();
obj.setGuid("0965805f-4478-4ee1-a8f9-c874d8d899b8");
obj.setFirstName("raghav");
obj.setLastName("g");
obj.setPhoneNumber("9849853248");
obj.setGender(Gender.MALE.getCode());
obj.setSaleByEmployeeId("undefined");
obj.setPrice(new BigDecimal(3000));
obj.setDiscount("0");
obj.setFinalSalePrice(new BigDecimal(3000));
obj.setTaxes(new BigDecimal(0));
obj.setCreatedByEmployeeGUID("d01486e6-0daf-43a6-bf9b-468923e10da0");
obj.setQuantity(1);
obj.setGuestEmailId("graghav@sohamonline.com");
//obj.setStartTime(new Date());
//obj.setEndTime(new Date());
PaymentsList pay = new PaymentsList();
pay.setPaymentInstrument("CashDetails");
pay.setAmexNumber("88888888");
pay.setAmexExpiry("12/25");
pay.setAmexRcptNumber("123456");
pay.setAmount(new BigDecimal(3000));
InvoiceDetails invoice = new InvoiceDetails();
invoice.setCenterId("7737a338-89e4-4492-9cd1-3dca4f6c9e72");
invoice.setInvoiceNo("1f97ddaa");
invoice.setInvoiceItemsList(obj);
invoice.setPaymentsList(pay);
InvoiceDetailsList invoiceDetailsList = new InvoiceDetailsList();
List<InvoiceDetails> list = new ArrayList<InvoiceDetails>();
list.add(invoice);
invoiceDetailsList.setInvoiceDetailsList(list);
List<SetInvoiceDetails> response = spaServcieManager.setInvoiceDetails(invoiceDetailsList);
System.out.println("response=" + response);
}
@Test
public void therapistsAvailableForService() throws MMSAPIException, ParseException{
TherapistsAvailableForServiceRequest request = new TherapistsAvailableForServiceRequest();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date requestDate = df.parse("2015-12-14");
request.setRequestDate(requestDate);
request.setServiceCode("Service1");
request.setType(TherapistRequestType.ANY);
GetAvailableTherapistsResponse response = spaServcieManager.therapistsAvailableForService(request);
System.out.println(response);
}
@Test
public void invoiceVoid() {
InvoiceVoidRequest parameters = new InvoiceVoidRequest();
parameters.setComments("my comments");
parameters.setInvoiceNo("24");
parameters.setUserCode("userCode");
InvoiceVoidResponse response = spaServcieManager.invoiceVoid(parameters);
System.out.println(response);
}
@Test
public void guestAppointmentsList() {
AppointmentListRequest request = new AppointmentListRequest();
request.setGuestCode("mms01");
request.setStart(0);
request.setLimit(10);
GuestAppointmentsListResponse response = spaServcieManager.guestAppointmentsList(request);
System.out.println(response);
}
@Test
public void appointmentCancel() {
InvoiceCancelRequest request = new InvoiceCancelRequest();
request.setInvoiceNo("141");
AppointmentCancelResponse response = spaServcieManager.appointmentCancel(request);
System.out.println(response);
}
@Test
public void appointmentDetails() {
AppointmentDetailsRequest request = new AppointmentDetailsRequest();
request.setInvoiceNo("141");
AppointmentDetailsResponse response = spaServcieManager.appointmentDetails(request);
System.out.println(response);
}
@Test
public void getInvoiceRevenue() throws ParseException{
//for(int i=0; i <=100;i++) {
InvoiceRevenueRequest request = new InvoiceRevenueRequest();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date startTime = df1.parse("2015-12-03");
Date endTime = df1.parse("2015-12-04");
request.setFromDate(startTime);
request.setToDate(endTime);
GetInvoiceRevenueResponse response = spaServcieManager.getInvoiceRevenue(request);
System.out.println( response);
//}
}
@Test
public void getAppointments()throws ParseException{
try{
GetAppointmentsRequest request = new GetAppointmentsRequest();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date startTime = df1.parse("2015-12-25");
Date endTime = df1.parse("2015-12-25");
request.setFromDate(startTime);
request.setToDate(endTime);
request.setStatus(AppointmentStatus.OPEN);
GetAppointmentsResponse response = spaServcieManager.getAppointments(request);
List<AppointmentDatum> list = response.getAppointmentData();
System.out.println("total:"+list.size());
for(AppointmentDatum appointmentDatum :list){
System.out.print(appointmentDatum.getInvoiceNo()+" "+appointmentDatum.getStatus()+ " "+appointmentDatum.getServiceCode());
System.out.print(" start "+appointmentDatum.getStartTime());
System.out.print(" end "+appointmentDatum.getEndTime());
System.out.print(" create "+appointmentDatum.getCreationDate());
System.out.print(" checkin "+appointmentDatum.getCheckInTime());
System.out.println("");
}
} catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void paymentByCustom() {
PaymentByCustomRequest parameters = new PaymentByCustomRequest();
parameters.setInvoiceNo("308");
parameters.setAmountPaid(new BigDecimal(100));
parameters.setTipAmount(new BigDecimal(0));
parameters.setPaymentMethod(CustomPaymentMethod.CASHVALUE);
PaymentByCustomResponse response = spaServcieManager.paymentByCustom(parameters);
System.out.println(response);
}
@Test
public void getPayments() throws ParseException {
GetPaymentsRequest request = new GetPaymentsRequest();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date startTime = df1.parse("2015-12-18");
Date endTime = df1.parse("2015-12-18");
request.setFromDate(startTime);
request.setToDate(endTime);
GetPaymentsResponse response = spaServcieManager.getPayments(request);
List<Payment> list = response.getPayments();
System.out.println("total:"+list.size());
for(Payment payment :list){
System.out.println(payment.getInvoiceNo()+" "+payment.getPaymentDate()+ " "+payment.getPaymentType() +" "+payment.getTipAmount()+" "+payment.getCustomName());
}
System.out.println(response);
}
@Test
public void test() {
String json = "[{\"Invoice-No\":\"1f97ddaa\",\"status\":\"1\"},{\"Invoice-No\":\"1f97ddaa\",\"status\":\"1\"}]";
System.out.println(json);
List<SetInvoiceDetails> response = null;
Type listType = new TypeToken<List<SetInvoiceDetails>>(){}.getType();
//response = GsonUtil.fromJson(json, listType);
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(SetInvoiceDetails.class, new SetInvoiceDetailsDeserializer());
Gson gson = gsonBuilder.create();
response = gson.fromJson(json, listType);
System.out.println(response);
}
@Test
public void appointmentServiceCancel() {
AppointmentCancelRequest request = new AppointmentCancelRequest();
String appointmentId ="308ea017-c00e-414b-8267-88289599ad66";
String comments ="yeyeye";
request.setAppointmentId(appointmentId);
request.setComments(comments);
AppointmentServiceCancelResponse response = spaServcieManager.appointmentServiceCancel(request);
System.out.println(response);
}
@Test
public void test2() {
String desc = " CSH-566611799990";
String transactionType = StringUtils.substring(desc.trim(), 0, 3);
System.out.println(transactionType);
}
}
|
package com.fanfte.designPattern.decorator;
public class PacketHTMLHeaderCreator extends PacketDecorator{
public PacketHTMLHeaderCreator(IPackeetCreator component) {
super(component);
}
@Override
public String handleContent() {
StringBuffer sb = new StringBuffer();
sb.append("<html>").append("<head>");
sb.append(component.handleContent());
sb.append("</body>").append("</html>");
return sb.toString();
}
}
|
public class B3main {
public static void main(String[] args)
{
B3view ins=new B3view();
}
}
|
package com.mediafire.sdk.api.responses;
import com.mediafire.sdk.api.responses.data_models.FileInfo;
import com.mediafire.sdk.api.responses.data_models.FileInfos;
import java.util.List;
public class FileGetInfoResponse extends ApiResponse {
private FileInfo file_info;
private List<FileInfos> file_infos;
public FileInfo getFileInfo() {
return this.file_info;
}
public List<FileInfos> getFileInfos() {
return file_infos;
}
}
|
package com.junkstoreapp.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
/**
* @author David VanDusen.
*/
@Service
@Profile("!production")
public class LoggingEmailService implements EmailService {
private static final Logger LOG = LoggerFactory.getLogger(LoggingEmailService.class);
@Override
public void send(String toName, String toEmail, String subject, String textMessage) {
LOG.info("Logging email...\nTo: \"{}\" <{}>\nSubject: {}\nMessage:\n{}", toName, toEmail, subject, textMessage);
}
}
|
package com.programapprentice.app;
import com.programapprentice.util.TreeNode;
/**
* User: program-apprentice
* Date: 8/9/15
* Time: 12:13 PM
*/
public class SameTree_100 {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) {
return true;
}
if(p == null || q == null) {
return false;
}
if(p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
|
/*
* 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 PRESTACIONES;
import Clases.CalculosPrestaciones.Indemnizacion;
import Clases.CalculosPrestaciones.classIndemnizacion;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author jluis
*/
public class CalculoIndemnización extends javax.swing.JInternalFrame {
DecimalFormat formatter3 = new DecimalFormat("0.00");
double salariototal;
Double salariopromedio12m;
/**
* Creates new form CalculoIndemnización
*/
public CalculoIndemnización() {
initComponents();
}
private void buscar() {
try {
classIndemnizacion p = Indemnizacion.buscarEmpleado(Integer.parseInt(Codigo.getText()));
Nombre.setText(p.getNombre());// + ' ' + p.getApellidos());
Salario.setText(formatter3.format(p.getSalario()));
Bonificacion.setText(formatter3.format(p.getBonificacion()));
FechaIngre.setText(p.getFechaIngre());
buscapromedio6meses();
ListarUltimosMesesLaborados();
buscapromedio12meses();
calculoIndemnizacion();
Calculoaguinaldo();
CalculoBono14();
horaextra();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERRORRRR" + e);
}
}
private void buscapromedio6meses(){
try {
classIndemnizacion p = Indemnizacion.PromedioSalarioDias(Integer.parseInt(Codigo.getText()));
salariopromedio.setText(formatter3.format(p.getSalario()));
diasLaborados.setText(String.valueOf(p.getDias()));
salariototal = p.getSalariopromedio();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERRORRRR" + e);
}
}
private void buscapromedio12meses(){
try {
classIndemnizacion p = Indemnizacion.PromedioSalario12meses(Integer.parseInt(Codigo.getText()));
salariopromedio12m = p.getSalariopromedio12();
salariopromedio12.setText(String.valueOf(salariopromedio12m));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERRORRRR" + e);
}
}
private void calculoIndemnizacion(){
try {
Double a = ((Double.parseDouble(salariopromedio.getText())));
Double b = (Double.parseDouble(salariopromedio.getText()));
Double c = a/365;
Double d = c *(Integer.parseInt(diasLaborados.getText()));
indemniacion.setText(formatter3.format(d));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERRORRRR" + e);
}
}
private void horaextra(){
Double a = Double.parseDouble(Salario.getText());
Double b = Double.parseDouble(Bonificacion.getText());
Double c = (((a+b)-250)/30)*7/44*1.5;
precioHoraExtra.setText(formatter3.format(c));
}
private void CalculoVacaciones(){
//Double a = Double.parseDouble(DiasVaciones.getText());
int a = (Integer.parseInt(diasLaboradosVacaciones.getText()));
int d = (Integer.parseInt(DiasVaciones.getText()));
Double b = (salariopromedio12m/365)*d;
Double c = (b/30)*a;
System.out.println("VACACIONES = "+b+" -- "+a+" -- "+d);
Vacaciones.setText(formatter3.format(c));
}
private void Calculoaguinaldo(){
Double a = (salariopromedio12m/365);
int b = (Integer.parseInt(DiasAguinaldo.getText()));
Double c = a*b;
Aguinaldo.setText(formatter3.format(c));
}
private void CalculoBono14(){
Double a = (salariopromedio12m/365);
int b = (Integer.parseInt(DiasBono14.getText()));
Double c = a*b;
Bono14.setText(formatter3.format(c));
}
private void salariohorasbonicficacion(){
Double a = (salariopromedio12m/30)* Double.parseDouble(DiasPendientes.getText());//ultino salario
salariosPendientes.setText(formatter3.format(a));
Double b = (250/30)* Double.parseDouble(DiasPendientes.getText());
BonificacionPendiente.setText(formatter3.format(b));
Double c = (Double.parseDouble(precioHoraExtra.getText()))* Double.parseDouble(HorasE.getText());
HorasExtras.setText(formatter3.format(c));
}
private void ListarUltimosMesesLaborados(){
ArrayList<classIndemnizacion> result1 = Indemnizacion.ListarUltimosMeses(Integer.parseInt(Codigo.getText()));
Listar(result1);
}
private void Listar(ArrayList<classIndemnizacion> list1) {
Object[][] datos = new Object[list1.size()][3];
int i = 0;
for(classIndemnizacion t : list1)
{
datos[i][0] = t.getSalario();
datos[i][1] = t.getFecha();
datos[i][2] = t.getDias();//+' '+t.getApellidos();
i++;
}
UltimosMeses.setModel(new javax.swing.table.DefaultTableModel(
datos,
new String[]{
"SALARIO DEVENGADO","FECHA","DIAS TRABAJADOS"
})
{
@Override
public boolean isCellEditable(int row, int column){
return false;
}
});
/*TableColumn columna1 = Evaluaciones.getColumn("No.");
columna1.setPreferredWidth(0);
TableColumn columna2 = Evaluaciones.getColumn("CODIGO");
columna2.setPreferredWidth(0);
TableColumn columna3 = Evaluaciones.getColumn("NOMBRE");
columna3.setPreferredWidth(150);
TableColumn columna4 = Evaluaciones.getColumn("PUESTO");
columna4.setPreferredWidth(150);
*/
}
/**
* 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();
jLabel1 = new javax.swing.JLabel();
Codigo = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
Nombre = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
Salario = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
Bonificacion = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
FechaIngre = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
UltimosMeses = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
Bono14 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
salariosPendientes = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
BonificacionPendiente = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
HorasExtras = new javax.swing.JTextField();
jPanel5 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
indemniacion = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
Vacaciones = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
Aguinaldo = new javax.swing.JTextField();
jPanel6 = new javax.swing.JPanel();
diasLaborados = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
salariopromedio = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
salariopromedio12 = new javax.swing.JTextField();
jPanel7 = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
precioHoraExtra = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
HorasE = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
DiasVaciones = new javax.swing.JTextField();
jDateChooser1 = new com.toedter.calendar.JDateChooser();
jLabel18 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
DiasPendientes = new javax.swing.JTextField();
jPanel8 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
diasLaboradosVacaciones = new javax.swing.JTextField();
jLabel20 = new javax.swing.JLabel();
DiasAguinaldo = new javax.swing.JTextField();
jLabel21 = new javax.swing.JLabel();
DiasBono14 = new javax.swing.JTextField();
setClosable(true);
setTitle("Calculo Indemnización");
jPanel1.setBackground(new java.awt.Color(153, 204, 255));
jLabel1.setText("CODIGO");
Codigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CodigoActionPerformed(evt);
}
});
jLabel2.setText("NOMBRE");
Nombre.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
Nombre.setForeground(new java.awt.Color(51, 51, 255));
Nombre.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NombreActionPerformed(evt);
}
});
jLabel12.setText("SALARIO");
Salario.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
Salario.setForeground(new java.awt.Color(51, 51, 255));
jLabel13.setText("BONIFICACION");
Bonificacion.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
Bonificacion.setForeground(new java.awt.Color(51, 51, 255));
jLabel17.setText("FECHA INGRESO");
FechaIngre.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
FechaIngre.setForeground(new java.awt.Color(51, 51, 255));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel12)
.addComponent(jLabel13)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Salario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(Nombre, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Bonificacion)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(FechaIngre, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(Nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(Salario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(Bonificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(FechaIngre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
UltimosMeses.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"SALARIO DEVENGADO", "FECHA", "DIAS TRABAJADOS"
}
));
jScrollPane1.setViewportView(UltimosMeses);
jLabel8.setText("BONO 14");
jButton2.setText("CALCULAR");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton1.setText("IMPRIMIR");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8))
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(Bono14, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(49, 49, 49)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Bono14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24)
.addComponent(jButton2)
.addGap(27, 27, 27)
.addComponent(jButton1)
.addContainerGap(27, Short.MAX_VALUE))
);
jLabel9.setText("SALARIOS PENDIENTES");
jLabel10.setText("BONIFICACION PENDIENTE");
jLabel11.setText("HORAS EXTRAORIDANARIAS PENDIENTES");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(HorasExtras, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(BonificacionPendiente, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(salariosPendientes, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(salariosPendientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BonificacionPendiente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(HorasExtras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
jLabel5.setText("INDEMNIZACION");
jLabel6.setText("VACACIONES");
jLabel7.setText("AGUINALDO");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(Vacaciones, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
.addComponent(indemniacion)
.addComponent(Aguinaldo))
.addContainerGap(11, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(indemniacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Vacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Aguinaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(26, Short.MAX_VALUE))
);
jLabel4.setText("DIAS LABORADOS");
jLabel3.setText("SALARIO PROMEDIO");
jLabel22.setText("SALARIO PROMEDIO 12 meses");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(salariopromedio, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(diasLaborados, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(salariopromedio12)
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(salariopromedio12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22))
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(diasLaborados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(salariopromedio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)))
.addContainerGap(17, Short.MAX_VALUE))
);
jLabel14.setText("PRECIO HORA EXTRA");
precioHoraExtra.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
precioHoraExtra.setForeground(new java.awt.Color(51, 51, 255));
precioHoraExtra.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
precioHoraExtraActionPerformed(evt);
}
});
jLabel15.setText("HORAS EXTRAS PENDIENTES");
HorasE.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
HorasE.setForeground(new java.awt.Color(51, 51, 255));
HorasE.setText("0");
HorasE.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HorasEActionPerformed(evt);
}
});
jLabel16.setText("DIAS DE VACACIONES");
DiasVaciones.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
DiasVaciones.setForeground(new java.awt.Color(51, 51, 255));
DiasVaciones.setText("10");
DiasVaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DiasVacionesActionPerformed(evt);
}
});
jLabel18.setText("FECHA DE BAJA");
jLabel23.setText("DIAS PENDIENTES");
DiasPendientes.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
DiasPendientes.setForeground(new java.awt.Color(51, 51, 255));
DiasPendientes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DiasPendientesActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel23)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15)
.addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING))
.addComponent(jLabel18))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
.addComponent(precioHoraExtra)
.addComponent(HorasE)
.addComponent(DiasVaciones))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(DiasPendientes, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE))
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(precioHoraExtra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(HorasE, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(DiasPendientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DiasVaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18))
.addGap(12, 12, 12))
);
jLabel19.setText("DIAS LABORADOS VACACIONES");
diasLaboradosVacaciones.setText("150");
diasLaboradosVacaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
diasLaboradosVacacionesActionPerformed(evt);
}
});
jLabel20.setText("DIAS LABORADOS AGUINALDO");
DiasAguinaldo.setText("360");
DiasAguinaldo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DiasAguinaldoActionPerformed(evt);
}
});
jLabel21.setText("DIAS LABORADOS BONO 14");
DiasBono14.setText("360");
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(diasLaboradosVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(DiasAguinaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DiasBono14, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(22, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(diasLaboradosVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel20)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DiasAguinaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DiasBono14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(16, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void CodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CodigoActionPerformed
buscar();
}//GEN-LAST:event_CodigoActionPerformed
private void NombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NombreActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_NombreActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
calculoIndemnizacion();
horaextra();
CalculoVacaciones();
Calculoaguinaldo();
CalculoBono14();
salariohorasbonicficacion();
}//GEN-LAST:event_jButton2ActionPerformed
private void precioHoraExtraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_precioHoraExtraActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_precioHoraExtraActionPerformed
private void HorasEActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HorasEActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_HorasEActionPerformed
private void DiasVacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiasVacionesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_DiasVacionesActionPerformed
private void DiasAguinaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiasAguinaldoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_DiasAguinaldoActionPerformed
private void DiasPendientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiasPendientesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_DiasPendientesActionPerformed
private void diasLaboradosVacacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diasLaboradosVacacionesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_diasLaboradosVacacionesActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Aguinaldo;
private javax.swing.JTextField Bonificacion;
private javax.swing.JTextField BonificacionPendiente;
private javax.swing.JTextField Bono14;
private javax.swing.JTextField Codigo;
private javax.swing.JTextField DiasAguinaldo;
private javax.swing.JTextField DiasBono14;
private javax.swing.JTextField DiasPendientes;
private javax.swing.JTextField DiasVaciones;
private javax.swing.JTextField FechaIngre;
private javax.swing.JTextField HorasE;
private javax.swing.JTextField HorasExtras;
private javax.swing.JTextField Nombre;
private javax.swing.JTextField Salario;
private javax.swing.JTable UltimosMeses;
private javax.swing.JTextField Vacaciones;
private javax.swing.JTextField diasLaborados;
private javax.swing.JTextField diasLaboradosVacaciones;
private javax.swing.JTextField indemniacion;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private com.toedter.calendar.JDateChooser jDateChooser1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField precioHoraExtra;
private javax.swing.JTextField salariopromedio;
private javax.swing.JTextField salariopromedio12;
private javax.swing.JTextField salariosPendientes;
// End of variables declaration//GEN-END:variables
}
|
package app.android.com.gitrepostriesApp.constant;
public class AppConstant {
/**
* get a api key from https://newsapi.org/
* just register an account and request for an api key
* when you will get an api key please replace with YOUR_API_KEY
*/
public static final String BASE_URL = "https://api.github.com/";
//replace token with your private access token
public static final String TOKEN_KEY = "b9e67a9f63618b226fxxxxxxxxx";
public static final int PAGE_SIZE = 1;
public static final int MobileData = 2;
public static final int WifiData = 1;
}
|
package com.zxt.compplatform.formengine.entity.view;
import com.zxt.framework.common.entity.BasicEntity;
/**
* Title: CacheInterface
* Description: 界面提示信息
* Create DateTime: 2010-9-27
*
* @author xxl
* @since v1.0
*
*/
public class Note extends BasicEntity {
/**
* 主键
*/
private String id;
/**
* 提示文本
*/
private String noteText;
/**
* 提示样式
*/
private String noteStyle;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
public String getNoteStyle() {
return noteStyle;
}
public void setNoteStyle(String noteStyle) {
this.noteStyle = noteStyle;
}
}
|
/*
* Written by Erhan Sezerer
* Contact <erhansezerer@iyte.edu.tr> for comments and bug reports
*
* Copyright (C) 2014 Erhan Sezerer
*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.darg.utils;
public final class Normalizer
{
/**normalizes the elements in the given list to a total sum,
* where the sum of resulting list will be equal to normValue.
* NormValue can be given 1 or 100 to normalize to percentages.
*
*
* NOTE: this function uses absolute values to preserve the sign.
*
*
* exp: calling the function with {0.2, -0.05, -0.15} and 1 result in;
* {0.5, -0,125, -0.375}
*
*
* @author erhan sezerer
*
* @param list
* @param normValue
* @return
*/
public static double[] normalizeSumAbsolute(final double list[], final double normValue)
{
double sum = 0;
double normConst = 0;
for(int i=0; i<list.length; i++)
{
sum += Math.abs(list[i]);
}
normConst = normValue/sum;
for(int i=0; i<list.length; i++)
{
list[i] *= normConst;
}
return list;
}
/**normalizes the elements in the given list to a total sum,
* where the sum of resulting list will be equal to normValue.
* NormValue can be given 1 or 100 to normalize to percentages.
*
*
* NOTE: this function does not preserve the sign.
*
*
* exp: calling the function with {0.2, -0.05, -0.15} and 1 result in;
* {0.5, -0,125, -0.375}
* @author erhan sezerer
*
* @param list
* @param normValue
* @return
*/
public static double[] normalizeSum(final double list[], final double normValue)
{
double sum = 0;
double normConst = 0;
double min = Double.POSITIVE_INFINITY;
for(int i=0; i<list.length; i++)
{
if(list[i] <= min)
{
min = list[i];
}
}
if(min <= 0)
{
double temp = Math.abs(min);
for(int i=0; i<list.length; i++)
{
list[i] += temp;
}
}
for(int i=0; i<list.length; i++)
{
sum += list[i];
}
normConst = normValue/sum;
for(int i=0; i<list.length; i++)
{
list[i] *= normConst;
}
return list;
}
}
|
package com.wrathOfLoD.Models.Skill;
/**
* Created by luluding on 4/7/16.
*/
public class Skill {
private int skillLevel;
public Skill(int skillLevel){
this.skillLevel = skillLevel;
}
public int getSkillLevel(){
return skillLevel;
}
public void updateSkillLevel(int skillPoint){
skillLevel += skillPoint;
}
}
|
package views.elements.drawers;
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Group;
import engine.Values;
import engine.utils.general.AssetsLoader;
import engine.utils.graphics.AnimationRegions;
import entities.Monkey;
/**
* MonkeyDrawer class. Doesn't inherit from EntitiesDrawer because there is only
* one entitiy here - the monkey. Thus, it is advised not to inherit from
* EntitiesDrawer
*
* @author David
*
*/
public class MonkeyDrawer extends Group {
private Monkey monkey;
private AnimationRegions monkeyAnimRight;
private AnimationRegions monkeyAnimLeft;
private TextureRegion monkeyStand;
private TextureRegion monkeyDead;
public MonkeyDrawer(Monkey monkey) {
this.monkey = monkey;
monkeyStand = new TextureRegion(AssetsLoader.getInstance()
.getAsset("animations/monkey.txt", TextureAtlas.class)
.findRegion("monkey_stand"));
monkeyAnimRight = new AnimationRegions(AssetsLoader.getInstance()
.getAsset("animations/monkey.txt", TextureAtlas.class)
.findRegion("monkeywalk"), 1, 4, 1 / 10f);
monkeyAnimLeft = new AnimationRegions(AssetsLoader.getInstance()
.getAsset("animations/monkey.txt", TextureAtlas.class)
.findRegion("monkeywalk"), 1, 4, 1 / 10f, true,
PlayMode.LOOP_REVERSED);
// Textures
monkeyDead = new TextureRegion(AssetsLoader.getInstance()
.getAsset("animations/monkey.txt", TextureAtlas.class)
.findRegion("monkeystates").getTexture(), 1205, 2, 191, 292);
addActor(monkeyAnimRight);
addActor(monkeyAnimLeft);
}
public void drawMonkey(SpriteBatch batch) {
switch (monkey.getState()) {
case STAND:
batch.draw(monkeyStand, monkey.getX(), monkey.getY(),
Values.Monkey_Width*1.2f, Values.Monkey_Height*1.2f);
break;
case WALKING_RIGHT:
batch.draw(monkeyAnimRight.getCurrentFrame(), monkey.getX(),
monkey.getY(), Values.Monkey_Width, Values.Monkey_Height);
break;
case WALKING_LEFT:
batch.draw(monkeyAnimLeft.getCurrentFrame(), monkey.getX(),
monkey.getY(), Values.Monkey_Width, Values.Monkey_Height);
break;
case DEAD:
batch.draw(monkeyDead, monkey.getX(), monkey.getY(),
Values.Monkey_Width, Values.Monkey_Height);
break;
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
drawMonkey((SpriteBatch) batch);
}
}
|
package com.lenovohit.hcp.material.manager;
import com.lenovohit.hcp.base.model.HcpUser;
import com.lenovohit.hcp.material.model.MatInfo;
public interface MatInfoRestManager {
/**
* 子医院保存物资基本信息
* @param matInfo
* @param user
* @return
*/
public MatInfo createMatInfo(MatInfo matInfo, HcpUser user);
/**
* 集团保存物资基本信息
* @param matInfo
* @param user
* @return
*/
public MatInfo createMatInfoGroup(MatInfo matInfo, HcpUser user);
}
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/**
* Created by efetoros on 4/15/17.
*/
public class Quadtree {
Node root;
static class Node implements Comparable<Node> {
String filename;
Node topLeft;
Node topRight;
Node bottomLeft;
Node bottomRight;
double Ullon;
double Ullat;
double Lrlon;
double Lrlat;
int depth;
Node(String filename, Node TL, Node TR, Node BL, Node BR, double Ullon,
double Ullat, double Lrlon, double Lrlat, int depth) {
this.filename = filename;
this.topLeft = TL;
this.topRight = TR;
this.bottomLeft = BL;
this.bottomRight = BR;
this.Ullon = Ullon;
this.Ullat = Ullat;
this.Lrlon = Lrlon;
this.Lrlat = Lrlat;
this.depth = depth;
}
public boolean intersects(double Query_Ullon, double Query_Ullat,
double Query_Lrlon, double Query_Lrlat) {
if ((this.Ullon >= Query_Ullon || this.Lrlon >= Query_Ullon) &&
(this.Ullon <= Query_Lrlon || this.Lrlon <= Query_Lrlon) &&
(this.Ullat <= Query_Ullat || this.Lrlat <= Query_Ullat) &&
(this.Ullat >= Query_Lrlat || this.Lrlat >= Query_Lrlat)) {
return true;
} else {
return false;
}
}
public ArrayList<Node> FindMatchingNodes(double Query_Ullon, double Query_Ullat, double Query_Lrlon,
double Query_Lrlat, double Query_width) {
ArrayList<Node> result = new ArrayList<>();
if (this.intersects(Query_Ullon, Query_Ullat, Query_Lrlon, Query_Lrlat)) {
if (this.depth == 7 || Rasterer.getLonDpp(this.Lrlon, this.Ullon, 256) <=
Rasterer.getLonDpp(Query_Lrlon, Query_Ullon, Query_width)) {
result.add(this);
} else {
result.addAll(this.topLeft.FindMatchingNodes(Query_Ullon, Query_Ullat, Query_Lrlon, Query_Lrlat,
Query_width));
result.addAll(this.topRight.FindMatchingNodes(Query_Ullon, Query_Ullat, Query_Lrlon, Query_Lrlat,
Query_width));
result.addAll(this.bottomLeft.FindMatchingNodes(Query_Ullon, Query_Ullat, Query_Lrlon, Query_Lrlat,
Query_width));
result.addAll(this.bottomRight.FindMatchingNodes(Query_Ullon, Query_Ullat, Query_Lrlon, Query_Lrlat,
Query_width));
}
}
return result;
}
@Override
public int compareTo(Node o) {
if (this.Ullon < o.Ullon) {
return -1;
} else if (this.Ullon > o.Ullon) {
return 1;
} else {
return 0;
}
}
}
public Quadtree() {
this.root = new Node("root.png", null, null, null, null,
-122.2998046875, 37.892195547244356, -122.2119140625, 37.82280243352756, 0);
double dividingfactorlat = (37.892195547244356 - 37.82280243352756) / 2;
double dividingFactorlon = ((-122.2119140625) - (-122.2998046875)) / 2;
this.root.topLeft = RecursiveBuild("1", -122.2998046875, 37.892195547244356, -122.2119140625 - dividingFactorlon, 37.82280243352756 + dividingfactorlat, dividingfactorlat / 2, dividingFactorlon / 2, 1);
this.root.topRight = RecursiveBuild("2", -122.2998046875 + dividingFactorlon, 37.892195547244356, -122.2119140625, 37.82280243352756 + dividingfactorlat, dividingfactorlat / 2, dividingFactorlon / 2, 1);
this.root.bottomLeft = RecursiveBuild("3", -122.2998046875, 37.892195547244356 - dividingfactorlat, -122.2119140625 - dividingFactorlon, 37.82280243352756, dividingfactorlat / 2, dividingFactorlon / 2, 1);
this.root.bottomRight = RecursiveBuild("4", -122.2998046875 + dividingFactorlon, 37.892195547244356 - dividingfactorlat, -122.2119140625, 37.82280243352756, dividingfactorlat / 2, dividingFactorlon / 2, 1);
}
public Node RecursiveBuild(String filename, double Ullon, double Ullat, double Lrlon, double Lrlat,
double dividingfactorlat, double dividingfactorlon, int depth) {
if (depth == 7) {
filename = filename + ".png";
return new Node(filename, null, null, null, null, Ullon,
Ullat, Lrlon, Lrlat, 7);
} else {
Node TL = RecursiveBuild(filename + "1", Ullon, Ullat, Lrlon - dividingfactorlon, Lrlat + dividingfactorlat, dividingfactorlat / 2, dividingfactorlon / 2, depth + 1);
Node TR = RecursiveBuild(filename + "2", Ullon + dividingfactorlon, Ullat, Lrlon, Lrlat + dividingfactorlat, dividingfactorlat / 2, dividingfactorlon / 2, depth + 1);
Node BL = RecursiveBuild(filename + "3", Ullon, Ullat - dividingfactorlat, Lrlon - dividingfactorlon, Lrlat, dividingfactorlat / 2, dividingfactorlon / 2, depth + 1);
Node BR = RecursiveBuild(filename + "4", Ullon + dividingfactorlon, Ullat - dividingfactorlat, Lrlon, Lrlat, dividingfactorlat / 2, dividingfactorlon / 2, depth + 1);
filename = filename + ".png";
return new Node(filename, TL, TR, BL, BR, Ullon, Ullat,
Lrlon, Lrlat, depth);
}
}
public static HashMap<Double, ArrayList<Node>> GroupByLat(ArrayList<Node> Alist) {
HashMap<Double, ArrayList<Node>> hashMap = new HashMap<>();
for (Node node : Alist) {
if (!hashMap.containsKey(node.Ullat)) {
ArrayList<Node> list = new ArrayList<>();
list.add(node);
hashMap.put(node.Ullat, list);
} else {
hashMap.get(node.Ullat).add(node);
}
}
return hashMap;
}
public static String[][] StringSort(ArrayList<Node> map) {
HashMap<Double, ArrayList<Node>> sorted = GroupByLat(map);
Object[] keys = sorted.keySet().toArray();
java.util.Arrays.sort(keys, Collections.reverseOrder());
String[][] result = new String[sorted.size()][sorted.get(keys[0]).size()];
int row = 0;
int col = 0;
for (Object key : keys) {
ArrayList<Node> he = sorted.get(key);
for (Node node : he) {
result[row][col] = "img/" + node.filename;
col = col + 1;
}
col = 0;
row = row + 1;
}
return result;
}
public static void main(String[] args) {
Quadtree me = new Quadtree();
//
// ArrayList<Node> hi = me.root.FindMatchingNodes(-122.24163047377972, 37.87655856892288,
// -122.24053369025242, 37.87548268822065, 892.0);
// Collections.sort(hi);
// for (Node node : hi) {
// System.out.print(node.filename +" ");
// System.out.print(node.Ullat+" ");
// System.out.println(node.Lrlat+" ");
// }
// System.out.println();
// HashMap<Double, ArrayList<Node>> bye = GroupByLat(hi);
// Object[] keys = bye.keySet().toArray();
// java.util.Arrays.sort(keys, Collections.reverseOrder());
//
// for(Object key : keys) {
// ArrayList<Node> he = bye.get(key);
// for (Node node : he)
// System.out.println(node.filename);
// }
// System.out.println();
// System.out.println();
// String[][] result = StringSort(hi);
// for (int i = 0; i < 3; i ++) {
// for (int m = 0; m < 3; m ++) {
// System.out.println(result[i][m]);
// }
// }
// System.out.println();
// System.out.println();
// HashMap<Integer, String> map = new HashMap<Integer, String>();
// map.put (1, "Mark");
// map.put (2, "Mark");
// map.put (3, "Tarryn");
// ArrayList<String> list = new ArrayList<String>(map.values());
// for (String s : list) {
// System.out.println(s);
// }
// System.out.println();
// System.out.println(bye);
}
}
|
package cn.seu.edu.hanbab.hanbabRedis.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
*
* @Author: Hanbab
* @Date: 2021/06/13/16:32
*/
@Api("Project")
@RestController
@RequestMapping("/api/project")
public class ProjectController {
@Autowired
RedisTemplate redisTemplate;
/**
* project search
*
* @Author: Hanbab
*/
@ApiOperation("project->message")
@RequestMapping(value = "/pjMes/{project}", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> getByProject(
@PathVariable String project){
Map<String, Object> project_message = redisTemplate
.opsForHash()
.entries("Project:"+ project);
return ResponseEntity
.status(HttpStatus.OK)
.header(HttpHeaders.CONTENT_DISPOSITION)
.body(project_message);
}
@ApiOperation("project+key->detailed message")
@RequestMapping(value = "/pjMes/{project}/{key}", method = RequestMethod.GET)
public ResponseEntity<Object> getDetailedProjectMessage(
@PathVariable String project,
@PathVariable String key){
Object project_detailed_message = redisTemplate
.opsForHash()
.entries("Project:"+project)
.get(key);
return ResponseEntity
.status(HttpStatus.OK)
.header(HttpHeaders.CONTENT_DISPOSITION)
.body(project_detailed_message);
}
@ApiOperation("key->search project & keys set")
@RequestMapping(value = "/pjKeysSet/{keyword}", method = RequestMethod.GET)
public ResponseEntity<Set<Object>> getProjectKeysSet(
@PathVariable String keyword
){
Set<Object> set = redisTemplate
.opsForSet()
.members("Project:Keys:"+keyword);
return ResponseEntity
.status(HttpStatus.OK)
.header(HttpHeaders.CONTENT_DISPOSITION)
.body(set);
}
}
|
package blazeplus;
import net.minecraft.src.Block;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityBlaze;
import net.minecraft.src.EntityGiantZombie;
import net.minecraft.src.EntitySnowman;
import net.minecraft.src.Material;
import net.minecraft.src.World;
public class BlazeBlock extends Block{
public BlazeBlock(int blockId, int terrainId) {
super(blockId, terrainId, Material.iron);
this.setTextureFile(DefaultProps.TEXTURE_PATH);
this.setCreativeTab(BlazePlus.blazeTabs);
}
}
|
/*
* Copyright 2002-2016 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.oxm;
import java.io.IOException;
import javax.xml.transform.Source;
/**
* Defines the contract for Object XML Mapping unmarshallers. Implementations of this
* interface can deserialize a given XML Stream to an Object graph.
*
* @author Arjen Poutsma
* @since 3.0
* @see Marshaller
*/
public interface Unmarshaller {
/**
* Indicate whether this unmarshaller can unmarshal instances of the supplied type.
* @param clazz the class that this unmarshaller is being asked if it can marshal
* @return {@code true} if this unmarshaller can indeed unmarshal to the supplied class;
* {@code false} otherwise
*/
boolean supports(Class<?> clazz);
/**
* Unmarshal the given {@link Source} into an object graph.
* @param source the source to marshal from
* @return the object graph
* @throws IOException if an I/O error occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
Object unmarshal(Source source) throws IOException, XmlMappingException;
}
|
/**
*
*/
package com.t11e.discovery.datatool;
import java.util.Map;
final class CountingChangesetListener
implements IItemChangesetListener
{
private int setItemCount;
private int removeItemCount;
@Override
public void onStartChangeset()
{
}
@Override
public void onSetItem(final String id, final Map<String, Object> properties)
{
++setItemCount;
}
@Override
public void onRemoveItem(final String id)
{
++removeItemCount;
}
@Override
public void onRemoveFromItem(final String id, final Object properties)
{
}
@Override
public void onEndChangeset()
{
}
@Override
public void onAddToItem(final String id, final Map<String, Object> properties)
{
}
@Override
public void onAddItem(final String id)
{
}
public int getRemoveItemCount()
{
return removeItemCount;
}
public int getSetItemCount()
{
return setItemCount;
}
}
|
package clienta;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* Portfolio Question 4
* This program sets up the Client side for the server to connect
*/
public class ClientA {
private static DataOutputStream outputStream;
private static DataInputStream inputStream;
private static Socket socket;
private static Scanner scan = new Scanner(System.in);
private static String serverInput;
private static String replyToServer;
public static void main(String[] args) {
connectServer();
}
// Connect to the server
public static void connectServer() {
try {
socket = new Socket("localhost", 2021);
openStreams(socket);
chatting();
closeStreams();
} catch (IOException e) {
System.out.println("Input not correct closing program.");
System.exit(0);
}
}
// Opens data output and input streams
public static void openStreams(Socket socket) throws IOException {
outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.flush();
inputStream = new DataInputStream(socket.getInputStream());
}
// Closes data input and output streams
public static void closeStreams() throws IOException {
socket.close();
inputStream.close();
outputStream.close();
}
// Read and send messages to the server
public static void chatting() throws IOException {
while (true) {
serverInput = inputStream.readUTF();
System.out.println(serverInput);
replyToServer = scan.nextLine();
outputStream.writeUTF(replyToServer);
outputStream.flush();
if (replyToServer.equalsIgnoreCase("exit")) {
System.exit(0);
} else {
chatting();
}
}
}
}
|
package com._520it.service;
import java.sql.SQLException;
import java.util.List;
import com._520it.dao.AdminProductDao;
import com._520it.domain.Category;
import com._520it.domain.Product;
import com._520it.vo.Select;
public class AdminProductService {
/**
* 查询所有商品的方法
* @return 所有的商品集合
*/
public List<Product> findAllProduct() {
//因为没有复杂的业务,直接传递请求就ok
List<Product> list=null;
//调用dao层的方法查询所有的商品信息
AdminProductDao dao =new AdminProductDao();
try {
list = dao.finaAllProduct();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 查询所有商品类别的方法
* @return 所有的商品类别的集合
* @throws SQLException
*/
public List<Category> findAllCategory() throws SQLException {
AdminProductDao dao =new AdminProductDao();
List<Category> categoryList = dao.findAllCategory();
return categoryList;
}
/**
* 添加商品
* @param product
* @throws SQLException
*/
public int addProduct(Product product) throws SQLException {
AdminProductDao dao =new AdminProductDao();
return dao.addProduct(product);
}
/**
* 删除商品的方法
* @param pid
* @throws SQLException
*/
public void delProduct(String pid) throws SQLException {
//没有复杂的业务,将请求和参数传递给dao层
AdminProductDao dao=new AdminProductDao();
dao.delProduct(pid);
}
/**
* 根据id查询商品信息
* @param pid
* @return
* @throws SQLException
*/
public Product editProduct(String pid) throws SQLException {
//将参数传递到dao层
AdminProductDao dao = new AdminProductDao();
Product product = dao.findProduct(pid);
return product;
}
/**
* 更新商品信息的方法
* @param product
* @throws SQLException
*/
public void editProduct(Product product) throws SQLException {
//将请求和参数传递给dao层
AdminProductDao dao = new AdminProductDao();
dao.editProduct(product);
}
public List<Product> selectProduct(Select select) throws SQLException {
//将请求和参数传递给dao层
AdminProductDao dao =new AdminProductDao();
List<Product> product = dao.selectProduct(select);
return product;
}
}
|
package crushstudio.crush_studio.config.mapper;
import org.springframework.stereotype.Component;
import org.modelmapper.ModelMapper;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class Mapper {
private static ModelMapper modelMapper;
public <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
return entityList.stream().map(entity -> map(entity, outCLass)).collect(Collectors.toList());
}
private Mapper() {
}
public <D, T> D map(final T entity, Class<D> outClass) {
return modelMapper.map(entity, outClass);
}
}
|
package com.example.apping.Events;
public class Search {
String title;
String postImage;
String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Search(String title, String postImage, String description) {
this.title = title;
this.postImage = postImage;
this.description = description;
}
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPostImage() {
return postImage;
}
public void setPostImage(String postImage) {
this.postImage = postImage;
}
}
|
public class GlobalTimer implements Runnable{
/**
* This class contains the global timer which keeps track of time in the main game.
*/
//Properties
int intGlobalTimer;
int intPieceMaxTimer;
int intDecrementValue;
public void run(){
intGlobalTimer = 5400;
intPieceMaxTimer = 300;
intDecrementValue = 20;
while(true){
if(intGlobalTimer <= 0){
break;
}
try{
Thread.sleep(1000/60);
}catch(InterruptedException e){
}
intGlobalTimer--;
if(intGlobalTimer % intDecrementValue == 0){
intPieceMaxTimer--;
}
}
}
public void pause(){
}
//Constructor
public GlobalTimer(){
}
}
|
package com.zantong.mobilecttx.api;
import java.util.Map;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
/**
* Created by RG on 2016/4/3.
*/
public interface FileUploadApi {
@Multipart
// @FormUrlEncoded
// @POST("ecip/uploadImage_uploadImage")
@POST("ecip/TbCfCImageUploadServlet.do")
Call<ResponseBody> uploadImage(@PartMap Map<String, RequestBody> params);
}
|
package ru.alexside.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import ru.alexside.model.PoType;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Alex on 25.03.2018.
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GpoHeaderFull {
private Long id;
private List<RpoHeaderFull> rpoHeaders = new ArrayList<>();
private ContactFull shipper;
private String zip5From;
private String zip5To;
private List<StopFull> stops;
private StateFull state;
private Long termsId;
private RouteFull route;
private List<CostFull> costs;
private List<ClaimFull> claims;
private List<ServiceFull> services;
private Long contractId;
private BigDecimal totalDistance;
private Long totalTime;
private Integer totalWeight;
private Double weightUom;
private Integer totalLength;
private Integer totalWidth;
private Integer totalHeight;
private OffsetDateTime createdDate;
private String proNumber;
private String specialInstructions;
private Integer unitQty;
private Integer temperatureLow;
private Integer temperatureHigh;
private BigDecimal teamDriveParameter;
private Boolean manualProcessing;
private PoType poType;
private Boolean teamDrive;
private BigDecimal totalCost;
private BigDecimal fuelCost;
private BigDecimal lineHaulCost;
private BigDecimal feeCost;
private BigDecimal teamDriveCost;
}
|
package org.spider.core.parse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.spider.core.HtmlDefinition;
import org.spider.core.WebClientHolder;
import org.spider.core.task.SpiderLocation;
/**
* @author liuxin
* @version Id: JsoupHtmlDefinitionParser.java, v 0.1 2018/7/26 下午5:43
*/
public class JsoupHtmlDefinitionParser implements HtmlDefinitionParser{
@Override
public HtmlDefinition parse(SpiderLocation spiderLocation, String htmlText) {
Document document = Jsoup.parse(htmlText);
String title = document.select("head > title").text();
return new HtmlDefinition(title,spiderLocation.getLocation(),document,htmlText);
}
}
|
package com.generic.core.validation.functions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.generic.core.utilities.Util;
import com.generic.core.utilities.UtilConstants;
import com.generic.core.utilities.Validation;
import com.generic.rest.constants.Constants;
import com.generic.rest.dto.ResponseDto;
public class CheckEmail implements ValidationFunction {
private String anEmailString;
@Override
public ResponseDto validate(String objectKey, String objectValue,
int objectNumber) {
this.anEmailString = objectValue;
if(Util.isNullAndEmpty(objectValue)) {
String errorResponse = Validation.generateErrorString(objectNumber, objectKey, Constants.LOGGER_WARNING, Constants.VALIDATION_NULL_DATA_MESSAGE);
return new ResponseDto(Constants.VALIDATION_NULL_DATA_CODE, errorResponse);
}
Boolean check = checkEmail();
if(!check) {
String errorResponse = Validation.generateErrorString(objectNumber, objectKey, Constants.LOGGER_ERROR, Constants.VALIDATION_INVALID_EMAIL_MESSAGE);
return new ResponseDto(Constants.VALIDATION_INVALID_EMAIL_CODE, errorResponse);
}
return null;
}
private Boolean checkEmail(){
Pattern pattern = Pattern.compile(UtilConstants.REGEX_IS_EMAIL);
Matcher matcher = pattern.matcher(anEmailString);
while(matcher.find(0)){
if(matcher.group(0).equals(anEmailString))
return true;
else
return false;
}
return false;
}
/*public static void main(String[] args) {
CheckEmail chk = new CheckEmail();
String anEmailString = "john.doe@example..com";
System.out.println(chk.validate("email", anEmailString, 1));
}*/
}
|
package com.example.demo.repository;
import com.example.demo.entity.Character;
import java.util.List;
public interface CharacterRepository {
Character save(Character character); //Insert Update
List<Character> findAll(); //Select * from
Character findByName(String name); // select where from
void deleteById(Integer id);
}
|
package mx.redts.ob3.model;
// Generated 03-jun-2014 0:22:34 by Hibernate Tools 3.4.0.CR1
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* CInvoicetax generated by hbm2java
*/
@Entity
@Table(name = "c_invoicetax", schema = "public")
public class CInvoicetax implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String CInvoicetaxId;
private CInvoice CInvoice;
private AdOrg adOrg;
private CTax CTax;
private String adClientId;
private char isactive;
private Date created;
private String createdby;
private Date updated;
private String updatedby;
private BigDecimal taxbaseamt;
private BigDecimal taxamt;
private BigDecimal line;
private char recalculate;
public CInvoicetax() {
}
public CInvoicetax(String CInvoicetaxId, CInvoice CInvoice, AdOrg adOrg,
CTax CTax, String adClientId, char isactive, Date created,
String createdby, Date updated, String updatedby,
BigDecimal taxbaseamt, BigDecimal taxamt, BigDecimal line,
char recalculate) {
this.CInvoicetaxId = CInvoicetaxId;
this.CInvoice = CInvoice;
this.adOrg = adOrg;
this.CTax = CTax;
this.adClientId = adClientId;
this.isactive = isactive;
this.created = created;
this.createdby = createdby;
this.updated = updated;
this.updatedby = updatedby;
this.taxbaseamt = taxbaseamt;
this.taxamt = taxamt;
this.line = line;
this.recalculate = recalculate;
}
public CInvoicetax(String CInvoicetaxId, CInvoice CInvoice, AdOrg adOrg,
CTax CTax, String adClientId, char isactive, Date created,
String createdby, Date updated, String updatedby,
BigDecimal taxbaseamt, BigDecimal taxamt, char recalculate) {
this.CInvoicetaxId = CInvoicetaxId;
this.CInvoice = CInvoice;
this.adOrg = adOrg;
this.CTax = CTax;
this.adClientId = adClientId;
this.isactive = isactive;
this.created = created;
this.createdby = createdby;
this.updated = updated;
this.updatedby = updatedby;
this.taxbaseamt = taxbaseamt;
this.taxamt = taxamt;
this.recalculate = recalculate;
}
@Column(name = "ad_client_id", nullable = false, length = 32)
public String getAdClientId() {
return this.adClientId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ad_org_id", nullable = false)
public AdOrg getAdOrg() {
return this.adOrg;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "c_invoice_id", nullable = false)
public CInvoice getCInvoice() {
return this.CInvoice;
}
@Id
@Column(name = "c_invoicetax_id", unique = true, nullable = false, length = 32)
public String getCInvoicetaxId() {
return this.CInvoicetaxId;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", nullable = false, length = 29)
public Date getCreated() {
return this.created;
}
@Column(name = "createdby", nullable = false, length = 32)
public String getCreatedby() {
return this.createdby;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "c_tax_id", nullable = false)
public CTax getCTax() {
return this.CTax;
}
@Column(name = "isactive", nullable = false, length = 1)
public char getIsactive() {
return this.isactive;
}
@Column(name = "line", precision = 131089, scale = 0)
public BigDecimal getLine() {
return this.line;
}
@Column(name = "recalculate", nullable = false, length = 1)
public char getRecalculate() {
return this.recalculate;
}
@Column(name = "taxamt", nullable = false, precision = 131089, scale = 0)
public BigDecimal getTaxamt() {
return this.taxamt;
}
@Column(name = "taxbaseamt", nullable = false, precision = 131089, scale = 0)
public BigDecimal getTaxbaseamt() {
return this.taxbaseamt;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated", nullable = false, length = 29)
public Date getUpdated() {
return this.updated;
}
@Column(name = "updatedby", nullable = false, length = 32)
public String getUpdatedby() {
return this.updatedby;
}
public void setAdClientId(String adClientId) {
this.adClientId = adClientId;
}
public void setAdOrg(AdOrg adOrg) {
this.adOrg = adOrg;
}
public void setCInvoice(CInvoice CInvoice) {
this.CInvoice = CInvoice;
}
public void setCInvoicetaxId(String CInvoicetaxId) {
this.CInvoicetaxId = CInvoicetaxId;
}
public void setCreated(Date created) {
this.created = created;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public void setCTax(CTax CTax) {
this.CTax = CTax;
}
public void setIsactive(char isactive) {
this.isactive = isactive;
}
public void setLine(BigDecimal line) {
this.line = line;
}
public void setRecalculate(char recalculate) {
this.recalculate = recalculate;
}
public void setTaxamt(BigDecimal taxamt) {
this.taxamt = taxamt;
}
public void setTaxbaseamt(BigDecimal taxbaseamt) {
this.taxbaseamt = taxbaseamt;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
}
|
package ltd.getman.testjobproject.domain.models.mechanizm;
import java.util.List;
import lombok.Getter;
import lombok.experimental.Builder;
/**
* Created by Artem Getman on 18.05.17.
* a.e.getman@gmail.com
*/
@Builder public class Data {
@Getter private List<Car> cars;
@Getter private List<Plane> planes;
@Getter private List<Ship> ships;
}
|
package org.hibernate.benchmarks.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Target;
@Inherited
@Target( ElementType.METHOD )
public @interface BenchmarkQueryMethod {
String value();
}
|
package Servlet;
import JavaBean.BookDao;
import JavaBean.Hon;
import JavaBean.User;
import JavaBean.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String dowhat=request.getParameter("dowhat");
if("logon".equals(dowhat)){ //注册
String id=request.getParameter("id");
String password=request.getParameter("password");
User user=new User();
user.setId(id);
user.setPassword(password);
Boolean exist =new UserDao().logon(user);
if(exist==false){
response.sendRedirect(request.getContextPath()+"/login.jsp");
}else{
HttpSession session=request.getSession();
session.setAttribute("erro","用户名已经存在了哦");
response.sendRedirect(request.getContextPath()+"/logon.jsp");
}
}
if("login".equals(dowhat)){ //登录
String autologin =request.getParameter("autologin");
String id =request.getParameter("id");
User user =new UserDao().checkLogin(id); //按id查找用户,若不存在说明无此用户
if(user==null){
request.getSession().setAttribute("erroi","用户不存在哦");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
String inputPw=request.getParameter("password"); //存在则验证密码
if(inputPw.equals(user.getPassword()) ){
request.setAttribute("id",id);
HttpSession session=request.getSession();
session.setAttribute("now",user); //储存当前登录用户
if(autologin !=null){
Cookie cookie =new Cookie("autologin",id + "-" +inputPw);
cookie.setMaxAge(Integer.parseInt(autologin));
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
request.getRequestDispatcher("/controller.jsp").forward(request,response); //登录成功
}else {
HttpSession session=request.getSession();
session.setAttribute("errop","再想想你的密码");
request.getRequestDispatcher("/login.jsp").forward(request,response); //登录失败返回登录页面并输出错误信息
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String dowhat=request.getParameter("dowhat");
if ("logout".equals(dowhat)){
request.getSession().removeAttribute("now");
Cookie cookie =new Cookie("autologin","null");
cookie.setMaxAge(0);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
}
}
|
package packages;
import java.util.Scanner;
public class bt2 {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
double a;
double b;
double c;
double x;
double x1;
double x2;
double d;
System.out.println("Nhập a: ");
a = s.nextInt();
System.out.println("Nhập b: ");
b = s.nextInt();
System.out.println("Nhập c: ");
c = s.nextInt();
if(a==0) {
x = -c/b;
System.out.println("Nghiệm = "+ x);
}
else {
d = b*b - 4*a*c;
if(d<0) {
System.out.println("Vô nghiệm");
}
else if(d==0){
x = -b/2*a;
System.out.println("Nghiệm kép = "+ x);
}
else {
x1 = (-b+Math.sqrt(d))/(2*a);
System.out.println("Nghiệm x1 = "+ x1);
x2 = (-b-Math.sqrt(d))/(2*a);
System.out.println("Nghiệm x2 = "+ x2);
}
}
}
}
|
package testfxml;
import java.util.ArrayList;
import java.util.List;
public class Story2 implements ICrossingStrategy{
@Override
public boolean isValid(List<ICrosser> rightBankCrossers, List<ICrosser> leftBankCrossers, List<ICrosser> boatRiders) {
if(boatRiders.size() == 1 && !boatRiders.get(0).canSail() || boatRiders.size() == 0)
return false;
if(boatRiders.size()==2)
if(boatRiders.get(0).getWeight()+boatRiders.get(1).getWeight()>100)
return false;
return true;
}
@Override
public List<ICrosser> getInitialCrossers() {
List<ICrosser> InitialCrossers = new ArrayList<ICrosser>() ;
Farmer F1 = new Farmer() ;
F1.setWeight(90.0) ;
Farmer F2 = new Farmer() ;
F2.setWeight(80.0) ;
Farmer F3 = new Farmer() ;
F3.setWeight(60.0) ;
Farmer F4 = new Farmer() ;
F4.setWeight(40.0) ;
HerbevorusAnimal H = new HerbevorusAnimal();
InitialCrossers.add(F1) ;
InitialCrossers.add(F2) ;
InitialCrossers.add(F3) ;
InitialCrossers.add(F4) ;
InitialCrossers.add(H) ;
return InitialCrossers;
}
@Override
public String[] getInstructions() {
String[] instructions = new String[2] ;
instructions[0]="Story2:\r\n�Four farmers and their animal need to cross a river in a small boat. The weights of the\r\nfarmers are 90 kg, 80 kg,60 kg and 40 kg respectively, and the weight of the animal is\r\n20 kg.�\r\nRules:\r\n1. The boat cannot bear a load heavier than 100 kg.\r\n2. All farmers can raft, while the animal cannot.\r\nHow can they all get to the other side with their animal?";
return instructions;
}
}
|
public class PohamHandle {
int quantity;
public PohamHandle() {
quantity = 0;
}
public String speedUp(int quantity) {
this.quantity = quantity;
return "¸®إد";
}
}
|
package be.darkshark.parkshark.api.controller;
import be.darkshark.parkshark.service.AllocationService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.junit.jupiter.api.Assertions.*;
@WebMvcTest(AllocationController.class)
class AllocationControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
AllocationService allocationService;
@Test
public void whenCalledToCreateAllocation_theAllocationServiceIsCalledOnce() throws Exception {
mockMvc.perform(post("/allocations").contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"licencePlate\": \"010-aba\",\n" +
" \"memberId\": 1,\n" +
" \"parkingLotId\": 1\n" +
"}").accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated());
}
@Test
public void whenCalledToStopAllocation_theAllocationServiceToStopIsCalledOnce() throws Exception {
long allocationId = 1L;
long memberId = 1L;
mockMvc.perform(put("/allocations/" + allocationId + "/" + memberId).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
@Test
public void whenCalledAllAllocations_theServiceForSortingIsCalled() throws Exception {
mockMvc.perform(get("/allocations")).andExpect(status().isOk());
}
@Test
public void whenCalledAllAllocationsWithParameters_TheServiceForSortingIsCalled() throws Exception {
Integer limit = 2;
String status = "Active";
Boolean desc = true;
mockMvc.perform(get("/allocations?limit=" + limit + "&status=" + status + "&desc=" + desc)).andExpect(status().isOk());
}
}
|
package com.thomasdedinsky.fydp.fydpweb.controllers;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
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.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class,
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class })
protected String handleConflict(RuntimeException ex, WebRequest request) {
return "redirect:/";
}
}
|
package com.xzh.shiro.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@ApiModelProperty(value = "ID", hidden = true)
private Long id;
@ApiModelProperty(value = "用户名", required = true, example = "xzh")
private String userName;
@ApiModelProperty(value = "密码", required = true, example = "123456")
private String password;
}
|
package com.example.randomlocks.listup.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.randomlocks.listup.Adapter.CheckboxRecyclerAdapter;
import com.example.randomlocks.listup.Adapter.DatabaseAdapter;
import com.example.randomlocks.listup.AsyncTask.QueryAddUpdateNote;
import com.example.randomlocks.listup.Helper.Constants;
import com.example.randomlocks.listup.Modal.DatabaseModel;
import com.example.randomlocks.listup.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class AddTodoList extends Fragment implements ColorPickerFragment.DialogListener,ProjectOptionFragment.InterfaceListener {
private static final String COLOR_KEY = "color";
Toolbar toolbar;
TextView project,project_type;
int whichProject=0;
EditText title,newItem;
RecyclerView recyclerView;
FloatingActionButton saveButton;
ArrayList<String> checkedList;
ArrayList<Boolean> isCheckedList;
DatabaseAdapter dbadapter;
DatabaseModel model = null;
private Long rowId = null;
int color=R.color.color1;
private OnFragmentInteractionListener mListener;
public AddTodoList() {
// Required empty public constructor
}
public void setRowId(Long rowId) {
this.rowId = rowId;
}
@Override
public void colorPicker(int color) {
if(toolbar!=null)
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(),color));
this.color = color;
}
/** WHEN PROJECT TYPE IS SELECTED **/
@Override
public void onComplete(int which, String str) {
project_type.setText(str);
whichProject = which;
}
public interface OnFragmentInteractionListener {
void onAddTodo();
}
public void setModel(DatabaseModel model){
this.model = model;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
checkedList = new ArrayList<>();
isCheckedList = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_todo_list, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
title = (EditText) getActivity().findViewById(R.id.title);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
project = (TextView) toolbar.findViewById(R.id.project);
project_type = (TextView) toolbar.findViewById(R.id.project_type);
recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view);
newItem = (EditText) getActivity().findViewById(R.id.new_item);
project.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProjectOptionFragment projectOptionFragment = ProjectOptionFragment.newInstance(whichProject);
projectOptionFragment.setTargetFragment(AddTodoList.this,0);
projectOptionFragment.show(getActivity().getSupportFragmentManager(),"Project_option");
}
});
if(savedInstanceState!=null)
{
Toast.makeText(getContext(), "hello savedinstance", Toast.LENGTH_SHORT).show();
color = savedInstanceState.getInt(COLOR_KEY);
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), color));
project_type.setText(savedInstanceState.getString(Constants.PROJECT_TYPE));
checkedList = savedInstanceState.getStringArrayList(Constants.CHECKED_KEY);
boolean array[] = savedInstanceState.getBooleanArray(Constants.IS_CHECKED_KEY);
for (int i = 0; i <array.length ; i++) {
isCheckedList.add(array[i]);
}
}
/************* POPULATE THE DATA FROM DATABASE *****************************/
if(model!=null)
populateFields();
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
/*********************** SETTING RECYCLER VIEW ***********************************/
final CheckboxRecyclerAdapter adapter = new CheckboxRecyclerAdapter(checkedList,isCheckedList,getContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
/***************************SETTING FILTERING OPTION FOR SEARCHING ********************/
/************************** UPDATING RECYCLE VIEW *************************************/
newItem.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
int curSize = adapter.getItemCount();
checkedList.add(v.getText().toString());
isCheckedList.add(false);
v.setText("");
adapter.notifyItemRangeInserted(curSize, checkedList.size());
return true;
}
return false;
}
});
/************************* SAVING THE DATA TO DB *****************************/
saveButton = (FloatingActionButton) getActivity().findViewById(R.id.save);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
JSONObject jsonCheckedList = new JSONObject();
try {
jsonCheckedList.put(Constants.CHECKED_STRING_KEY,new JSONArray(checkedList));
jsonCheckedList.put(Constants.IS_CHECKED_KEY,new JSONArray(isCheckedList));
} catch (JSONException e) {
e.printStackTrace();
}
DatabaseModel dbModel = new DatabaseModel(title.getText().toString(),color,jsonCheckedList.toString(),whichProject);
/* if(model==null){
//save the notes :-
Toast.makeText(getContext(),String.valueOf(whichProject),Toast.LENGTH_SHORT).show();
dbadapter.insertNote(dbModel);
}else {
//update the note
boolean b =dbadapter.updateNote(rowId,dbModel);
} */
new QueryAddUpdateNote(getContext(), dbModel, new QueryAddUpdateNote.QueryAllNodeInterface() {
@Override
public void processFinish() {
Constants.hideKeyBoard(v,getContext());
mListener.onAddTodo();
}
}).execute(rowId);
}
});
}
private void populateFields() {
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(),model.getColor()));
color = model.getColor();
title.setText(model.getTitle());
whichProject = model.getTodoType();
final String[] items = getResources().getStringArray(R.array.Todo_Type);
final ArrayList<String> itemList = new ArrayList<>(Arrays.asList(items));
project_type.setText(itemList.get(whichProject));
try {
JSONObject jsonObject = new JSONObject(model.getCheckboxText());
JSONArray checkedString = jsonObject.optJSONArray(Constants.CHECKED_STRING_KEY);
JSONArray isChecked = jsonObject.optJSONArray(Constants.IS_CHECKED_KEY);
for (int i = 0; i < checkedString.length() ; i++) {
checkedList.add(checkedString.optString(i));
isCheckedList.add(isChecked.optBoolean(i));
}
} catch (JSONException e) {
Log.e("error",e.toString());
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_add_todo_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.change_background :
ColorPickerFragment picker = ColorPickerFragment.newInstance(color);
picker.setTargetFragment(this, 0);
picker.show(getActivity().getSupportFragmentManager(),"COLOR");
break;
case android.R.id.home:
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(COLOR_KEY, color);
outState.putString(Constants.PROJECT_TYPE, project_type.getText().toString());
outState.putStringArrayList(Constants.CHECKED_KEY, checkedList);
boolean[] array=new boolean[isCheckedList.size()];
for (int i = 0; i <isCheckedList.size() ; i++) {
array[i]= isCheckedList.get(i);
}
outState.putBooleanArray(Constants.IS_CHECKED_KEY,array);
}
}
|
package com.jgermaine.fyp.android_client.activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ViewFlipper;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.jgermaine.fyp.android_client.R;
import com.jgermaine.fyp.android_client.application.CouncilAlertApplication;
import com.jgermaine.fyp.android_client.fragment.CategoryFragment;
import com.jgermaine.fyp.android_client.fragment.TypeFragment;
import com.jgermaine.fyp.android_client.model.Citizen;
import com.jgermaine.fyp.android_client.model.Message;
import com.jgermaine.fyp.android_client.model.Report;
import com.jgermaine.fyp.android_client.request.PostReportTask;
import com.jgermaine.fyp.android_client.util.DialogUtil;
import com.jgermaine.fyp.android_client.util.LocationUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* @author JasonGermaine
* Activity to submit a new issue
*/
public class SendReportActivity extends LocationActivity implements
CategoryFragment.OnCategoryInteractionListener,
TypeFragment.OnTypeInteractionListener,
PostReportTask.OnResponseListener {
private boolean stateSaved = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_report);
getActionBar().setIcon(android.R.color.transparent);
setZoomLevel(LocationUtil.START_ZOOM_LEVEL);
getGoogleMap();
registerLocationListener();
getCategoryFragment();
mIsComments = false;
mFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.report, menu);
menu.findItem(R.id.action_comments).setVisible(false);
menu.findItem(R.id.action_done).setVisible(false);
mMenu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_comments) {
getCommentFragment();
return true;
} else if (id == R.id.action_done) {
flipBackToMain();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Loads a Category Fragment
*/
private void getCategoryFragment() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.add(R.id.fragment_container, CategoryFragment.newInstance());
ft.commit();
}
/**
* Loads the corresponding Type Fragment based on the category data passed in
*
* @param category
*/
public void getTypeFragment(String category) {
// replace
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.replace(R.id.fragment_container, TypeFragment.newInstance(category));
ft.addToBackStack(null);
ft.commit();
}
@Override
public void getCommentFragment() {
super.getCommentFragment();
if (!stateSaved) {
setupCommentFragment();
}
}
@Override
public void onCategoryInteraction(String category) {
getTypeFragment(category);
}
@Override
public void onTypeInteraction(String type) {
setupCommentFragment();
setZoomLevel(LocationUtil.COMPLETE_ZOOM_LEVEL);
toggleUI(false);
setReport(createNewReport(type));
animateMap();
}
/**
* Displays a marker on the Google map along with a title and description
*
* @param title
* @param desc
*/
public void setMarker(String title, String desc) {
setMarker(LocationUtil.getMarker(getMap(), getMarker(), getCurrentLocation(), title, desc));
}
/**
* Animates the Google Map using a user defined callback
*/
private void animateMap() {
getMap().animateCamera(CameraUpdateFactory.newLatLngZoom(LocationUtil.getCoordinates(getCurrentLocation()),
getZoomLevel()), LocationUtil.CUSTOM_ZOOM_TIME, new GoogleMap.CancelableCallback() {
@Override
public void onFinish() {
if (getZoomLevel() == LocationUtil.COMPLETE_ZOOM_LEVEL) {
setMarker(getReport().getName(), ((CouncilAlertApplication) getApplication()).getUser().getEmail());
}
}
@Override
public void onCancel() {
if (getZoomLevel() == LocationUtil.COMPLETE_ZOOM_LEVEL) {
setMarker(getReport().getName(), ((CouncilAlertApplication) getApplication()).getUser().getEmail());
}
}
});
}
@Override
public void onBackPressed() {
if (mIsComments) {
flipBackToMain();
} else {
FragmentManager fm = getFragmentManager();
setMarker(LocationUtil.removeMarker(getMarker()));
if (findViewById(R.id.fragment_container).getVisibility() == View.GONE) {
toggleUI(true);
} else if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
}
/**
* Toggles the UI elements based on forward or backward navigation
*
* @param backPressed
*/
private void toggleUI(boolean backPressed) {
stateSaved = !backPressed;
findViewById(R.id.fragment_container).setVisibility(backPressed ? View.VISIBLE : View.GONE);
findViewById(R.id.map_shadow).setVisibility(backPressed ? View.VISIBLE : View.GONE);
findViewById(R.id.footer).setVisibility(backPressed ? View.GONE : View.VISIBLE);
findViewById(R.id.options_shadow).setVisibility(backPressed ? View.GONE : View.VISIBLE);
mMenu.findItem(R.id.action_comments).setVisible(!backPressed);
getMap().setMyLocationEnabled(backPressed);
if (backPressed) {
setReport(null);
setZoomLevel(LocationUtil.START_ZOOM_LEVEL);
getMap().animateCamera(CameraUpdateFactory.newLatLngZoom(LocationUtil.getCoordinates(getCurrentLocation()),
getZoomLevel()));
}
}
/**
* OnClick listener for SEND button
* Creates a new Report object using the data collected and spawns a HttpRequestTask
*
* @param view
*/
public void submitData(View view) {
if (!((CouncilAlertApplication) getApplication()).isNetworkConnected(this)) {
DialogUtil.showToast(this, getString(R.string.no_connnection));
} else {
Citizen citizen = (Citizen) ((CouncilAlertApplication) getApplication()).getUser();
new PostReportTask(getReport(), this).execute("citizen/" + citizen.getEmail());
}
}
public Report createNewReport(String type) {
Report report = new Report();
report.setName(type);
report.setLatitude(getCurrentLocation().getLatitude());
report.setLongitude(getCurrentLocation().getLongitude());
report.setStatus(false);
return report;
}
@Override
public void onResponseReceived(ResponseEntity<Message> response) {
if (response.getStatusCode().value() == HttpStatus.CREATED.value()) {
DialogUtil.showToast(this, response.getBody().getMessage());
finish();
} else if (response.getStatusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
DialogUtil.showToast(this, response.getBody().getMessage());
}
}
}
|
public class ArrayListOfStrings implements ListOfStrings {
/**
* Implémentation par un tableau qui l'on redimensionnera à chaque ajout.
*/
private String[] array;
public ArrayListOfStrings() {
array = new String[0];
}
@Override
public void add(String s) {
String[] tmp = new String[array.length + 1];
for(int i=0; i < array.length; i++) {
tmp[i] = array[i];
}
tmp[array.length] = s; // le dernier
array = tmp;
}
@Override
public int size() {
return array.length;
}
@Override
public void set(int i, String s) {
array[i] = s;
}
@Override
public String get(int i) {
return array[i];
}
}
|
package com.algorithm.array;
public class MissingNumber {
public int missingNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if ((nums[i + 1] - nums[i]) == 2) {
return nums[i] + 1;
}
}
return 0;
}
}
|
package com.chapter7.test;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Created by sheldonshen on 2017/3/21.
*/
public class GenericTypeUtils {
//获的一个泛型类的实际泛型类型
public static <T> Class<T> getGenericClassType(Class clz){
Type type = clz.getGenericSuperclass();
if(type instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType) type;
Type[] types = pt.getActualTypeArguments();
if(types.length > 0 && types[0] instanceof Class){
//若有多个泛型参数,依据位置索引返回
return (Class) types[0];
}
}
return (Class) Object.class;
}
}
|
/*
* 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 proof;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author Bancho
*/
public class Main {
//the 46th fib num is the last one below Integer.MAX_VALUE
public static final int LIMIT = 46;
public static void main(String[] args) {
ArrayList<Integer> numericValues = convertTextFileIntoNumericValues();
ArrayList<Integer> fibSeq = generateFibSeq(LIMIT);
Collections.reverse(fibSeq);
System.out.println("Number of letters: " + numericValues.size());
ArrayList<Match> matches = performCalculations(numericValues, fibSeq);
System.out.println("Matches: " + matches.size());
}
public static ArrayList<Match> performCalculations(ArrayList<Integer> letters, ArrayList<Integer> fibSeq) {
ArrayList<Match> existingMatches = new ArrayList<>();
int numOfLettersFibsMadeOf = 4;
while(numOfLettersFibsMadeOf > 0){
for (int i = 0; i < letters.size(); i+=numOfLettersFibsMadeOf) {
String strNum = "";
for (int j = 0; j < numOfLettersFibsMadeOf; j++) {
int index = i+j;
if(index >= letters.size() == false){
int val = letters.get(i+j);
String strVal = Integer.toString(val);
strNum = strNum.concat(strVal);
}
}
if (strNum.equals("")) {
continue;
}
int num = Integer.parseInt(strNum);
boolean matchPossible;
ArrayList<Integer> numsInSeq = null;
if(fibSeq.contains(num)){
matchPossible = true;
numsInSeq = new ArrayList<>();
numsInSeq.add(num);
}
else{
matchPossible = false;
}
while(matchPossible){
//test next ones
strNum = "";
for (int j = numsInSeq.size() * numOfLettersFibsMadeOf; j < numsInSeq.size() * numOfLettersFibsMadeOf + numOfLettersFibsMadeOf; j++) {
int index = i+j;
if(index >= letters.size() == false){ //avoiding IndexOutOfBoundsException
int val = letters.get(i+j);
String strVal = Integer.toString(val);
strNum = strNum.concat(strVal);
}
}
if (strNum.equals("")) {
matchPossible = false;
continue;
}
num = Integer.parseInt(strNum);
if(fibSeq.contains(num)){
int last = numsInSeq.get(numsInSeq.size() - 1);
int index = fibSeq.indexOf(last);
if(index + 1 >= fibSeq.size() == false){ //avoiding IndexOutOfBoundsException
if(num == fibSeq.get(index + 1)){
numsInSeq.add(num);
if(numsInSeq.size() >= 3){ //only three in a row or above count as a match
//ding ding ding
ArrayList<Match> matchesToBeOverWritten = new ArrayList<>();
for (Match match : existingMatches) {
if(match.getStartIndex() == i){
matchesToBeOverWritten.add(match);
}
}
existingMatches.removeAll(matchesToBeOverWritten);
existingMatches.add(new Match(numOfLettersFibsMadeOf, numsInSeq.size(), i, null)); //TODO: provide actual magical letters
}
}
else{
matchPossible = false;
}
}
else{
matchPossible = false;
}
}
else{
matchPossible = false;
}
}
}
numOfLettersFibsMadeOf--;
}
return existingMatches;
}
public static ArrayList<Integer> convertTextFileIntoNumericValues() {
// File file = new File("C:\\Users\\Bancho\\Documents\\NetBeansProjects\\Proof\\books\\bible.txt");
File file = new File("C:\\Users\\Bancho\\Documents\\NetBeansProjects\\Proof\\books\\my_path_to_atheism.txt");
FileInputStream fis = null;
ArrayList<Integer> values = new ArrayList();
try {
fis = new FileInputStream(file);
// System.out.println("Total file size to read (in bytes) : "
// + fis.available());
int content;
while ((content = fis.read()) != -1) {
char c = (char) content;
int numVal = Character.getNumericValue(c);
if(numVal >= 10){
values.add(numVal - 9);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return values;
}
public static ArrayList<Integer> generateFibSeq(int limit){
ArrayList<Integer> fibs = new ArrayList<>();
for (int i = 2; i <= limit; i++) {
fibs.add(fib(i));
}
return fibs;
}
//Iteration method for calculating fibs
private static int fib(int n) {
int x = 0, y = 1, z = 1;
for (int i = 0; i < n; i++) {
x = y;
y = z;
z = x + y;
}
return x;
}
}
|
package util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* 解析配置文件并连接数据库
* @author MG
*
*/
public class Jdbc {
static private String driver;
static private String url;
static private String uname;
static private String upassword;
static{ //解析配置文件
Properties pro = new Properties();
try {
pro.load(Jdbc.class.getResourceAsStream("Jdbc_Config.properties"));
driver = pro.getProperty("driver");
url = pro.getProperty("url");
uname = pro.getProperty("uname");
upassword = pro.getProperty("upassword");
} catch (IOException e) {
//e.printStackTrace();
}
}
/**
* LinkBase 并且返回数据库连接对象
* @return 数据库对象
*/
static public Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver); //用于测试数据库驱动的合法性
conn = DriverManager.getConnection(url, uname, upassword);
} catch (ClassNotFoundException | SQLException e) {
//e.printStackTrace();
}
try {
conn.setAutoCommit(false); //不自动提交数据
} catch (SQLException e) {
//e.printStackTrace();
}
return conn;
}
// static public void main(String[] args){
// System.out.println(Jdbc.getConnection());
// }
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.ioc.definition.field;
import xyz.noark.core.exception.ServerBootstrapException;
import xyz.noark.core.ioc.IocMaking;
import xyz.noark.core.ioc.definition.DefaultBeanDefinition;
import xyz.noark.core.util.FieldUtils;
import xyz.noark.core.util.MapUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Map类型的属性注入
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class MapFieldDefinition extends DefaultFieldDefinition {
public MapFieldDefinition(Field field, boolean required) {
super(field, (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[1], required);
}
@Override
protected Object extractInjectionObject(IocMaking making, Class<?> klass, Field field) {
List<DefaultBeanDefinition> allImpl = making.findAllImpl(fieldClass);
if (allImpl.isEmpty()) {
return Collections.emptyMap();
}
final Map<Serializable, Object> result = MapUtils.newHashMap(allImpl.size());
final Map<Serializable, DefaultBeanDefinition> primaryMap = MapUtils.newHashMap(allImpl.size());
Class<?> keyClass = FieldUtils.getMapKeyGenericClass(field);
// Int类型的Key,使用ID
if (Integer.class.equals(keyClass)) {
allImpl.forEach(v -> Arrays.stream(v.getIds()).forEach(n -> result.put(n, selectPrimaryImpl(primaryMap, n, v).getSingle())));
}
// 其他类型使用Name
else {
allImpl.forEach(v -> Arrays.stream(v.getNames()).forEach(n -> result.put(n, selectPrimaryImpl(primaryMap, n, v).getSingle())));
}
return result;
}
protected DefaultBeanDefinition selectPrimaryImpl(Map<Serializable, DefaultBeanDefinition> primaryMap, Serializable key, DefaultBeanDefinition newImpl) {
DefaultBeanDefinition oldImpl = primaryMap.get(key);
if (oldImpl == null) {
primaryMap.put(key, newImpl);
return newImpl;
}
// 这个名称有两个实现,优先级一样,好无语
if (oldImpl.isPrimary() == newImpl.isPrimary()) {
throw new ServerBootstrapException("Class:" + field.getDeclaringClass().getName() + ">>Field:" + field.getName()
+ " map key expected single matching bean but found 2. " +
"class1=" + oldImpl.getBeanClass().getName() + ", class2=" + newImpl.getBeanClass().getName());
}
// 新实现优先
if (newImpl.isPrimary()) {
primaryMap.put(key, newImpl);
return newImpl;
}
// 老实现优先
return oldImpl;
}
}
|
package four_target_for_interface_reference_example;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
@Aspect
@Component
@EnableAspectJAutoProxy
public class LoggingAspect { //this is aspect class
//Pointcut Designator :A pointcut expression starts with a pointcut designator (PCD), which is a keyword telling Spring AOP what to match. There are several pointcut designators, such as the execution of a method, a type, method arguments, or annotations.
@Before("target(MyInterface)")
public void call(){
System.out.println("before");
}
/*@Before("within(impl)")
public void call1() {
System.out.println("before");
}*/
}
|
package com.mygdx.game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Field {
final static int COL_COUNT = 15;
final static int ROW_COUNT = 23;
private Texture texture;
public Field() {
texture = Storage.getTexture("field_cell.bmp");
}
void draw() {
for (int iCol = 0; iCol < COL_COUNT; iCol++) {
for (int iRow = 0; iRow < ROW_COUNT; iRow++){
Storage.batch.draw(texture, texture.getWidth() * iCol, texture.getHeight() * iRow);
}
}
}
}
|
package com.lambdas;
import java.util.Arrays;
import java.util.List;
public class FuncInterfaceLambdasApp {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(new Car("honda", 25000, "blue"), new Car("hundayi", 35000, "red"),
new Car("suzuki", 95000, "green"), new Car("benz", 80000, "blue"), new Car("audi", 45000, "green"),
new Car("nissan", 65000, "yellow"), new Car("mg", 55000, "blue"));
System.out.println("Printing cars based on the color...");
// lambda expression for the below code
printCars(cars, (c) -> c.getColor().equals("green"));
// printCars(cars, new Condition1() {
//
// @Override
// public boolean test(Car c) {
// if (c.getColor().equals("blue"))
// return true;
// return false;
// }
// });
System.out.println("Printing cars based on the prince range..");
// lambda expression for the below code
printCars(cars, (c) -> c.getPrice() > 50000 && c.getPrice() < 70000);
// printCars(cars, new Condition1() {
//
// @Override
// public boolean test(Car c) {
// if (c.getPrice() > 55000 && c.getPrice() < 70000)
// return true;
// return false;
// }
// });
}
public static void printCars(List<Car> cars, Condition1 condition) {
for (Car c : cars) {
if (condition.test(c))
c.printCar();
;
}
}
}
@FunctionalInterface
interface Condition1 {
public boolean test(Car c);
}
|
package com.exam.zzz_other_menu;
// 소그룹 정보입력
public class Select_mart_Model{
private String group;
private String MartName;
private int BookMarker;
private long id;
public String getMartName()
{
return MartName;
}
public void setMartName(String MartName)
{
this.MartName = MartName;
}
public int getBookMarker()
{
return BookMarker;
}
public void setBookMarker(int BookMarker)
{
this.BookMarker = BookMarker;
}
public String getGroup()
{
return group;
}
public void setGroup(String group)
{
this.group = group;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
}
|
package com.youthlin.demo.antlr.calc;
/**
* 创建: youthlin.chen
* 时间: 2018-05-08 10:47
*/
public class DirectiveListener extends CalcBaseListener {
@Override
public void exitPrintExpr(CalcParser.PrintExprContext ctx) {
System.out.println("RET\n");
}
@Override
public void exitAssign(CalcParser.AssignContext ctx) {
String id = ctx.ID().getText();
System.out.println("STR " + id);
}
@Override
public void exitMulDiv(CalcParser.MulDivContext ctx) {
if (ctx.op.getType() == CalcParser.MUL) {
System.out.println("MUL");
} else {
System.out.println("DIV");
}
}
@Override
public void exitAddSub(CalcParser.AddSubContext ctx) {
if (ctx.op.getType() == CalcParser.ADD) {
System.out.println("ADD");
} else {
System.out.println("SUB");
}
}
@Override
public void exitId(CalcParser.IdContext ctx) {
System.out.println("LDV " + ctx.ID().getText());
}
@Override
public void exitInt(CalcParser.IntContext ctx) {
System.out.println("LDC " + ctx.INT().getText());
}
}
|
package io.nuls.cmd.client.processor.farm;
import io.nuls.base.api.provider.Result;
import io.nuls.base.api.provider.ServiceManager;
import io.nuls.base.api.provider.farm.FarmProvider;
import io.nuls.base.api.provider.farm.facade.FarmStakeReq;
import io.nuls.cmd.client.CommandBuilder;
import io.nuls.cmd.client.CommandResult;
import io.nuls.cmd.client.processor.CommandGroup;
import io.nuls.cmd.client.processor.CommandProcessor;
import io.nuls.core.core.annotation.Component;
/**
* @author Niels
*/
@Component
public class FarmStakeProcessor implements CommandProcessor {
private FarmProvider farmProvider = ServiceManager.get(FarmProvider.class);
@Override
public String getCommand() {
return "farmstake";
}
@Override
public CommandGroup getGroup() {
return CommandGroup.Farm;
}
@Override
public String getHelp() {
CommandBuilder builder = new CommandBuilder();
builder.newLine(getCommandDescription())
.newLine("\t<address> Address to send the transaction - Required")
.newLine("\t<farmHash> the ID of the farm - Required")
.newLine("\t<amount> Stake amount - Required");
return builder.toString();
}
@Override
public String getCommandDescription() {
return "farmstake <address> <farmHash> <amount> -- Stake assets to farm";
}
@Override
public boolean argsValidate(String[] args) {
checkArgsNumber(args, 3);
return true;
}
@Override
public CommandResult execute(String[] args) {
String password = getPwd();
Result<String> result = farmProvider.stake(new FarmStakeReq(args[1], args[2], Double.parseDouble(args[3]),password));
if (result.isFailed()) {
return CommandResult.getFailed(result);
}
return CommandResult.getSuccess(result);
}
}
|
package com.kh.jd.work;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.kh.jd.lecture.Lecture;
@Repository("workDao")
public class WorkDao {
@Autowired
private SqlSession sqlSession;
public List<Work> listWork(int startPage, int limit,Map<String, Object> map) {
int startRow = (startPage - 1) * limit;
RowBounds row = new RowBounds(startRow, limit);
return sqlSession.selectList("work.listWork", map, row);
}
public int getListCount(Map<String, Object> map) {
return sqlSession.selectOne("work.getlistCount",map);
}
public int addWork(Work vo) {
return sqlSession.insert("work.addWork",vo);
}
public Work viewWork(int work_no) {
return sqlSession.selectOne("work.viewWork", work_no);
}
public List<Lecture> lecturechk(int teacher_number){
return sqlSession.selectList("work.lecturechk",teacher_number);
}
public List<Work> classCheck(int lecture_no) {
return sqlSession.selectOne("work.classCheck", lecture_no);
}
public void removeWork(int work_no) {
sqlSession.delete("work.removeWork", work_no);
}
public void editWork(Work vo) {
sqlSession.update("work.editWork",vo);
}
public List<Work> listWorkResult(int startPage, int limit,Map<String, Object> map) {
int startRow = (startPage - 1) * limit;
RowBounds row = new RowBounds(startRow, limit);
return sqlSession.selectList("work.listWorkResult", map, row);
}
public int getlistWorkResultCount(Map<String, Object> map) {
return sqlSession.selectOne("work.getlistWorkResultCount",map);
}
public List<Work> registrationNo(int lecture_no) {
return sqlSession.selectList("work.registrationNo", lecture_no);
}
public int addWorkResult(int regstration_no) {
return sqlSession.insert("work.addWorkResult",regstration_no);
}
public int getCountClass1(int work_no) {
return sqlSession.selectOne("work.getCountClass1",work_no);
}
public int getCountWorkSubmit1(int work_no) {
return sqlSession.selectOne("work.getCountWorkSubmit1",work_no);
}
public int getCountClass2(int work_no) {
return sqlSession.selectOne("work.getCountClass2",work_no);
}
public int getCountWorkSubmit2(int work_no) {
return sqlSession.selectOne("work.getCountWorkSubmit2",work_no);
}
public List<Work> listSubmitWork(int startPage, int limit,Map<String, Object> map) {
int startRow = (startPage - 1) * limit;
RowBounds row = new RowBounds(startRow, limit);
return sqlSession.selectList("work.listSubmitWork", map, row);
}
public int getListSubmitCount(Map<String, Object> map) {
return sqlSession.selectOne("work.getlistSubmitCount",map);
}
public Work viewSubmitWork(Work vo) {
return sqlSession.selectOne("work.viewSubmitWork", vo);
}
public int submitWork(Work vo) {
return sqlSession.update("work.submitWork", vo);
}
public int removeSubmitWork(Work vo) {
return sqlSession.update("work.removeSubmitWork", vo);
}
}
|
/**
* Created by Chroon on 2016-11-12.
*/
package View;
import Interface.OptionChoisi;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Option implements OptionChoisi{
private Scene option,menu;
private ImageView fond;
private CheckBox tempete,god,assault;
private Button retour;
Text infoTempete,infoGod,infoAssault;
HBox opt1,opt2,opt3;
VBox org;
//Mode que quand tu lache le gaz le vaisseau deveinnt invisible
public Option(Stage leStage){
fond=new ImageView("Image/cielEtoile.gif");
retour=new Button("Retour");
tempete=new CheckBox();
infoTempete=new Text("Tempete solaire: ");
god=new CheckBox();
infoGod=new Text("Infini Essence: ");
assault=new CheckBox();
infoAssault=new Text("Assault orbital: ");
opt1=new HBox();
opt1.getChildren().addAll(infoTempete,tempete);
opt2=new HBox();
opt2.getChildren().addAll(infoGod,god);
opt3=new HBox();
opt3.getChildren().addAll(infoAssault,assault);
org=new VBox();
org.getChildren().addAll(opt1,opt2,opt3,retour);
setPosition(leStage);
setAction(leStage);
setText();
Group root = new Group();
root.getChildren().addAll(fond,org);
option=new Scene(root,1400,700);
}
private void setPosition(Stage stage){
org.setAlignment(Pos.CENTER);
org.setSpacing(30);
org.setPadding(new Insets(250,640,100,640));
fond.fitHeightProperty().bind(stage.heightProperty());
fond.fitWidthProperty().bind(stage.widthProperty());
}
private void setAction(Stage stage){
retour.setOnAction(event -> {
stage.setScene(menu);
});
}
private void setText(){
infoGod.setStroke(Color.WHITE);
infoTempete.setStroke(Color.WHITE);
infoAssault.setStroke(Color.WHITE);
}
Scene getSceneOption(){
return option;
}
void setSceneMenu(Scene scene){
menu=scene;
}
public boolean tempete(){
return tempete.isSelected();
}
public boolean cheatEssence(){
return god.isSelected();
}
public boolean asaultOrbital(){
return assault.isSelected();
}
}
/*
ven solaire forece sur cote
Lumiere soudaine rend lecran blanc
Météorite
quand tubouge tu devien invisibel
Moins ta te gaz + taccelaire
*/
|
package com.skp.test.linkedlist;
public class LinkedList {
private Node head;
public void setHead(Node head) {
this.head = head;
}
public LinkedList() {
}
public Node getHead() {
return head;
}
public void add(Node node) {
if (head == null) {
head = node;
return;
}
Node start = head;
while (start.getNext() != null) {
start = start.getNext();
}
start.setNext(node);
}
public void display() {
Node start = head;
while (start != null) {
System.out.println(start.getVal());
start = start.getNext();
}
}
}
|
public class SavingAccountNegativeException extends Exception {
public SavingAccountNegativeException(String msg) {
super(msg);
}
}
|
package com.atguigu.java;
public class SingletonTest {
public static void main(String[] args) {
Bank instance = Bank.getInstance();
System.out.println(instance);
}
}
/*
*
* 使用代码块去实现单例
*/
class Bank{
//1.私有化构造器
private Bank(){}
//2.提供该类对象的声明
private static Bank bank = null;
static{ //只能使用静态代码块。(不能使用非静态代码块,因为非静态代码块是随着对象的创建而加载的)
bank = new Bank();
}
//3.提供一个公共的方法返回当前类的对象
public static Bank getInstance(){
return bank;
}
}
|
package spriet2000.state.variant1.impl;
import spriet2000.state.variant1.ProductContext;
import spriet2000.state.variant1.ProductState;
import java.util.Arrays;
import java.util.List;
public class CancelledState extends ProductState {
public void handle(ProductContext context) {
// logic
System.out.printf("logic applied of status %s%n", this.getName());
// set new state
context.setState(this);
}
public String getName() {
return "Cancelled";
}
public List<ProductState> getNextStates(ProductContext context) {
return Arrays.asList(new ProductState[0]);
}
}
|
package edu.usf.cse.physmotive;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import edu.usf.cse.physmotive.db.UserDBM;
public class MainMenu extends Activity implements LocationListener
{
// Database Fields
public static final String ID = "_id";
public static final String FNAME = "firstName";
public static final String LNAME = "lastName";
public static final String USERID = "userId";
// Visible Items on screen
protected Button newActivityButton;
protected Button viewActivityButton;
protected Button mapButton;
protected Button diaryButton;
protected Button statisticsButton;
protected Button settingsButton;
protected Button newUserButton;
protected Spinner userSpinner;
protected LocationManager locationManager;
protected GeoPoint point;
// Internal Variables
private int userId = 1;
private UserDBM userDBM;
private Cursor userCursor;
private SimpleCursorAdapter adapter;
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userDBM = new UserDBM(this);
// Connect interface elements to properties
newActivityButton = (Button) findViewById(R.id.newActivityButton);
viewActivityButton = (Button) findViewById(R.id.viewActivityButton);
mapButton = (Button) findViewById(R.id.mapButton);
diaryButton = (Button) findViewById(R.id.diaryButton);
statisticsButton = (Button) findViewById(R.id.statisticsButton);
settingsButton = (Button) findViewById(R.id.settingsButton);
newUserButton = (Button) findViewById(R.id.newUserButton);
userSpinner = (Spinner) findViewById(R.id.userSpinner);
setOnClickListeners();
updateSpinner();
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
// Get initial location locations.
this.getInitialLocation();
}
private void initiateLocationServices()
{
// Use the LocationManager class to obtain GPS locations.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
@Override
protected void onResume()
{
super.onResume();
// Restore state here
updateSpinner();
initiateLocationServices();
}
@Override
protected void onPause()
{
super.onPause();
userCursor.close();
userDBM.close();
}
@Override
public void onStop()
{
super.onStop();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location loc)
{
// Stores the information in the point
point = new GeoPoint((int) (loc.getLatitude() * 1E6), (int) (loc.getLongitude() * 1E6));
Log.d("lat:long", loc.getLatitude() + ":" + loc.getLongitude());
locationManager.removeUpdates(this);
}
@Override
public void onProviderDisabled(String provider)
{
Log.d("onProviderDisabled", "GPS Disabled");
}
@Override
public void onProviderEnabled(String provider)
{
Log.d("onProviderEnabled", "GPS Enabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO: Something
}
public void getInitialLocation()
{
initiateLocationServices();
Location lastKnown = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnown != null)
{
Log.d("last known lat:long", lastKnown.getLatitude() + ":" + lastKnown.getLongitude());
} else
{
Log.d("GPS", "Determining location...");
}
}
// //////////////////////////////////////////////
// This is the beginning of the dialog windows //
// //////////////////////////////////////////////
@Override
protected Dialog onCreateDialog(int i, Bundle args)
{
LayoutInflater factory = LayoutInflater.from(this);
switch (i) {
// This case is for the New User Dialog
case 0:
// Setup of the view for the dialog
final View textEntryView = factory.inflate(R.layout.new_user, null);
return new AlertDialog.Builder(MainMenu.this)
// .setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.newUserTitle).setView(textEntryView)
.setPositiveButton(R.string.btnSave, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
// Gets text fields from dialog
EditText firstName = (EditText) textEntryView.findViewById(R.id.userFirstNameEditText);
EditText lastName = (EditText) textEntryView.findViewById(R.id.userLastNameEditText);
firstName.requestFocus();
// Verifies the fields have information in
// them
if (firstName.getText().toString().equals("")
|| firstName.getText().toString().trim().equals("")
|| lastName.getText().toString().equals("")
|| lastName.getText().toString().trim().equals(""))
{
Toast.makeText(MainMenu.this, "User must have first and last name.", Toast.LENGTH_LONG)
.show();
firstName.setText("");
lastName.setText("");
} else
{
Toast.makeText(MainMenu.this, "The user is saving...", Toast.LENGTH_SHORT).show();
userDBM.open();
userId = userDBM.insert(firstName.getText().toString(), lastName.getText().toString(), 0, 0,
0, 0, 0, 0, 0, userId);
userDBM.close();
firstName.setText("");
lastName.setText("");
updateSpinner();
}
}
}).setNegativeButton(R.string.btnCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
// clears the fields and closes the dialog
EditText firstName = (EditText) textEntryView.findViewById(R.id.userFirstNameEditText);
EditText lastName = (EditText) textEntryView.findViewById(R.id.userLastNameEditText);
firstName.requestFocus();
firstName.setText("");
lastName.setText("");
}
}).create();
default:
break;
}
return null;
}
// //////////////////////////////////
// User Spinner setup and controls //
// //////////////////////////////////
private void updateSpinner()
{
int user;
userDBM.open();
// gets list of available users
userCursor = userDBM.getList(userId);
startManagingCursor(userCursor);
String[] from = new String[] { ID, FNAME, LNAME };
int[] to = new int[] { R.id.itemId, R.id.itemText1, R.id.itemText2 };
adapter = new SimpleCursorAdapter(this, R.layout.two_part_list_item, userCursor, from, to);
userSpinner.setAdapter(adapter);
// Sets the proper name to display
for (int i = 0; i < userSpinner.getCount(); i++)
{
Cursor value = (Cursor) userSpinner.getItemAtPosition(i);
user = value.getInt(value.getColumnIndex(ID));
// if userId equals the saved userId of the app the spinner will
// select that user
if (((Integer) user).intValue() == ((Integer) userId).intValue())
{
userSpinner.setSelection(i);
}
}
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
userDBM.close();
}
public class MyOnItemSelectedListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
// Gets cursor from list, updates the new userId
Cursor value = (Cursor) parent.getItemAtPosition(pos);
userId = value.getInt(0);
}
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing.
}
}
// ///////////////
// Button Setup //
// ///////////////
// Overrides the back button to always exit the app
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
private void invokeActivityMenu(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), ActivityMenu.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void invokeActivityView(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), ActivityList.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void invokeDiaryList(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), DiaryList.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void invokeMapView(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), MapMenu.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void invokeStatisticsMenu(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), StatisticsMenu.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void invokeSettingsMenu(View arg0)
{
Intent myIntent = new Intent(arg0.getContext(), SettingsMenu.class);
Bundle b = new Bundle();
b.putInt(USERID, userId);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
private void setOnClickListeners()
{
newActivityButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickNewActivity(v);
}
});
viewActivityButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickViewActivity(v);
}
});
mapButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickMap(v);
}
});
diaryButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickDiary(v);
}
});
statisticsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickStatistics(v);
}
});
settingsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickSettings(v);
}
});
newUserButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
onButtonClickNewUser(v);
}
});
}
private void onButtonClickNewActivity(View w)
{
invokeActivityMenu(w);
}
private void onButtonClickViewActivity(View w)
{
invokeActivityView(w);
}
private void onButtonClickMap(View w)
{
invokeMapView(w);
}
private void onButtonClickDiary(View w)
{
invokeDiaryList(w);
}
private void onButtonClickStatistics(View w)
{
invokeStatisticsMenu(w);
}
private void onButtonClickSettings(View w)
{
invokeSettingsMenu(w);
}
private void onButtonClickNewUser(View w)
{
showDialog(0, null);
}
}
|
package com.guard.myguard.services.interfaces;
import java.io.Serializable;
public interface ParsingService {
/**
* Method is responsible for serializing object to json
*
* @param object is object to serialize
* @return json representation of serialized object
*/
String serialize(Serializable object);
/**
* Method is responsible for deserialization object from json
*
* @param json is string representation of serialized object
* @param type is class to which we want to deserialize json
* @return deserialized object
*/
<T> T deserialize(String json, Class<T> type);
}
|
package com.nosae.game.objects;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import com.nosae.game.popo.GameParams;
import com.nosae.game.popo.R;
import com.nosae.game.settings.DebugConfig;
/**
* Created by eason on 2015/10/23.
*/
public class Score extends GameObj {
public static Integer[] mScore = {
R.drawable.s_0,
R.drawable.s_1,
R.drawable.s_2,
R.drawable.s_3,
R.drawable.s_4,
R.drawable.s_5,
R.drawable.s_6,
R.drawable.s_7,
R.drawable.s_8,
R.drawable.s_9,
};
private final int destX;
private final int destY;
public final int edge_X_right;
public int totalScore;
public int width;
public int height;
protected Bitmap bitmap;
public Score(int destX, int destY) {
super(destX, destY, 0, 0, 0, 0, 0, 0, 0, 0, 0);
this.destX = destX;
this.destY = destY;
bitmap = GameParams.decodeResource(mScore[0]);
width = bitmap.getWidth();
height = bitmap.getHeight();
edge_X_right = (int) (destX + 3 * width + 4 * GameParams.density);
bitmap.recycle();
bitmap = null;
}
public void setTotalScore(int totalScore) {
this.totalScore = totalScore;
}
public void drawScore(Canvas canvas) {
int[] digits = getDigitsOf(totalScore);
// bitmap = (Bitmap) BitmapFactory.decodeResource(GameParams.res,
// mScore[0]);
Bitmap bitmap;
for (int i = 0; i < digits.length; i++) {
bitmap = GameParams.decodeResource(mScore[digits[i]]);
if (bitmap != null)
canvas.drawBitmap(bitmap, destX + i * bitmap.getWidth() + i * 2 * GameParams.density, destY, null);
}
}
public int[] getDigitsOf(int num)
{
int digitCount = Integer.toString(num).length();
if (num < 0)
digitCount--;
int[] result = new int[digitCount];
while (digitCount-- >0) {
result[digitCount] = num % 10;
num /= 10;
}
return result;
}
}
|
package com.codingKnowledge.entity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Client implements InitializingBean, DisposableBean {
private String driver, url, username, password;
private Connection con;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void afterPropertiesSet() throws Exception {
/* Resources Initialization */
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Opened....\n");
}
public void save(int id, String name, String gender, String address) {
String sql = "insert into client values(?,?,?,?)";
PreparedStatement pst;
try {
pst = con.prepareStatement(sql);
pst.setInt(1, id);
pst.setString(2, name);
pst.setString(3, gender);
pst.setString(4, address);
pst.executeUpdate();
System.out.println("Inserted Successfully....\n");
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void destroy() throws Exception {
/* Resources Destroy */
con.close();
System.out.println("Connection Closed....\n");
}
}
|
package com.minoon.disco;
import android.animation.ValueAnimator;
import android.view.View;
import com.minoon.disco.choreography.Choreography;
import com.minoon.disco.choreography.ScrollChoreography;
import com.minoon.disco.choreography.ViewChaseChoreography;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A Choreography set linked with a view.
* This class has dependent child views and choreography set.
*
* Created by a13587 on 15/09/11.
*/
/* package */ class ChoreographyChain {
private static final String TAG = Logger.createTag(ChoreographyChain.class.getSimpleName());
private final List<ScrollChoreography> myScrollChoreography;
private final List<ViewChaseChoreography> myChoreography;
private final Map<View, ChoreographyChain> childChoreography;
/**
* Constructor
*
*/
/* package */ ChoreographyChain() {
childChoreography = new HashMap<>();
myChoreography = new ArrayList<>();
myScrollChoreography = new ArrayList<>();
}
/* package */ ChoreographyChain(ScrollChoreography scrollChoreography) {
this();
myScrollChoreography.add(scrollChoreography);
}
/**
* transform the chaser view based on the scroll information.
*
* @param chaserView
* @param dx
* @param dy
* @param x
* @param y
*/
/* package */ void playScroll(View chaserView, int dx, int dy, int x, int y) {
boolean changed = false;
for (ScrollChoreography c : myScrollChoreography) {
changed = changed || c.playScroll(chaserView, dx, dy, x, y);
}
if (changed) {
for (View v : childChoreography.keySet()) {
childChoreography.get(v).playChase(chaserView, v);
}
}
}
/**
* {@link #playChase(View, View, boolean)}
*
* @param anchorView
* @param chaserView
*/
/* package */ void playChase(View anchorView, View chaserView) {
playChase(anchorView, chaserView, false);
}
/**
* transform the chaser view based on the condition of the anchor view.
*
* @param anchorView
* @param chaserView
* @param force
*/
/* package */ void playChase(View anchorView, View chaserView, boolean force) {
boolean changed = false;
for (ViewChaseChoreography c : myChoreography) {
changed = changed || c.playChase(anchorView, chaserView);
}
if (changed || force) {
for (View v : childChoreography.keySet()) {
childChoreography.get(v).playChase(chaserView, v, force);
}
}
}
/**
* animate view and notify event to child views.
*
* @param event
* @param chaserView
*/
/* package */ void playEvent(Enum event, final View chaserView) {
long duration = 0;
for (Choreography c : myChoreography) {
duration = Math.max(duration, c.playEvent(event, chaserView));
}
for (Choreography c : myScrollChoreography) {
duration = Math.max(duration, c.playEvent(event, chaserView));
}
for (View v : childChoreography.keySet()) {
childChoreography.get(v).playEvent(event, v);
}
// animate child views while chaserView is animating.
if (duration > 0) {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(duration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
for (View v : childChoreography.keySet()) {
childChoreography.get(v).playChase(chaserView, v);
}
}
});
animator.start();
}
}
/**
* add as child which depends on their own.
*
* @param childView
* @param choreography
*/
/* package */ void addChildDependency(View childView, ViewChaseChoreography choreography) {
if (childChoreography.containsKey(childView)) {
childChoreography.get(childView).addMyChoreography(choreography);
} else {
ChoreographyChain childChain = new ChoreographyChain();
childChain.addMyChoreography(choreography);
childChoreography.put(childView, childChain);
}
}
/**
* add as child which depends on their own.
*
* @param childView
* @param choreography
*/
/* package */ void addChildDependency(View childView, ScrollChoreography choreography) {
if (childChoreography.containsKey(childView)) {
childChoreography.get(childView).addMyChoreography(choreography);
} else {
ChoreographyChain childChain = new ChoreographyChain();
childChoreography.put(childView, childChain);
}
}
/**
* add view dependency if there is an anchor view in the offspring.
*
* @param anchorView
* @param childView
* @param choreography
*/
/* package */ void maybeAddDependency(View anchorView, View childView, ViewChaseChoreography choreography) {
// if the child map has a anchor view, add grandchild view with choreography.
if (childChoreography.containsKey(anchorView)) {
ChoreographyChain child = childChoreography.get(anchorView);
child.addChildDependency(childView, choreography);
return;
}
// loop for child instance
for (ChoreographyChain d : childChoreography.values()) {
d.maybeAddDependency(anchorView, childView, choreography);
}
}
private void addMyChoreography(ViewChaseChoreography choreography) {
if (choreography != null && !myChoreography.contains(choreography)) {
myChoreography.add(choreography);
}
}
private void addMyChoreography(ScrollChoreography choreography) {
if (choreography != null && !myChoreography.contains(choreography)) {
myScrollChoreography.add(choreography);
}
}
/**
* remove anchor view.
* return true if this dependency meaning is gone and should be removed.
*
* @param chaserView
* @return
*/
/* package */ void removeChaserView(View chaserView) {
if (childChoreography.containsKey(chaserView)) {
childChoreography.remove(chaserView);
}
for (View v : childChoreography.keySet()) {
childChoreography.get(v).removeChaserView(chaserView);
}
}
}
|
package com.example.myprog.java;
import com.example.myprog.java.garage.Car;
import com.example.myprog.java.garage.parking.ParkingSpot;
import com.example.myprog.kotlin.garage.CarKt;
import com.example.myprog.kotlin.garage.parking.ParkingSpotKt;
public class MyProg {
public static int multiply(int a, int b) {
int result = 0;
for (int i = 0; i < b; i++) {
result += a;
}
return result;
}
public static void main(String[] args) {
nullCheckingExamples();
}
private static void nullCheckingExamples() {
/* Null dereference, warning due to Java @Nullable annotation. */
ParkingSpot<Car> mySpot = new ParkingSpot<>(20, 10, null);
mySpot.getVehicle().sayHello();
/* Kotlin version, bytecode also gets an equivalent annotation. */
ParkingSpotKt<CarKt> mySpotKt = new ParkingSpotKt<>(20, 10, null);
mySpotKt.getVehicle().sayHello();
/* Worked around by null-checking a local variable. Safe! */
Car theCarToCheck = mySpot.getVehicle();
if (theCarToCheck != null) {
theCarToCheck.sayHello();
} else {
System.out.println("The car is null!");
}
}
}
|
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.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Driver_signup extends AppCompatActivity {
Button sign_et;
TextView login_et;
ImageView back_et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_signup);
sign_et =(Button) findViewById(R.id.signup_id);
login_et =(TextView) findViewById(R.id.login_id);
back_et = (ImageView) findViewById(R.id.back_id);
}
public void open_home_layout(View v){
Intent i = new Intent(Driver_signup.this, Driver_home_layout.class);
startActivity(i);
}
public void open_login_layout(View v){
Intent i = new Intent(Driver_signup.this ,Driver_login.class);
startActivity(i);
}
public void back(View v){
Intent i = new Intent(Driver_signup.this ,Driver_login.class);
startActivity(i);
}
}
|
package com.ifeng.recom.mixrecall.core.channel.impl;
import com.ifeng.recom.mixrecall.common.constant.GyConstant;
import com.ifeng.recom.mixrecall.common.model.RecallResult;
import com.ifeng.recom.mixrecall.common.model.RecordInfo;
import com.ifeng.recom.mixrecall.common.model.UserModel;
import com.ifeng.recom.mixrecall.common.model.request.LogicParams;
import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo;
import com.ifeng.recom.mixrecall.core.cache.preload.SourceExploreCache;
import com.ifeng.recom.mixrecall.core.channel.excutor.UserSourceRecallExecutorN;
import com.ifeng.recom.mixrecall.core.threadpool.ExecutorThreadPool;
import com.ifeng.recom.tools.common.logtools.model.TimerEntity;
import com.ifeng.recom.tools.common.logtools.utils.timer.TimerEntityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Created by lilg1 on 2018/1/18.
*/
@Service
public class UserSourceChannelImpl {
private final static Logger logger = LoggerFactory.getLogger(UserSourceChannelImpl.class);
private static final Logger timeLogger = LoggerFactory.getLogger(TimerEntityUtil.class);
private final static int timeout = 500;
private List<RecordInfo> convertSoruceToRecallInfo(List<RecordInfo> sourceForExplores) {
List<RecordInfo> results = new ArrayList<>();
if (sourceForExplores == null || sourceForExplores.size() == 0) {
return results;
}
RecordInfo recordInfo = null;
for (RecordInfo s : sourceForExplores) {
recordInfo = new RecordInfo(GyConstant.key_Source + s.getRecordName(), s.getWeight());
results.add(recordInfo);
}
return results;
}
/**
* 每个标签召回量写死3条,试验多样性
* @param mixRequestInfo
* @return
*/
public List<RecallResult> doRecallN(MixRequestInfo mixRequestInfo) {
UserModel userModel = mixRequestInfo.getUserModel();
TimerEntity timer = TimerEntityUtil.getInstance();
List<RecallResult> result = new ArrayList<>();
timer.addStartTime("totalUserSource");
try {
LogicParams logicParams = mixRequestInfo.getLogicParams();
timer.addStartTime("userGetSource");
//获取用户媒体来源
List<RecordInfo> sourceForExplores = SourceExploreCache.getFromCache(mixRequestInfo.getUid());
//变更sourceName格式
sourceForExplores = convertSoruceToRecallInfo(sourceForExplores);
timer.addEndTime("userGetSource");
timer.addStartTime("getSourceDoc");
UserSourceRecallExecutorN userSourceRecallExecutorN = new UserSourceRecallExecutorN(mixRequestInfo, sourceForExplores);
result = userSourceRecallExecutorN.call();
timer.addEndTime("getSourceDoc");
} catch (Exception e) {
logger.error("uid:{},UserSourceChannelImpl thread error {}", mixRequestInfo.getUid(), e);
e.printStackTrace();
}
timer.addEndTime("totalUserSource");
timeLogger.info("ChannelLog UserSourceChannelImpl {} uid:{}", timer.getStaticsInfo(), userModel.getUserId());
TimerEntityUtil.remove();
return result;
}
}
|
package com.atomix.jsonparse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.atomix.datamodel.AnnouncementsInfo;
import com.atomix.datamodel.ArticleInfo;
import com.atomix.datamodel.AuthorInfo;
import com.atomix.datamodel.ClassifiedCategoryInfo;
import com.atomix.datamodel.ClassifiedInfo;
import com.atomix.datamodel.ClassifiedsOwnerInfo;
import com.atomix.datamodel.ClassifiedsPhotoInfo;
import com.atomix.datamodel.EventsInfo;
import com.atomix.datamodel.ForumCommentator;
import com.atomix.datamodel.ForumComments;
import com.atomix.datamodel.ForumHotTopics;
import com.atomix.datamodel.ForumPhotoInfo;
import com.atomix.datamodel.ForumsInfo;
import com.atomix.datamodel.ForumsTagInfo;
import com.atomix.datamodel.GalleryDetailsInfo;
import com.atomix.datamodel.GalleryInfo;
import com.atomix.datamodel.GalleryYearInfo;
import com.atomix.datamodel.HumanResourceInfo;
import com.atomix.datamodel.NotificationInfo;
import com.atomix.datamodel.OfferPromotionCategories;
import com.atomix.datamodel.OfferPromotionInfo;
import com.atomix.datamodel.OfferPromotionPhoto;
import com.atomix.datamodel.PoliceisInfo;
import com.atomix.datamodel.PoliciesDeptInfo;
import com.atomix.datamodel.SidraInNewsAPIInfo;
import com.atomix.datamodel.SidraPressReleaseInfo;
import com.atomix.datamodel.StaffDirectoryDepartmentsInfo;
import com.atomix.datamodel.StaffListInfo;
import com.atomix.datamodel.UserInfo;
import com.atomix.sidrainfo.ConstantValues;
import com.atomix.sidrainfo.SidraPulseApp;
import com.atomix.utils.Utilities;
public class CommunicationLayer {
public static int getSignInData(String func_id, String user_id, String password, String device_type, String device_token, String registration_key) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("username", user_id));
postData.add((NameValuePair) new BasicNameValuePair("password", password));
postData.add((NameValuePair) new BasicNameValuePair("device_type", device_type));
postData.add((NameValuePair) new BasicNameValuePair("device_token", device_token));
postData.add((NameValuePair) new BasicNameValuePair("registration_key", registration_key));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("server response ", "__________"+serverResponse);
return parseSignInData(serverResponse);
}
private static int parseSignInData(String jData) throws JSONException {
int logindata;
JSONObject jDataObj = new JSONObject(jData);
logindata = jDataObj.getInt("status");
UserInfo info = new UserInfo();
if(logindata == 1) {
JSONObject dataObj = jDataObj.getJSONObject("data");
info.setUserID(dataObj.getInt("user_id"));
info.setPushStatus(dataObj.getInt("push_on"));
info.setAccessToken(dataObj.getString("access_token").trim());
Log.e("------User Id", dataObj.getString("user_id").trim());
} else {
}
SidraPulseApp.getInstance().setUserInfo(info);
return logindata;
}
//API #2
public static int getPushStatusData(String func_id, String user_id, String access_token, String push_on) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("push_on", push_on));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parsePushStatusData(serverResponse);
}
private static int parsePushStatusData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
//API #3
public static int getNotificationData(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseNotificationData(serverResponse);
}
private static int parseNotificationData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
NotificationInfo info = new NotificationInfo();
Log.i("Notification Response","" + jData);
if(jDataObj.getInt("status") == 1) {
JSONObject dataObj = jDataObj.getJSONObject("data");
info.setAnnouncement(dataObj.getInt("announcement"));
info.setClassified(dataObj.getInt("classified"));
info.setEvent(dataObj.getInt("event"));
info.setGallery(dataObj.getInt("gallery"));
info.setOfferAndPromotion(dataObj.getInt("offerAndPromotion"));
info.setForum(dataObj.getInt("forum"));
} else {
}
SidraPulseApp.getInstance().setNotificationInfo(info);
return jDataObj.getInt("status");
}
//API #4
public static int getAnnouncementData(String func_id, String user_id, String access_token, String last_element_id, String direction) throws Exception {
Log.i("AnnounceMent_PARAM","f_id: " + func_id + " accToken: " + access_token + " Page: " + " page_no: " + last_element_id);
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("Announcement Response", "***" + serverResponse);
return parseAnnouncementData(serverResponse, last_element_id, direction);
}
private static int parseAnnouncementData(String jData, String element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<AnnouncementsInfo> arrayList = new ArrayList<AnnouncementsInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
AnnouncementsInfo info = new AnnouncementsInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setType(values.getString("cat_name").trim());
info.setId(values.getInt("id"));
info.setTitle(values.getString("title").trim());
info.setDescription(values.getString("description").trim());
info.setDayAndDate(Utilities.dateConvertion(values.getString("created_at").trim()));
info.setDate(Utilities.eventFullDateConvertion(values.getString("created_at").trim()));
info.setTime(Utilities.timeConversion(values.getString("created_at").trim()));
info.setReadStatus(values.getInt("is_read"));
arrayList.add(info);
}
}
if (!"".equals(element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getAnnouncementsInfoList().addAll(arrayList);
} else if (!"".equals(element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getAnnouncementsInfoList().addAll(0, arrayList);
}else {
SidraPulseApp.getInstance().setAnnouncementsInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
return jDataObj.getInt("status");
}
public static int getUnReadData(String func_id, String user_id, String access_token, String type, String element_id) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("element_id", element_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseUnReadData(serverResponse);
}
private static int parseUnReadData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getBubbleUnReadData(String func_id, String user_id, String access_token, String type) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseBubbleUnReadData(serverResponse);
}
private static int parseBubbleUnReadData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
//API #15
//API #15
public static int getOfferAndPromotionData(String func_id, String user_id, String access_token, String type, String cat_id, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("server response offer and promotion ", "_______________" + serverResponse);
return parseOfferAndPromotionData(serverResponse, last_element_id, direction);
}
private static int parseOfferAndPromotionData(String jData,String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<OfferPromotionInfo> arrayList = new ArrayList<OfferPromotionInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
OfferPromotionInfo offerPromotionInfo = new OfferPromotionInfo();
JSONObject values = dataArray.getJSONObject(i);
offerPromotionInfo.setId(values.getInt("id"));
offerPromotionInfo.setCategoryId(values.getInt("cat_id"));
offerPromotionInfo.setTitle(values.getString("title").trim());
if(!values.getString("valid_until").trim().equalsIgnoreCase("null")) {
offerPromotionInfo.setValidUntil(Utilities.offerPromotionDateConvertion(values.getString("valid_until").trim()));
} else {
offerPromotionInfo.setValidUntil("");
}
offerPromotionInfo.setLongTerm(values.getInt("long_term"));
offerPromotionInfo.setDescription(values.getString("description").trim());
offerPromotionInfo.setCompanyThumb(values.getString("company_thumb").trim());
// offerPromotionInfo.setApprovedBy(values.getInt("approved_by"));
// offerPromotionInfo.setPublishedBy(values.getInt("published_by"));
offerPromotionInfo.setIsDelete(values.getInt("is_del"));
offerPromotionInfo.setIsDraft(values.getInt("is_draft"));
offerPromotionInfo.setCreatedBy(values.getInt("created_by"));
offerPromotionInfo.setUpdatedBy(values.getInt("updated_by"));
offerPromotionInfo.setCreatedAt(Utilities.offerPromotionDateConvertion(values.getString("created_at").trim()).toString());
offerPromotionInfo.setUpdatedAt(Utilities.offerPromotionDateConvertion(values.getString("updated_at").trim()));
offerPromotionInfo.setIsBookmarked(values.getInt("is_bookmarked"));
ArrayList<OfferPromotionPhoto> photo_arraylist = new ArrayList<OfferPromotionPhoto>();
JSONArray values_photoArray = values.getJSONArray("photo");
if(values_photoArray.length() > 1) {
for(int j = 0; j < values_photoArray.length(); j++) {
OfferPromotionPhoto photo = new OfferPromotionPhoto();
JSONObject photoObject = values_photoArray.getJSONObject(j);
photo.setId(photoObject.getInt("id"));
photo.setOffer_and_promotion_id(photoObject.getInt("offer_and_promotion_id"));
photo.setPhoto(photoObject.getString("photo").trim());
photo.setIsDelete(photoObject.getInt("is_del"));
photo_arraylist.add(photo);
}
offerPromotionInfo.setPhotoArray(photo_arraylist);
}
arrayList.add(offerPromotionInfo);
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().addAll(0,arrayList);
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(null);
}
} else {
/*if (Integer.parseInt(last_element_id) > 1) {
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(null);
} */
//SidraPulseApp.getInstance().setOfferPromotionInfoList(null);
}
return jDataObj.getInt("status");
}
/*public static int getOfferAndPromotionData(String func_id, String user_id, String access_token, String type, String cat_id, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("server response offer and promotion ", "_______________"+serverResponse);
return parseOfferAndPromotionData(serverResponse, last_element_id, direction);
}
private static int parseOfferAndPromotionData(String jData,String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<OfferPromotionInfo> arrayList = new ArrayList<OfferPromotionInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
OfferPromotionInfo offerPromotionInfo = new OfferPromotionInfo();
JSONObject values = dataArray.getJSONObject(i);
offerPromotionInfo.setId(values.getInt("id"));
offerPromotionInfo.setCategoryId(values.getInt("cat_id"));
offerPromotionInfo.setTitle(values.getString("title"));
if(!values.getString("valid_until").equalsIgnoreCase("null")) {
offerPromotionInfo.setValidUntil(Utilities.offerPromotionDateConvertion(values.getString("valid_until")));
} else {
offerPromotionInfo.setValidUntil("");
}
offerPromotionInfo.setLongTerm(values.getInt("long_term"));
offerPromotionInfo.setDescription(values.getString("description"));
offerPromotionInfo.setCompanyThumb(values.getString("company_thumb"));
// offerPromotionInfo.setApprovedBy(values.getInt("approved_by"));
// offerPromotionInfo.setPublishedBy(values.getInt("published_by"));
offerPromotionInfo.setIsDelete(values.getInt("is_del"));
offerPromotionInfo.setIsDraft(values.getInt("is_draft"));
offerPromotionInfo.setCreatedBy(values.getInt("created_by"));
offerPromotionInfo.setUpdatedBy(values.getInt("updated_by"));
offerPromotionInfo.setCreatedAt(Utilities.offerPromotionDateConvertion(values.getString("created_at")).toString());
offerPromotionInfo.setUpdatedAt(Utilities.offerPromotionDateConvertion(values.getString("updated_at")));
offerPromotionInfo.setIsBookmarked(values.getInt("is_bookmarked"));
ArrayList<OfferPromotionPhoto> photo_arraylist = new ArrayList<OfferPromotionPhoto>();
JSONArray values_photoArray = values.getJSONArray("photo");
if(values_photoArray.length() > 1) {
for(int j = 0; j < values_photoArray.length(); j++) {
OfferPromotionPhoto photo = new OfferPromotionPhoto();
JSONObject photoObject = values_photoArray.getJSONObject(j);
photo.setId(photoObject.getInt("id"));
photo.setOffer_and_promotion_id(photoObject.getInt("offer_and_promotion_id"));
photo.setPhoto(photoObject.getString("photo"));
photo.setIsDelete(photoObject.getInt("is_del"));
photo_arraylist.add(photo);
}
offerPromotionInfo.setPhotoArray(photo_arraylist);
}
arrayList.add(offerPromotionInfo);
} // End For Loop
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().addAll(0,arrayList);
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(null);
} // End dataArray length checking
} else {
if (Integer.parseInt(last_element_id) > 1) {
} else {
SidraPulseApp.getInstance().setOfferPromotionInfoList(null);
}
}
return jDataObj.getInt("status");
}*/
public static int getBookmarkOfferAndPromotion(String func_id, String user_id, String access_token, String offer_id, String is_bookmark) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("offer_id", offer_id));
postData.add((NameValuePair) new BasicNameValuePair("is_bookmark", is_bookmark));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseBookmarkOfferAndPromotion(serverResponse);
}
private static int parseBookmarkOfferAndPromotion(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getOfferAndPromotionCategories(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return getOfferAndPromotionCategories(serverResponse);
}
private static int getOfferAndPromotionCategories (String jData) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<OfferPromotionCategories> arrayList = new ArrayList<OfferPromotionCategories>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
Log.e("category data", "---------"+dataArray);
for(int i = 0; i < dataArray.length(); i++) {
OfferPromotionCategories catagoryInfo = new OfferPromotionCategories();
JSONObject values = dataArray.getJSONObject(i);
catagoryInfo.setId(values.getInt("id"));
catagoryInfo.setCategoryName(values.getString("cat_name").trim());
catagoryInfo.setCreatedBy(values.getInt("created_by"));
catagoryInfo.setUpdatedBy(values.getInt("updated_by"));
catagoryInfo.setIsDelete(values.getInt("is_del"));
catagoryInfo.setCreatedAt(Utilities.offerPromotionDateConvertion(values.getString("created_at").trim()).toString());
catagoryInfo.setUpdatedAt(Utilities.offerPromotionDateConvertion(values.getString("updated_at").trim()));
arrayList.add(catagoryInfo);
Collections.sort(arrayList, OfferPromotionCategories.CategoryNameComparator);
}
}
} else {
}
SidraPulseApp.getInstance().setOfferAndPromotionCategories(arrayList);
return jDataObj.getInt("status");
}
public static int getGalleryData(String func_id, String user_id, String access_token, String year) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("year", year));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseGalleryData(serverResponse);
}
private static int parseGalleryData(String jData) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<GalleryInfo> arrayList = new ArrayList<GalleryInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
GalleryInfo info = new GalleryInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setAlbumTitle(values.getString("cat_name").trim());
info.setAlbumImageUrl(values.getString("thumb").trim());
info.setPhotoNumber(Integer.toString(values.getInt("photos")));
info.setVideoNumber(Integer.toString(values.getInt("videos")));
info.setTotalAlbum(values.getInt("total_album"));
info.setDate(Utilities.eventFullDateConvertion(values.getString("created_at").trim()));
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setGalleryInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getGalleryImageAndVideoData(String func_id, String user_id, String access_token, String gallery_id, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("gallery_id", gallery_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseGalleryImageAndVideoData(serverResponse, last_element_id, direction);
}
private static int parseGalleryImageAndVideoData(String jData, String last_element_id, String direction) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<GalleryDetailsInfo> arrayList = new ArrayList<GalleryDetailsInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
GalleryDetailsInfo info = new GalleryDetailsInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setMediaType(values.getInt("media_type"));
info.setId(values.getInt("id"));
info.setImageOrVideoUrl(values.getString("media").trim());
arrayList.add(info);
}
}
} else {
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getGalleryDetailsInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getGalleryDetailsInfoList().addAll(0, arrayList);
} else {
SidraPulseApp.getInstance().setGalleryDetailsInfoList(arrayList);
}
return jDataObj.getInt("status");
}
public static int getLogoutData(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseLogoutData(serverResponse);
}
private static int parseLogoutData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
//API #7
public static int getEventsData(String func_id, String user_id, String access_token, String type, String date, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(7);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("date", date));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
Log.i("EVENT POST DATA API NO 7","***" + postData);
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("EVENTS","***" + serverResponse);
return parseEventsData(serverResponse, last_element_id, direction);
}
private static int parseEventsData(String jData, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<EventsInfo> arrayList = new ArrayList<EventsInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
EventsInfo info = new EventsInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setEventTitle(values.getString("event_title").trim());
info.setVanue(values.getString("venue").trim());
info.setEventDescription(values.getString("event_description").trim());
info.setStartDate(Utilities.eventFullDateConvertion(values.getString("start_dt").trim()));
info.setStartTime(Utilities.timeConversion(values.getString("start_dt").trim()));
info.setEventStartDay(Utilities.eventDayConvertion(values.getString("start_dt").trim()).toUpperCase());
info.setEventStartDate(Utilities.eventDateConvertion(values.getString("start_dt").trim()));
info.setEventStartFullDate(Utilities.eventReminderDateConvertion(values.getString("start_dt").trim()));
info.setEventEndFullDate(Utilities.eventReminderDateConvertion(values.getString("end_dt").trim()));
info.setEndDate(Utilities.eventFullDateConvertion(values.getString("end_dt").trim()));
info.setEndTime(Utilities.timeConversion(values.getString("end_dt").trim()));
info.setEventEndDay(Utilities.eventDayConvertion(values.getString("end_dt").trim()).toUpperCase());
info.setEventEndDate(Utilities.eventDateConvertion(values.getString("end_dt").trim()));
info.setBookMarked(values.getInt("is_bookmarked"));
arrayList.add(info);
}
if (!"".equals(last_element_id) && "1".equals(direction)) {
SidraPulseApp.getInstance().getEventsInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && "0".equals(direction)) {
SidraPulseApp.getInstance().getEventsInfoList().addAll(0, arrayList);
} else {
SidraPulseApp.getInstance().setEventsInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
//SidraPulseApp.getInstance().setEventsInfoList(null);
}
} else {
//SidraPulseApp.getInstance().setEventsInfoList(null);
}
return jDataObj.getInt("status");
}
public static int getStaffDirectoryDepartmentsData(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseStaffDirectoryDepartmentsData(serverResponse);
}
private static int parseStaffDirectoryDepartmentsData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<StaffDirectoryDepartmentsInfo> arrayList = new ArrayList<StaffDirectoryDepartmentsInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
StaffDirectoryDepartmentsInfo info = new StaffDirectoryDepartmentsInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setDepartmentName(values.getString("dept_name").trim());
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setDirectoryDepartmentsInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getStaffDirectoryStaffListData(String func_id, String user_id, String access_token, String dept_id, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("dept_id", dept_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
Log.e("StaffDirectory","post: ***" + postData);
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseStaffDirectoryStaffListData(serverResponse, last_element_id, direction);
}
private static int parseStaffDirectoryStaffListData(String jData, String last_element_id,String direction) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<StaffListInfo> arrayList = new ArrayList<StaffListInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
StaffListInfo info = new StaffListInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setName(values.getString("name").trim());
info.setDesignation(values.getString("designation").trim());
info.setDepartment(values.getString("dept_name").trim());
info.setEmail(values.getString("email").trim());
info.setOffice(values.getInt("office"));
info.setMobile(Integer.toString(values.getInt("mobile")));
info.setIsBookmarked(values.getInt("is_bookmarked"));
arrayList.add(info);
}
}
if (!"".equals(last_element_id) && "1".equals(direction)) {
SidraPulseApp.getInstance().getStaffListInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && "0".equals(direction)) {
SidraPulseApp.getInstance().getStaffListInfoList().addAll(0, arrayList);
} else {
SidraPulseApp.getInstance().setStaffListInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
//SidraPulseApp.getInstance().setStaffListInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getEventMakeFavourite(String func_id, String user_id, String access_token, String is_fav, String event_id) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("is_fav", is_fav));
postData.add((NameValuePair) new BasicNameValuePair("event_id", event_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseEventMakeFavourite(serverResponse);
}
private static int parseEventMakeFavourite(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getSidraInNewsAPI(String func_id, String user_id, String access_token, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("SIDRA_IN_NEWS", "*** " + serverResponse);
return parseSidraInNewsAPI(serverResponse, last_element_id, direction);
}
private static int parseSidraInNewsAPI(String jData, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<SidraInNewsAPIInfo> arrayList = new ArrayList<SidraInNewsAPIInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
SidraInNewsAPIInfo newsApi = new SidraInNewsAPIInfo();
JSONObject values = dataArray.getJSONObject(i);
newsApi.setId(values.getInt("id"));
newsApi.setHeadline(values.getString("headline").trim());
newsApi.setReleaseDate(Utilities.dateConvertion(values.getString("release_date").trim())+", "+Utilities.timeConversion(values.getString("release_date").trim()));
newsApi.setSourcePublication(values.getString("source_publication").trim());
newsApi.setLink(values.getString("link").trim());
// newsApi.setApprovedBy(values.getInt("approved_by"));
// newsApi.setPublishedBy(values.getInt("published_by"));
newsApi.setIsDelete(values.getInt("is_del"));
newsApi.setIsDraft(values.getInt("is_draft"));
newsApi.setCreatedBy(values.getInt("created_by"));
newsApi.setUpdatedBy(values.getInt("updated_by"));
newsApi.setCreatedAt(Utilities.dateConvertion(values.getString("created_at").trim()).toString()+", "+Utilities.timeConversion(values.getString("created_at").trim()));
newsApi.setUpdatedAt(Utilities.dateConvertion(values.getString("updated_at").trim())+", "+Utilities.timeConversion(values.getString("updated_at").trim()));
newsApi.setStatus(values.getInt("status"));
arrayList.add(newsApi);
}
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getSidraInNewsAPI().addAll(arrayList);
}else if (!"".equals(last_element_id) && direction.equals("0")){
SidraPulseApp.getInstance().getSidraInNewsAPI().addAll(0,arrayList);
} else {
SidraPulseApp.getInstance().setSidraInNewsAPI(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
return jDataObj.getInt("status");
}
//API #12
public static int getSidraPressRelease(String func_id, String user_id, String access_token, String last_element_id , String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseSidraPressRelease(serverResponse, last_element_id, direction);
}
private static int parseSidraPressRelease(String jData, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<SidraPressReleaseInfo> arrayList = new ArrayList<SidraPressReleaseInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
SidraPressReleaseInfo pressRelease = new SidraPressReleaseInfo();
JSONObject values = dataArray.getJSONObject(i);
pressRelease.setId(values.getInt("id"));
pressRelease.setTitle(values.getString("title").trim());
pressRelease.setReleaseDate(Utilities.dateConvertion(values.getString("release_date").trim()));
pressRelease.setReleaseTime(Utilities.timeConversion(values.getString("release_date").trim()));
pressRelease.setContent(values.getString("content").trim());
// pressRelease.setApprovedBy(values.getInt("approved_by"));
// pressRelease.setPublishedBy(values.getInt("published_by"));
pressRelease.setIsDelete(values.getInt("is_del"));
pressRelease.setIsDraft(values.getInt("is_draft"));
pressRelease.setCreatedBy(values.getInt("created_by"));
pressRelease.setUpdatedBy(values.getInt("updated_by"));
pressRelease.setCreatedAt(Utilities.dateConvertion(values.getString("created_at").trim())+", "+Utilities.timeConversion(values.getString("created_at").trim()));
pressRelease.setUpdatedAt(Utilities.dateConvertion(values.getString("updated_at").trim())+", "+Utilities.timeConversion(values.getString("updated_at").trim()));
pressRelease.setStatus(values.getInt("status"));
arrayList.add(pressRelease);
}//end for loop
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getSidraPressRelease().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getSidraPressRelease().addAll(0,arrayList);
} else {
SidraPulseApp.getInstance().setSidraPressRelease(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
return jDataObj.getInt("status");
}
public static int getHumanResourcesCategory(String func_id, String user_id, String access_token, String type, boolean isArticle, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
Log.i("FAQ POST", "*****" + postData);
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.e("Server response is: faq", "----------------" + serverResponse);
return parseHumanResourcesCategory(serverResponse, isArticle, last_element_id, direction);
}
private static int parseHumanResourcesCategory(String jData, boolean isArticle, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
if(isArticle) {
ArrayList<ArticleInfo> arrayList = new ArrayList<ArticleInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ArticleInfo info = new ArticleInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setCatId(values.getInt("cat_id"));
info.setQuestion(values.getString("question").trim());
info.setAnswer(values.getString("answer").trim());
info.setUpdatedAt(Utilities.dateConvertion(values.getString("updated_at").trim())+", "+Utilities.timeConversion(values.getString("updated_at").trim()));
arrayList.add(info);
}
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getArticleInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getArticleInfoList().addAll(1, arrayList);
} else {
SidraPulseApp.getInstance().setArticleInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
} else {
ArrayList<HumanResourceInfo> arrayList = new ArrayList<HumanResourceInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
HumanResourceInfo info = new HumanResourceInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setQuestion(values.getString("question").trim());
info.setAnswer(values.getString("answer").trim());
arrayList.add(info);
}
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getHumanResourceInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getHumanResourceInfoList().addAll(0, arrayList);
} else {
SidraPulseApp.getInstance().setHumanResourceInfoList(arrayList);;
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
} else {
}
//SidraPulseApp.getInstance().setHumanResourceInfoList(arrayList);
}
return jDataObj.getInt("status");
}
public static int getHumanResourceList(String func_id, String user_id, String access_token, String cat_id, String page_no) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("page_no", page_no));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseHumanResourceList(serverResponse);
}
private static int parseHumanResourceList(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<HumanResourceInfo> arrayList = new ArrayList<HumanResourceInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
HumanResourceInfo info = new HumanResourceInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setQuestion(values.getString("question").trim());
info.setAnswer(values.getString("answer").trim());
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setHumanResourceInfoList(arrayList);
return jDataObj.getInt("status");
}
// API #17 Show Classifieds
public static int getShowClassified(String func_id, String user_id, String access_token, String type, String cat_id, String last_element_id, String direction) throws Exception {
Log.e("is classed", "");
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseShowClassified(serverResponse, last_element_id, direction);
}
private static int parseShowClassified(String jData, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<ClassifiedInfo> arrayList = new ArrayList<ClassifiedInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ClassifiedInfo info = new ClassifiedInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setTitle(values.getString("title").trim());
info.setDescription(values.getString("description").trim());
info.setCatId(values.getInt("cat_id"));
info.setCreatedBy(values.getInt("created_by"));
info.setUpdatedBy(values.getInt("updated_by"));
info.setIsDel(values.getInt("is_del"));
info.setStatus(values.getInt("status"));
info.setIsDraft(values.getInt("is_draft"));
info.setUpdatedAt(Utilities.eventFullDateConvertion(values.getString("updated_at").trim()));
info.setCreatedAt(Utilities.eventFullDateConvertion(values.getString("created_at").trim()));
JSONArray ownerDataArray = values.getJSONArray("owner_info");
ClassifiedsOwnerInfo ownerInfo = new ClassifiedsOwnerInfo();
if (ownerDataArray.length() > 0) {
JSONObject ownerValues = ownerDataArray.getJSONObject(0);
ownerInfo.setName(ownerValues.getString("name").trim());
ownerInfo.setEmail(ownerValues.getString("email").trim());
if(!"".equalsIgnoreCase(ownerValues.getString(("mobile").trim())))
{
ownerInfo.setMobile(ownerValues.getString(("mobile").trim()));
}
}
info.setOwnerInfo(ownerInfo);
JSONArray photoDataArray = values.getJSONArray("photo");
ArrayList<ClassifiedsPhotoInfo> photoArrayList = new ArrayList<ClassifiedsPhotoInfo>();
if(photoDataArray.length() > 0){
for(int j = 0; j < photoDataArray.length(); j++) {
ClassifiedsPhotoInfo photoInfo = new ClassifiedsPhotoInfo();
JSONObject photoValues = photoDataArray.getJSONObject(j);
photoInfo.setId(photoValues.getInt("id"));
photoInfo.setPhoto(photoValues.getString("photo").trim());
photoInfo.setClassifiedId(photoValues.getInt("classified_id"));
photoInfo.setIsDel(photoValues.getInt("is_del"));
photoInfo.setUpdatedAt(photoValues.getString("updated_at").trim());
photoInfo.setCreatedAt(Utilities.eventFullDateConvertion(photoValues.getString("created_at").trim()));
photoArrayList.add(photoInfo);
}
info.setPhotoInfo(photoArrayList);
}
arrayList.add(info);
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getClassifiedInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getClassifiedInfoList().addAll(0,arrayList);
} else {
SidraPulseApp.getInstance().setClassifiedInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
}
} else {
}
/*if (Integer.parseInt(last_element_id) > 1) {
SidraPulseApp.getInstance().getClassifiedInfoList().addAll(arrayList);
} else {
SidraPulseApp.getInstance().setClassifiedInfoList(arrayList);
}
*/
return jDataObj.getInt("status");
}
// API #18 Classifieds Categories
public static int getClassifiedCategories(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseClassifiedCategories(serverResponse);
}
private static int parseClassifiedCategories(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<ClassifiedCategoryInfo> arrayList = new ArrayList<ClassifiedCategoryInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ClassifiedCategoryInfo pressRelease = new ClassifiedCategoryInfo();
JSONObject values = dataArray.getJSONObject(i);
pressRelease.setId(values.getInt("id"));
pressRelease.setCategoryName(values.getString("cat_name").trim());
arrayList.add(pressRelease);
}
}
} else {
}
SidraPulseApp.getInstance().setClassifiedCategoryInfoList(arrayList);
return jDataObj.getInt("status");
}
// API# 19 Classifieds Photo Upload
public static String getClassifiedPhotoUpload(String func_id, String user_id, String access_token, String photo) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("photo", photo));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseClassifiedPhotoUpload(serverResponse);
}
private static String parseClassifiedPhotoUpload(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
JSONObject photoData = jDataObj.getJSONObject("data");
String photoName = photoData.getString("photo_name").trim();
//return jDataObj.getInt("status");
return photoName;
}
// API #20 Classified Entry
public static int getClassifiedEntry(String func_id, String user_id, String access_token, String cat_id, String title, String description, String photo, String is_draft) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(8);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("title", title));
postData.add((NameValuePair) new BasicNameValuePair("description", description));
postData.add((NameValuePair) new BasicNameValuePair("photo", photo));
postData.add((NameValuePair) new BasicNameValuePair("is_draft", is_draft));
Log.e("classified entry is", "--"+ postData);
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseClassifiedEntry(serverResponse);
}
private static int parseClassifiedEntry(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
// API #21
public static int getShowTagList(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseShowTagList(serverResponse);
}
private static int parseShowTagList(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<ForumsTagInfo> arrayList = new ArrayList<ForumsTagInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ForumsTagInfo pressRelease = new ForumsTagInfo();
JSONObject values = dataArray.getJSONObject(i);
pressRelease.setId(values.getInt("id"));
pressRelease.setTagName(values.getString("tag_name").trim());
arrayList.add(pressRelease);
}
}
} else {
}
SidraPulseApp.getInstance().setForumsTagInfoList(arrayList);
return jDataObj.getInt("status");
}
// API #22
public static int getAPIShowForumList(String func_id, String user_id, String access_token, String type, String tag_id, String last_element_id, String direction) throws Exception {
Log.i("FORUM_LIST_PARAM","f_id: " + func_id + " accToken: " + access_token + " type: " + type + " tag: " + tag_id + " element_id: " + last_element_id + " Direction" + direction);
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("tag_id", tag_id));
postData.add((NameValuePair) new BasicNameValuePair("last_element_id", last_element_id));
postData.add((NameValuePair) new BasicNameValuePair("direction", direction));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.i("FORUM RESPONSE","DATA " + serverResponse);
return parseAPIShowForumList(serverResponse, last_element_id, direction);
}
private static int parseAPIShowForumList(String jData, String last_element_id, String direction) throws JSONException, ParseException {
Calendar calendarDay = Calendar.getInstance();
JSONObject jDataObj = new JSONObject(jData);
ArrayList<ForumsInfo> arrayList = new ArrayList<ForumsInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ForumsInfo info = new ForumsInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setText(values.getString("text").trim());
info.setCreatedBy(values.getInt("created_by"));
info.setUpdatedBy(values.getInt("updated_by"));
info.setUpdatedAt(values.getString("updated_at").trim());
if (Utilities.getNowDay(values.getString("created_at").trim()).equalsIgnoreCase(Integer.toString(calendarDay.get(Calendar.DATE)))) {
info.setCreatedAt("Today"+", "+Utilities.timeConversion(values.getString("created_at").trim()));
} else {
info.setCreatedAt(Utilities.dateConvertion(values.getString("created_at").trim())+" "+Utilities.timeConversion(values.getString("created_at").trim()));
}
info.setIsDel(values.getInt("is_del"));
info.setStatus(values.getInt("status"));
JSONObject authorArrayData = values.getJSONObject("author_info");
AuthorInfo authorInfo = new AuthorInfo();
authorInfo.setName(authorArrayData.getString("name").trim());
authorInfo.setEmail(authorArrayData.getString("email").trim());
authorInfo.setMobile(authorArrayData.getString("mobile").trim());
info.setAuthorInfo(authorInfo);
JSONArray photoArrayData = values.getJSONArray("photo");
ArrayList<ForumPhotoInfo> photoArray = new ArrayList<ForumPhotoInfo>();
if(photoArrayData.length() > 0) {
for(int j = 0; j <photoArrayData.length(); j++) {
ForumPhotoInfo photoInfo = new ForumPhotoInfo();
JSONObject photoValue = photoArrayData.getJSONObject(j);
photoInfo.setId(photoValue.getInt("id"));
photoInfo.setForumId(photoValue.getInt("forum_id"));
photoInfo.setPhoto(photoValue.getString("photo").trim());
photoInfo.setStatus(photoValue.getInt("status"));
photoInfo.setUpdatedAt(Utilities.offerPromotionDateConvertion(photoValue.getString("updated_at").trim()));
if (Utilities.getNowDay(photoValue.getString("created_at").trim()).equalsIgnoreCase(Integer.toString(calendarDay.get(Calendar.DATE)))) {
photoInfo.setCreatedAt("Today"+", "+Utilities.timeConversion(values.getString("created_at").trim()));
} else {
//photoValue.getString("created_at")
photoInfo.setCreatedAt(Utilities.dateConvertion(photoValue.getString("created_at").trim())+", "+Utilities.timeConversion(values.getString("created_at")));
}
photoArray.add(photoInfo);
}
}
info.setForumPhotos(photoArray);
JSONArray commmentsArrayData = values.getJSONArray("comments");
ArrayList<ForumComments> commmentsArray = new ArrayList<ForumComments>();
if(commmentsArrayData.length()>0)
{
for(int k = 0; k <commmentsArrayData.length(); k++) {
ForumComments commentsInfo = new ForumComments();
JSONObject commentsValue = commmentsArrayData.getJSONObject(k);
commentsInfo.setId(commentsValue.getInt("id"));
commentsInfo.setUserId(commentsValue.getInt("user_id"));
commentsInfo.setForumId(commentsValue.getInt("forum_id"));
commentsInfo.setCommentText(commentsValue.getString("comment_text").trim());
commentsInfo.setVideoUrl(commentsValue.getString("video").trim());
commentsInfo.setCommentsPhoto(commentsValue.getString("image").trim());
commentsInfo.setIsDel(commentsValue.getInt("is_del"));
commentsInfo.setUpdatedAt(Utilities.offerPromotionDateConvertion(commentsValue.getString("updated_at").trim()));
if (Utilities.getNowDay(commentsValue.getString("created_at").trim()).equalsIgnoreCase(Integer.toString(calendarDay.get(Calendar.DATE)))) {
commentsInfo.setCreatedAt(("Today")+", "+Utilities.timeConversion(values.getString("created_at").trim()));
} else {
commentsInfo.setCreatedAt(Utilities.dateConvertion(commentsValue.getString("created_at").trim()) + ", " + Utilities.timeConversion(commentsValue.getString("created_at").trim()));
}
JSONObject commmentatorArrayData = commentsValue.getJSONObject("commentator");
ForumCommentator commmentator = new ForumCommentator();
if( commmentatorArrayData!=null){
commmentator.setName(commmentatorArrayData.getString("name").trim());
commmentator.setEmail(commmentatorArrayData.getString("email").trim());
commmentator.setMobile(commmentatorArrayData.getString("mobile").trim());
}
else{
Log.e("Commentator is null", "--------------------------");
}
commentsInfo.setCommentator(commmentator);
commmentsArray.add(commentsInfo);
}
}
info.setForumComments(commmentsArray);
info.setDate(Utilities.eventDateConvertion(values.getString("created_at").trim()).toString());
info.setTotalComments(values.getInt("total_comments"));
arrayList.add(info);
}
if (!"".equals(last_element_id) && direction.equals("1")) {
SidraPulseApp.getInstance().getForumsInfoList().addAll(arrayList);
} else if (!"".equals(last_element_id) && direction.equals("0")) {
SidraPulseApp.getInstance().getForumsInfoList().addAll(0, arrayList);
} else {
SidraPulseApp.getInstance().setForumsInfoList(arrayList);
}
if (dataArray.length() == 10) {
ConstantValues.PullDownActive = true;
} else {
ConstantValues.PullDownActive = false;
}
}
} else {
}
return jDataObj.getInt("status");
}
//API #23
public static int getThreadPhotoUpload(String func_id, String user_id, String access_token, String photo) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("photo", photo));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseThreadPhotoUpload(serverResponse);
}
private static int parseThreadPhotoUpload(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
//API #24
public static int getThreadEntryAPI(String func_id, String user_id, String access_token, String photo, String text, String tags) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("photo", photo));
postData.add((NameValuePair) new BasicNameValuePair("text", text));
postData.add((NameValuePair) new BasicNameValuePair("tags", tags));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseThreadEntryAPI(serverResponse);
}
private static int parseThreadEntryAPI(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getShowAllPolicyDept(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(3);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.e("Server Response for policy dept", ""+serverResponse);
return parseShowAllPolicyDept(serverResponse);
}
private static int parseShowAllPolicyDept(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<PoliciesDeptInfo> arrayList = new ArrayList<PoliciesDeptInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
PoliciesDeptInfo info = new PoliciesDeptInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setCatName(values.getString("cat_name").trim());
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setPoliciesDeptInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getShowPolicyDataByDept(String func_id, String user_id, String access_token, String dept_id) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(4);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("dept_id", dept_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.e("Server Response for policy data by dept", ""+serverResponse);
return parseShowPolicyDataByDept(serverResponse);
}
private static int parseShowPolicyDataByDept(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<PoliceisInfo> arrayList = new ArrayList<PoliceisInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
PoliceisInfo info = new PoliceisInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setTitle(values.getString("title").trim());
info.setPolicyNo(values.getInt("policy_no"));
info.setOverview(values.getString("overview").trim());
info.setPolicyStatement(values.getString("policy_statement").trim());
info.setDefinitions(values.getString("definitions").trim());
info.setReference(values.getString("reference").trim());
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setPoliceisInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getDeleteAPI(String func_id, String user_id, String access_token, String type, String element_id) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("element_id", element_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseDeleteAPI(serverResponse);
}
private static int parseDeleteAPI(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getForumComment(String func_id, String user_id, String access_token, String forum_id, String comment_text) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("forum_id", forum_id));
postData.add((NameValuePair) new BasicNameValuePair("comment_text", comment_text));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseForumComment(serverResponse);
}
private static int parseForumComment(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
public static int getStaffSearchData(String func_id, String user_id, String access_token, String dept_id, String keyword) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("dept_id", dept_id));
postData.add((NameValuePair) new BasicNameValuePair("keyword", keyword));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseStaffSearch(serverResponse);
}
private static int parseStaffSearch(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<StaffListInfo> arrayList = new ArrayList<StaffListInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
StaffListInfo info = new StaffListInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setId(values.getInt("id"));
info.setName(values.getString("name").trim());
info.setDesignation(values.getString("designation").trim());
info.setDepartment(values.getString("dept_name").trim());
info.setEmail(values.getString("email").trim());
info.setOffice(values.getInt("office"));
info.setMobile(values.getString("mobile").trim());
info.setIsBookmarked(values.getInt("is_bookmarked"));
arrayList.add(info);
}
}
} else {
}
SidraPulseApp.getInstance().setStaffListInfoList(arrayList);
return jDataObj.getInt("status");
}
public static int getStaffBookmarkData(String func_id, String user_id, String access_token, String is_bookmark, String staff_id) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(5);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("is_bookmark", is_bookmark));
postData.add((NameValuePair) new BasicNameValuePair("staff_id", staff_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseStaffBookmard(serverResponse);
}
private static int parseStaffBookmard(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
// API #35 Classified Entry
public static int getClassifiedUpdate(String func_id, String user_id, String access_token, String cat_id, String classified_id, String title, String description, String photo, String is_draft) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(9);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("cat_id", cat_id));
postData.add((NameValuePair) new BasicNameValuePair("classified_id", classified_id ));
postData.add((NameValuePair) new BasicNameValuePair("title", title));
postData.add((NameValuePair) new BasicNameValuePair("description", description));
postData.add((NameValuePair) new BasicNameValuePair("photo", photo));
postData.add((NameValuePair) new BasicNameValuePair("is_draft", is_draft));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseClassifiedUpfate(serverResponse);
}
private static int parseClassifiedUpfate(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
return jDataObj.getInt("status");
}
//API #36
public static int getGalleryYearData(String func_id, String user_id, String access_token) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
return parseGalleryYearData(serverResponse);
}
private static int parseGalleryYearData(String jData) throws JSONException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<GalleryYearInfo> arrayList = new ArrayList<GalleryYearInfo>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
GalleryYearInfo info = new GalleryYearInfo();
JSONObject values = dataArray.getJSONObject(i);
info.setTotalAlbum(values.getInt("total_album"));
info.setYear(values.getString("year").trim());
arrayList.add(info);
}
SidraPulseApp.getInstance().setGalleryYearInfoList(arrayList);
}
} else {
SidraPulseApp.getInstance().setGalleryYearInfoList(null);
}
return jDataObj.getInt("status");
}
public static int getAPIShowForumTopics(String func_id, String user_id, String access_token, String type, String tag_id, String last_element_id, String direction) throws Exception {
List<NameValuePair> postData = new ArrayList<NameValuePair>(6);
postData.add((NameValuePair) new BasicNameValuePair("func_id", func_id));
postData.add((NameValuePair) new BasicNameValuePair("user_id", user_id));
postData.add((NameValuePair) new BasicNameValuePair("access_token", access_token));
postData.add((NameValuePair) new BasicNameValuePair("type", type));
postData.add((NameValuePair) new BasicNameValuePair("tag_id", tag_id));
postData.add((NameValuePair) new BasicNameValuePair("page_no", last_element_id));
String serverResponse = WebServerOperation.sendHTTPPostRequestToServer(SidraPulseApp.getInstance().getBaseUrl(), postData, true);
Log.e("Server Response", "---" + serverResponse);
return parseAPIShowForumTopics(serverResponse, last_element_id, direction);
}
private static int parseAPIShowForumTopics(String jData, String last_element_id, String direction) throws JSONException, ParseException {
JSONObject jDataObj = new JSONObject(jData);
ArrayList<ForumHotTopics> arrayList = new ArrayList<ForumHotTopics>();
if(jDataObj.getInt("status") == 1) {
JSONArray dataArray = jDataObj.getJSONArray("data");
if(dataArray.length() > 0) {
for(int i = 0; i < dataArray.length(); i++) {
ForumHotTopics hotTopics = new ForumHotTopics();
JSONObject values = dataArray.getJSONObject(i);
hotTopics.setTagId(values.getInt("tag_id"));
hotTopics.setTagName(values.getString("tag_name").trim());
hotTopics.setTotal(values.getInt("total_posts"));
arrayList.add(hotTopics);
}
}
} else {
}
SidraPulseApp.getInstance().setHotTopicsList(arrayList);
return jDataObj.getInt("status");
}
}
|
package lab11;
import java.io.File;
import java.util.Scanner;
/**
* Created by ran on 4/1/16.
*
* bubble sort, insertion sort & selection sort
*
*/
public class Lab {
public static void main(String[] args) throws Exception{
//prepare file
String file = "src/lab10/students.dat";
Scanner sc = new Scanner(new File(file));
Student[] s = new Student[3380];
Student[] t = new Student[3380];
//load file to array
long startTime = System.nanoTime();
int i = 0;
while (sc.hasNext()){
String temp = sc.nextLine();
String[] temps = temp.split(" ");
s[i] = new Student(temps[0], temps[1], temps[2], Long.parseLong(temps[3]));
i++;
}
long finishTime = System.nanoTime();
long elapsedTime = finishTime - startTime;;
sc.close();
System.out.println("Load file to array takes " + elapsedTime / 1E9 + " seconds");
//do bubble sort
System.arraycopy(s, 0, t, 0, s.length);
startTime = System.nanoTime();
bubbleSort(t);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println("Bubble sort of data file takes " + elapsedTime / 1E9 + " seconds");
//do insertion sort
System.arraycopy(s, 0, t, 0, s.length);
startTime = System.nanoTime();
insertionSort(t);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println("Insertion sort of data file takes " + elapsedTime / 1E9 + " seconds");
//do selection sort
System.arraycopy(s, 0, t, 0, s.length);
startTime = System.nanoTime();
selectionSort(t);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println("Selection sort of data file takes " + elapsedTime / 1E9 + " seconds");
//for (Student c : t) {System.out.println(c.toString());}
}
//bubble sort
public static void bubbleSort(Student[] o) {
int swapped = 1;
int i = 0;
while (swapped != 0) {
swapped = 0;
for (int j = 0; j < (o.length - i - 1); j++) {
if (o[j].compareTo(o[j+1]) > 0) {
Student temp;
temp = new Student(o[j].lastname, o[j].firstname, o[j].middlename, o[j].id);
o[j] = new Student(o[j+1].lastname, o[j+1].firstname, o[j+1].middlename, o[j+1].id);
o[j+1] = new Student(temp.lastname, temp.firstname, temp.middlename, temp.id);
swapped++;
}
}
i++;
}
}
//insertion sort
public static void insertionSort(Student[] o) {
for (int i = 1; i < o.length - 1; i++) {
int j = i;
while (j > 0 && (o[j-1].compareTo(o[j]) > 0)) {
Student temp;
temp = new Student(o[j].lastname, o[j].firstname, o[j].middlename, o[j].id);
o[j] = new Student(o[j-1].lastname, o[j-1].firstname, o[j-1].middlename, o[j-1].id);
o[j-1] = new Student(temp.lastname, temp.firstname, temp.middlename, temp.id);
j--;
}
}
}
//selection sort
public static void selectionSort(Student[] o) {
for (int i = 0; i < o.length; i++) {
int min = i;
for (int j = i+1; j < o.length; j++) {
if (o[min].compareTo(o[j]) > 0) {
min = j;
}
}
if (i != min) {
Student temp;
temp = new Student(o[i].lastname, o[i].firstname, o[i].middlename, o[i].id);
o[i] = new Student(o[min].lastname, o[min].firstname, o[min].middlename, o[min].id);
o[min] = new Student(temp.lastname, temp.firstname, temp.middlename, temp.id);
}
}
}
}
|
package pairSumDivBySixty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class pairDivisibleBySixty {
int comb(int x){
return x*(x-1)/2;
}
public static void main(String args[]) {
pairDivisibleBySixty p = new pairDivisibleBySixty();
Scanner s = new Scanner(System.in);
System.out.println("Enter numbers (comma separated): ");
String input[] = s.nextLine().trim().split(" ");
// System.out.println("Enter sum: ");
// int sum = s.nextInt();
s.close();
float temp;
//create hashmap of all values divided by 60
HashMap<Integer, List<Integer>> mp = new HashMap<Integer, List<Integer>>();
for(int i = 0; i<input.length; i++){
List<Integer> a = new ArrayList<Integer>();
int rem = Integer.parseInt(input[i]) % 60;
if(mp.containsKey(rem))
a = mp.get(rem);
a.add(Integer.parseInt(input[i]));
mp.put( rem, a);
}
int result = 0;
if(mp.containsKey(0))
result += p.comb(mp.get(0).size()) ;
if(mp.containsKey(30))
result += p.comb(mp.get(30).size()) ;
for(int i=1; i<30; i++){
if(mp.containsKey(i) && mp.containsKey(60-i))
result += mp.get(i).size() * mp.get(60-i).size();
}
System.out.println(result);
}
}
|
package com.example.practice.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.practice.model.Author;
import com.example.practice.repository.AuthorRepository;
public class AuthorServiceImple implements AuthorService {
}
|
package kr.or.ddit.task.service;
import java.util.List;
import java.util.Map;
import kr.or.ddit.successboard.dao.ISuccessBoardDao;
import kr.or.ddit.task.dao.ITaskDao;
import kr.or.ddit.vo.JoinVO;
import kr.or.ddit.vo.ProjectVO;
import kr.or.ddit.vo.SuccessBoardCommentVO;
import kr.or.ddit.vo.SuccessBoardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TaskServiceImpl implements ITaskService {
@Autowired
private ITaskDao dao;
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> selectTaskList(Map<String, String> params)
throws Exception {
return dao.selectTaskList(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectAverage(Map<String, String> params)
throws Exception {
return dao.selectAverage(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectPersonAverage(Map<String, String> params)
throws Exception {
return dao.selectPersonAverage(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public String insertTask(Map<String, String> params) throws Exception {
return dao.insertTask(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateTask(Map<String, String> params) throws Exception {
return dao.updateTask(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteTask(Map<String, String> params) throws Exception {
return dao.deleteTask(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectTaskInfo(Map<String, String> params)
throws Exception {
return dao.selectTaskInfo(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> checkPosition(Map<String, String> params)
throws Exception {
return dao.checkPosition(params);
}
}
|
package com.esum.comp.kftp;
import com.esum.common.exception.XTrusException;
public class KFtpException extends XTrusException {
public KFtpException(String code, String location, String message, Throwable cause) {
super(code, location, message, cause);
}
public KFtpException(String location, String message, Throwable cause) {
super(location, message, cause);
}
public KFtpException(String code, String location, String message) {
super(code, location, message);
}
}
|
package com.aaa.house.service;
import com.aaa.house.dao.DMaintainMapping;
import com.aaa.house.entity.Maintain;
import com.aaa.house.utils.CusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @ClassName DMaintainServiceImpl
* @Author 龚志博
* @Date 2019/7/27 10:37
* @Version 1.0
*/
@Service
public class DMaintainServiceImpl implements DMaintainService{
@Autowired
private DMaintainMapping maintainMapping;
@Override
public int queryPageCount(Map map) {
return maintainMapping.queryPageCount(map);
}
@Override
public List<Map> queryStatic(Map map) {
return maintainMapping.queryStatic(map);
}
/**
* 数量
* @param map
* @return
*/
@Override
public int queryPageCount1(Map map) {
return maintainMapping.queryPageCount1(map);
}
/**
* 修改审核
* @param map
* @return
*/
@Override
public int upAudit(Map map) {
String ma_staff = CusUtil.getStaff().getStaff_num();
map.put("ma_staff",ma_staff);
return maintainMapping.upAudit(map);
}
@Override
public List<Map> queryCode1() {
return maintainMapping.queryCode1();
}
@Override
public List<Map> queryCode() {
return maintainMapping.queryCode();
}
@Override
public int upMaintain(Map map) {
String ma_staff = CusUtil.getStaff().getStaff_num();
map.put("ma_staff",ma_staff);
return maintainMapping.upMaintain(map);
}
@Override
public List<Map> queryAudit(Map map) {
return maintainMapping.queryAudit(map);
}
@Override
public int updateAu(Maintain maintain) {
return maintainMapping.updateAu(maintain);
}
@Override
public int updateMa(Maintain maintain) {
return maintainMapping.updateMa(maintain);
}
}
|
package patterns.behavioral.mediator;
/**
* 中介者模式:集中相关对象之间复杂的沟通和控制方式。
*/
public class Client
{
public static void main(String[] args)
{
AlarmColleague alarmColleague = new AlarmColleague();
CoffeePotColleague coffeePotColleague = new CoffeePotColleague();
Mediator mediator = new ConcreteMediator(alarmColleague, coffeePotColleague);
alarmColleague.onEvent(mediator);
}
}
|
package aplicattion;
import java.util.Locale;
import java.util.Scanner;
import entities.Carro;
public class Program {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
Carro carro = new Carro();
System.out.println("Digite os dados do carro");
System.out.print("nome: ");
carro.nome = sc.nextLine();
System.out.print("marca: ");
carro.marca = sc.nextLine();
System.out.print("cor: ");
carro.cor = sc.nextLine();
System.out.print("ano: ");
carro.ano = sc.nextInt();
System.out.println(carro);
}
}
|
package cuc.edu.cn.hynnsapp02.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import android.R.string;
public class HttpUtility {
private static int retryCount = 5;
private static final int OK = 200;// OK: Success!
private static final int NOT_MODIFIED = 304;
private static final int BAD_REQUEST = 400;
private static final int NOT_AUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int NOT_ACCEPTABLE = 406;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int NETWORK_DISABLED = 601;
public static int downloadSize = 0;
/**
* Post请求
*
* @param postParams
* @param connectionUrl
* @param connectTimeout
* @return
* @throws Exception
*/
public static String doPost(List<NameValuePair> postParams, String connectionUrl, int connectTimeout) throws Exception {
int retriedCount = 0;
// Response response = null;
downloadSize = 0;
HttpURLConnection connection = null;
int responseCode = -1;
for (retriedCount = 0; retriedCount < retryCount; retriedCount++) {
OutputStream os = null;
//1 创建HttpURLConnection
connection = (HttpURLConnection) new URL(connectionUrl).openConnection();
if (connectTimeout != 0) {
connection.setConnectTimeout(connectTimeout);
}
//2 设置HttpURLConnection参数
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
String postParam = "";
if (postParams != null) {
//POST请求参数的设置
postParam = encodeParameters(postParams);
}
byte[] bytes = postParam.getBytes("UTF-8");
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
//3 URLConnection建立连接
os = connection.getOutputStream();
//4 HttpURLConnection发送请求
os.write(bytes);
os.flush();
os.close();
responseCode = connection.getResponseCode();
if (responseCode == OK ) {
break;
}
}
if(responseCode != OK){
return null;
}
String responseAsString = null;
BufferedReader bufferedReader;
//5 HttpURLConneciton获取响应
InputStream stream = connection.getInputStream();
if (null == stream) {
return null;
}
bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line;
while (null != (line = bufferedReader.readLine())) {
buffer.append(line).append("\n");
}
responseAsString = buffer.toString();
stream.close();
connection.disconnect();
return responseAsString;
}
/**
* Get请求
*
* @param getParams
* @param connectionUrl
* @param connectTimeout
* @return
*/
public static String doGet(List<NameValuePair> getParams, String connectionUrl, int connectTimeout) throws Exception {
HttpURLConnection connection = null;
int retriedCount = 0;
int responseCode = -1;
for (retriedCount = 0; retriedCount < retryCount; retriedCount++) {
//1 创建HttpURLConnection
if (getParams != null) {
////Get请求参数的设置
connection = (HttpURLConnection) new URL(connectionUrl + "?" + encodeParameters(getParams))
.openConnection();
} else {
connection = (HttpURLConnection) new URL(connectionUrl).openConnection();
}
if (connectTimeout != 0) {
connection.setConnectTimeout(connectTimeout);
}
responseCode = connection.getResponseCode();
if (responseCode == OK ) {
break;
}
}
if(responseCode != OK){
return null;
}
String responseAsString = null;
BufferedReader bufferedReader;
//5 HttpURLConneciton获取响应
InputStream stream = connection.getInputStream();
if (null == stream) {
return null;
}
bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line;
while (null != (line = bufferedReader.readLine())) {
buffer.append(line).append("\n");
}
responseAsString = buffer.toString();
stream.close();
connection.disconnect();
return responseAsString;
}
private static String encodeParameters(List<NameValuePair> postParams) throws Exception {
StringBuffer buffer = new StringBuffer();
if (postParams != null) {
for (int i = 0; i < postParams.size(); i++) {
if (i != 0) {
buffer.append("&");
}
buffer.append(URLEncoder.encode(postParams.get(i).getName(), "UTF-8")).append("=")
.append(URLEncoder.encode(postParams.get(i).getValue().toString(), "UTF-8"));
}
}
return buffer.toString();
}
}
|
package com.example.thang.moviehype;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.List;
public class BookmarkRecyclerAdapter extends RecyclerView.Adapter<BookmarkRecyclerAdapter.ViewHolder> {
public List<UserBookmark> bookmarkList;
public Context context;
private FirebaseFirestore firebaseFirestore;
public BookmarkRecyclerAdapter(List<UserBookmark> bookmarkList) {
this.bookmarkList = bookmarkList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bookmark, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String movie = bookmarkList.get(position).getMovie();
String movieImageDownloadUri = bookmarkList.get(position).getMovieImage();
holder.setMovieImage(movieImageDownloadUri);
holder.setMovieTitle(movie);
}
@Override
public int getItemCount() {
return bookmarkList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView movieTitle;
private ImageView movieImage;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setMovieTitle(String title) {
movieTitle = mView.findViewById(R.id.bookmarkMovieTitle);
movieTitle.setText(title);
}
public void setMovieImage(String downloadUri) {
RequestOptions placeholder = new RequestOptions();
placeholder.placeholder(R.drawable.default_placeholder);
movieImage = mView.findViewById(R.id.bookmarkMovieImage);
Glide.with(context).setDefaultRequestOptions(placeholder).load(downloadUri).into(movieImage);
}
}
}
|
package com.moran.proj.shared;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class ApplicationListener extends ContextLoaderListener
{
public void contextInitialized(ServletContextEvent sce)
{
System.out.println("/==========================Web容器已开启==========================/");
}
public void contextDestroyed(ServletContextEvent sce)
{
System.out.println("/==========================Web容器已关闭==========================/");
}
}
|
package Utilities;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import pojos.Item;
public class ProductsSiglington {
private static Map<Item, String> list = new HashMap<>();
private static ProductsSiglington products;
private ProductsSiglington()
{
listAll();
}
public static ProductsSiglington getProducts()
{
if (products == null)
{
products = new ProductsSiglington();
}
return products;
}
public Map<Item, String> getList()
{
return list;
}
private void listAll()
{
list.clear();
Connection con = connection();
if (con == null)
{
System.out.println("cannot connect to database");
return;
}
PreparedStatement ps = null;
ResultSet rs = null;
String sqlStr = "SELECT * FROM inventory";
try
{
ps = con.prepareStatement(sqlStr);
rs = ps.executeQuery();
while (rs.next())
{
Item temp = new Item(rs.getInt(1), rs.getString(2), rs.getString(3));
String link = temp.getName().toLowerCase().replace(' ', '_');
link += ".xhtml";
list.put(temp, link);
}
} catch (Exception ex)
{
ex.printStackTrace();
} finally
{
try
{
con.close();
if (ps != null)
{
ps.close();
}
} catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}
private static Connection connection() //throws InstantiationException, IllegalAccessException
{
String databaseName = "website";
String userName = "root";
String password = "";
String URL2 = "com.mysql.jdbc.Driver";
Connection con = null;
try
{// Load Sun's jdbc driver
Class.forName(URL2).newInstance();
System.out.println("JDBC Driver loaded!");
}
catch (Exception e) // driver not found
{
System.err.println("Unable to load database driver");
System.err.println("Details : " + e);
return null;
}
String ip = "localhost"; //internet connection
String url = "jdbc:mysql://" + ip + ":3308/" + databaseName + "?characterEncoding=latin1";
try
{
con = DriverManager.getConnection(url, userName, password);
con.setReadOnly(false);
}
catch (Exception e)
{
System.err.println(e.toString());
return null;
}
System.out.println("connection successfull");
return con;
}
}
|
package com.java.practice.pattern;
import java.util.Stack;
public class StringOccurance {
public static void main(String[] args) {
System.out.println(countOccurence("aBBccccaaAAAddeeEE"));
}
private static String countOccurence(String target) {
if (target == null) {
return null;
}
Stack<Character> stack = new Stack();
StringBuilder sb = new StringBuilder();
for (Character ch : target.toCharArray()) {
if (stack.isEmpty() || stack.peek() == ch) {
stack.push(ch);
}
if (!stack.isEmpty() && stack.peek() != ch) {
int count = 0;
char top = stack.peek();
while (!stack.isEmpty()) {
stack.pop();
count++;
}
sb.append(top).append(count);
stack.push(ch);
}
}
return sb.toString();
}
}
|
package com.everysports.domain;
import lombok.Data;
@Data
public class SearchTeacherVO {
private Long teacher_ID;
private String teacher_Name;
private Long class_SumNum;
private String uploadPath;
private String fileName;
}
|
//Encapsulation
package java_learning;
class Student1
{
int RollNo;
String name;
//Getters and Setters
public void setRollNo(int r)
{
RollNo=r;
}
public int getRollNo()
{
return RollNo;
}
public void setname(String n)
{
name=n;
}
public String getname()
{
return name;
}
}
public class EncapsulatonDemo {
public static void main(String args[])
{
Student1 s1= new Student1();
s1.setRollNo(5);
s1.setname("teja");
System.out.println("Roll Number is:"+ s1.getRollNo());
System.out.println("Name is "+ s1.getname());
}
}
|
package ethan.mobilecount;
import java.util.Date;
/**
* @since 2013-11-2
* @author ethan
*/
public class OrderStrategyHolder<T> {
//有效的套餐
private T strategy ;
//订购的日期
private Date effectDate; //3==>4
public T order(Date orderedDate,T newStrategy){
T oldStrategy = null;
if(effectDate != null && effectDate.before(orderedDate)){
oldStrategy = strategy;
}
//无论如何,新套餐都要存起来的
effectDate=orderedDate;
strategy = newStrategy;
return oldStrategy;
}
public T getValid(Date computeDate){
//计算月在有效套餐月后或等于有效套餐月,都是可用的
if(effectDate != null && !effectDate.before(computeDate)){
return strategy;
}
return null;
}
}
|
package com.gxtc.huchuan.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import com.gxtc.commlibrary.utils.WindowUtil;
import com.gxtc.huchuan.R;
import io.rong.imageloader.core.display.RoundedBitmapDisplayer.RoundedDrawable;
/**
* Created by sjr on 2017/3/3.
* 显示未读信息小红点
*/
public class DotViewBitmapUtil {
//背景半径
private static final int BACKGROUND_RADIUS = 12;
public static Bitmap getDotNumViewBitmap(Context context, Bitmap icon, String num) {
//获取屏幕大小
DisplayMetrics dm = context.getResources().getDisplayMetrics();
float baseDensity = 2.3f;
float factor = dm.density / baseDensity;
//初始化画布
int iconSize = (int) context.getResources().
getDimension(R.dimen.px110dp);
Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(numIcon);
//背景Paint
Paint iconPaint = new Paint();
//抗锯齿
iconPaint.setAntiAlias(true);
//对图片进行剪裁,设置为null就会显示整个图片
Rect src = new Rect(0, 0, icon.getWidth() , icon.getHeight());
//图片在Canvas画布中显示的区域,大于src则把src的裁截区放大,小于src则把src的裁截区缩小
Rect dst = new Rect(0, 0, iconSize, iconSize);
canvas.drawBitmap(icon, src, dst, iconPaint);
if (TextUtils.isEmpty(num)) {
num = "0";
}
if (Integer.valueOf(num) > 99) {
num = "99+";
}
//文字Paint
Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
numPaint.setColor(Color.WHITE);
numPaint.setTextSize(60f * factor);
numPaint.setTypeface(Typeface.DEFAULT);
int textWidth = (int) numPaint.measureText(num, 0, num.length());
int backgroundHeight = (int) (2 * 32 * factor);
int backgroundWidth = textWidth > backgroundHeight ? (int) (textWidth + 20 * factor)
: backgroundHeight;
//保存状态
canvas.save();
//画背景
ShapeDrawable drawable = getBackground(context);
drawable.setIntrinsicHeight(backgroundHeight );
drawable.setIntrinsicWidth(backgroundWidth);
drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
canvas.translate(iconSize - backgroundWidth , 0);
drawable.draw(canvas);
//重置状态
canvas.restore();
canvas.drawText(num, (float) (iconSize - (backgroundWidth + textWidth) / 2),
52 * factor, numPaint);
return numIcon;
}
/**
* 获取圆形背景
*
* @param context
* @return
*/
private static ShapeDrawable getBackground(Context context) {
int radius = WindowUtil.dip2px(context, BACKGROUND_RADIUS);
float[] other = new float[]{radius, radius, radius, radius,
radius, radius, radius, radius};
RoundRectShape rrs = new RoundRectShape(other, null, null);
ShapeDrawable drawable = new ShapeDrawable(rrs);
drawable.getPaint().setColor(Color.RED);
return drawable;
}
}
|
package ua.siemens.dbtool.serializers.Job;
import com.google.gson.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.siemens.dbtool.model.auxilary.JobType;
import ua.siemens.dbtool.service.JobService;
import java.lang.reflect.Type;
/**
* The class is custom serializer for {@link JobType}
*
* @author Perevoznyk Pavlo
* creation date 22 Jan 2018
* @version 1.0
*/
@Component
public class JobTypeSerializer implements JsonSerializer<JobType> {
private JobService jobService;
@Override
public JsonElement serialize(JobType jobType, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject jsonJobType = new JsonObject();
jsonJobType.addProperty("id", jobType.getId());
if (jobType.getWpTypeId() != null) {
jsonJobType.addProperty("wpTypeId", jobType.getWpTypeId());
}
if(jobType.getProjectId() != null){
jsonJobType.addProperty("projectId", jobType.getProjectId());
}
jsonJobType.addProperty("name", jobType.getName());
jsonJobType.addProperty("hasFactHours", jobType.hasFactHours());
jsonJobType.addProperty("hasVerificator", jobType.hasVerificator());
jsonJobType.addProperty("type", jobType.getClass().getSimpleName());
jsonJobType.addProperty("editable", !jobService.isJobTypeUsed(jobType));
return jsonJobType;
}
@Autowired
public void setJobService(JobService jobService) {
this.jobService = jobService;
}
}
|
/**
*
*/
package fr.isae.mae.ss.sockets.treasures;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* MyClientSocket class
* @author Cedric Mayer, 2018
*/
public class ManualGameConsoleClient {
/**
* @param args
*/
public static void main(String[] args) {
final String hostName;
final int portNumber;
// helped by
// https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
if (args.length != 2) {
System.err.println("Usage: java " + ManualGameConsoleClient.class.getName() + " <host name> <port number>");
// System.exit(1);
hostName = "localhost";
portNumber = 8081;
} else {
hostName = args[0];
portNumber = Integer.parseInt(args[1]);
}
// connect and open streams
try (Socket clientSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
// ask for name
System.out.println("Write your name: ");
out.println(stdIn.readLine() + "-manual");
System.out.println("Wait a little for a map to start...");
// main loop
while (true) {
String serverReturned = in.readLine();
if (serverReturned == null) {
// server lost
break;
}
System.out.println(serverReturned);
if (serverReturned.startsWith("Found")) {
// treasure found. Next line is the good one
serverReturned = in.readLine();
if (serverReturned == null) {
// server lost
break;
}
System.out.println(serverReturned);
}
// maybe you could parse serverReturned to display the map in the console directly?
// read and send
String userInput = stdIn.readLine();
out.println(userInput);
}
System.out.println("End of communication with the server.");
// some common problems
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
}
|
package server.sport.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import server.sport.model.Sport;
import server.sport.service.SportService;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping ("/api/sports")
public class SportController {
@Autowired
SportService sportService;
//At this stage it is simply making sport name, and is not concerned with the teams that correspond with the sport
@PostMapping ()
public ResponseEntity <Sport> createSport (@RequestBody Sport sport) {
return sportService.createSport(sport);
}
@PutMapping (path="/{sport_id}", consumes="application/json")
public ResponseEntity <Sport> updateSport (@PathVariable ("sport_id") int sportId, @RequestBody Sport sport){
return sportService.updateSport(sportId, sport);
}
@GetMapping
public ResponseEntity<List<Sport>> getAllSports(){
return sportService.getAllSports();
}
}
|
package com.example.derrick.p03_classjournal;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class InfoActivity extends AppCompatActivity {
int requestCodeForAdd = 1;
ListView lv;
ArrayAdapter adapter;
ArrayList<DailyGrade> gradeArrList;
Button btnInfo, btnAdd, btnEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
Intent i = getIntent();
final String module_code = i.getStringExtra("module_code");
setTitle("Info for " + module_code);
lv = findViewById(R.id.lvInfo);
gradeArrList = new ArrayList<DailyGrade>();
gradeArrList.add(new DailyGrade(1,"A"));
gradeArrList.add(new DailyGrade(2,"A"));
gradeArrList.add(new DailyGrade(3,"A"));
adapter = new DailyGradeAdapter(this, R.layout.row_dailygrade, gradeArrList);
lv.setAdapter(adapter);
btnAdd = findViewById(R.id.btnAdd);
btnInfo = findViewById(R.id.btnInfo);
btnEmail = findViewById(R.id.btnEmail);
btnInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String web = getString(R.string.rp_web);
Intent rpIntent = new Intent(Intent.ACTION_VIEW);
rpIntent.setData(Uri.parse(web + module_code));
startActivity(rpIntent);
}
});
btnEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"andy_tao@rp.edu.sg"});
String statement = "Hi faci,\n\nI am Derrick\nPlease see my remarks so far, thank you!\n\n";
for (int i =0; i<gradeArrList.size();i++){
statement += "Week " + gradeArrList.get(i).getWeekValue() + ": DG: " + gradeArrList.get(i).getGrade() +"\n";
}
email.putExtra(Intent.EXTRA_TEXT, statement);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,"Choose an Email client : "));
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(InfoActivity.this, AddGradeActivity.class);
int newWeek = gradeArrList.size()+1;
i.putExtra("week", newWeek);
startActivityForResult(i,requestCodeForAdd);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
// Only handle when 2nd activity close normally
// and data contains something
if (resultCode == RESULT_OK){
if (data != null){
// Get data passed back from 2nd activity
String grade = data.getStringExtra("grade");
// If it is activity started by clicking
// Superman, create corresponding String
if (requestCode == requestCodeForAdd){
gradeArrList.add(new DailyGrade(gradeArrList.size()+1,grade));
adapter.notifyDataSetChanged();
}
}
}
}
}
|
package com.njit.card.servlet;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.njit.card.dao.AdminDAO;
import com.njit.card.dao.LoginDAO;
import com.njit.card.dao.StudentDAO;
import com.njit.card.dao.impl.AdminDAOImpl;
import com.njit.card.dao.impl.EducationDAOImpl;
import com.njit.card.dao.impl.LoginDAOImpl;
import com.njit.card.dao.impl.StudentDAOImpl;
import com.njit.card.entity.Book;
import com.njit.card.entity.BookRecord;
import com.njit.card.entity.Card;
import com.njit.card.entity.CostRecord;
import com.njit.card.entity.FoodItem;
import com.njit.card.entity.Login;
import com.njit.card.entity.Student;
public class ServletAction extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置服务器与页面数据交换的数据编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 获取session对象
HttpSession session = request.getSession();
// 获取请求路径并对其分割成为简单地命令请求
String uri = request.getRequestURI();
String action = uri.substring(uri.lastIndexOf("/"), uri
.lastIndexOf("."));
System.out.println(action);
if (action.equals("/login")) {
// 获取页面输入的用户编码
request.setCharacterEncoding("utf-8");
// 获取用户在登陆界面上输入的值 包括用户名和密码,角色选择
long id = Long.parseLong(request.getParameter("id"));
int type = Integer.parseInt(request.getParameter("type"));
String pwd = request.getParameter("mm");
// 连接数据库 查找这个编码对应的记录是否存在
LoginDAO dao = new LoginDAOImpl();
Login login = dao.findById(id);
// 如果数据库查出的角色和用户选择的角色不一样,返回到登陆错误界面
if (login == null || !(login.getType() == type)
|| !(login.getMm().equals(pwd))) {
session.setAttribute("login", login);
response.sendRedirect("../main/loginError.jsp");
} else {
session.setAttribute("login", login);
if (type == 1) {
response.sendRedirect("../student/student.jsp");
} else if (type == 2) {
response.sendRedirect("../admin/admin.jsp");
} else {
response.sendRedirect("../education/education.jsp");
}
}
} else if (action.equals("/listRegist")) {
Login login = (Login) session.getAttribute("login");
StudentDAOImpl daoImpl = new StudentDAOImpl();
Student student = null;
try {
student = daoImpl.findById(login.getId());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(student.getRuxueshijian());
request.setAttribute("student", student);
request.setAttribute("mm", login.getMm());
RequestDispatcher rd = request
.getRequestDispatcher("student/listStudent.jsp");
rd.forward(request, response);
} else if (action.equals("/listFoodItem")) {
StudentDAOImpl daoImpl = new StudentDAOImpl();
List<FoodItem> foodItems = new ArrayList<FoodItem>();
try {
foodItems = daoImpl.findFoodItems();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("foodItems", foodItems);
RequestDispatcher rd = request
.getRequestDispatcher("student/listFoodItems.jsp");
rd.forward(request, response);
} else if (action.equals("/foodBuy")) {
// 获取请求命令传过来的 食品编号
long foodid = Long.parseLong(request.getParameter("id"));
// 获取用户的id
Login login = (Login) session.getAttribute("login");
/**
* 获取数据库中的相关的数值 要购买先查看卡上的余额是否大于或者等于食品单价 这样就需要Card对象和FoodItem对象
*
* 比较如果满足条件:再增加到食品记录里面 不满足就给出提示
*/
StudentDAOImpl daoImpl = new StudentDAOImpl();
AdminDAOImpl adminDaoImpl = new AdminDAOImpl();
Card card = null;
FoodItem item = null;
try {
card = daoImpl.findByCardId(login.getId());
item = daoImpl.findByFoodItemId(foodid);
} catch (Exception e) {
e.printStackTrace();
}
if(card.getCardstate()) {
double balance = card.getBalance();
System.out.println(balance);
System.out.println(card.getBalance());
double danjia = item.getDanjia();
if (balance == danjia || balance > danjia) {
CostRecord record = new CostRecord();
record.setCardid(login.getId());
record.setFoodid(foodid);
card.setBalance(balance - danjia);
try {
adminDaoImpl.updateCard(card);
daoImpl.addCostRecord(record);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("student/buyFoodSuccess.jsp");
} else {
response.sendRedirect("student/buyFoodError.jsp");
}
}
else {
response.sendRedirect("education/cardStateError.jsp");
}
// 显示个人食堂的消费记录
} else if (action.equals("/listCostRecord")) {
Login login = (Login) session.getAttribute("login");
StudentDAOImpl daoImpl = new StudentDAOImpl();
List<FoodItem> foodItems = null;
List<CostRecord> records = null;
try {
foodItems = daoImpl.findFoodItemsById(login.getId());
for(FoodItem food : foodItems){
System.out.println("window"+food.getChuangkou());
System.out.println("Danjia"+food.getDanjia());
System.out.println("id"+food.getFoodid());
System.out.println("foodname"+food.getFoodname());
}
records = daoImpl.findCostRecordsById(login.getId());
System.out.println(foodItems);
System.out.println(records);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("foodItems",foodItems);
request.setAttribute("records",records);
RequestDispatcher rt = request.getRequestDispatcher("student/listCostRecords.jsp");
rt.forward(request,response);
} else if (action.equals("/listBook")) {
StudentDAOImpl daoImpl = new StudentDAOImpl();
List<Book> booklist = null;
try {
booklist = daoImpl.findBooks();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("booklist", booklist);
RequestDispatcher rd = request
.getRequestDispatcher("student/booklist.jsp");
rd.forward(request, response);
} else if (action.equals("/lend")) {
// 从请求地址取到参数值----bookid
long bookid = Long.parseLong(request.getParameter("id"));
// 根据bookid,找到这本书
// 将这本书借还状态置为借出,
StudentDAOImpl daoImpl = new StudentDAOImpl();
Book book = null;
try {
book = daoImpl.findBookById(bookid);
} catch (Exception e) {
e.printStackTrace();
}
// 判断这本书是否全部借出
if (book.getBookstate() <= 0) {
response.sendRedirect("student/lenderror.jsp");
} else {
// 获取登录的对象,并获取卡号
Login login = (Login) session.getAttribute("login");
System.out.println(login.getId());
long cardid = login.getId();
BookRecord bookRecord = new BookRecord();
bookRecord.setBookid(bookid);
bookRecord.setCardid(cardid);
//判断是否借过该书籍
boolean b=false;
try {
b = daoImpl.findBookById(cardid, bookid);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if(b) {
//借过将借过标识符传给前端页面
request.setAttribute("choice", 1);
}
else {
try {
//未借过将该图书加入图书借阅记录
daoImpl.addBookRecord(bookRecord);
} catch (Exception e1) {
e1.printStackTrace();
}
}
RequestDispatcher rd = request
.getRequestDispatcher("student/lendsuccess.jsp");
rd.forward(request, response);
}
} else if (action.equals("/listBookRecord")) {
Login login = (Login) session.getAttribute("login");
StudentDAOImpl daoImpl = new StudentDAOImpl();
List<Book> bookrecords = null;
try {
if(login.getType()==3) {
long id = Long.parseLong(request.getParameter("id"));
bookrecords = daoImpl.findBookRecordsById(id);
}else {
bookrecords = daoImpl.findBookRecordsById(login.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("bookrecords", bookrecords);
request.setAttribute("type", login.getType());
RequestDispatcher rd = request
.getRequestDispatcher("student/listbookrecord.jsp");
rd.forward(request, response);
} else if (action.equals("/giveBook")) {
long bookid = Long.parseLong(request.getParameter("id"));
Login login = (Login) session.getAttribute("login");
StudentDAOImpl daoImpl = new StudentDAOImpl();
try {
daoImpl.delBookRecordById(bookid);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("type", login.getType());
RequestDispatcher rd = request
.getRequestDispatcher("student/givesuccess.jsp");
rd.forward(request, response);
} else if (action.equals("/manageStudent")) {
AdminDAOImpl daoImpl = new AdminDAOImpl();
List<Student> students = null;
try {
students = daoImpl.findStudents();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("students", students);
Login login=(Login)session.getAttribute("login");
RequestDispatcher rd=null;
if(login.getType() == 3) {
rd = request.getRequestDispatcher("education/listStudents.jsp");
}else {
rd = request.getRequestDispatcher("admin/listStudents.jsp");
}
rd.forward(request, response);
} else if (action.equals("/Delstudnet")) {
long id = Long.parseLong(request.getParameter("id"));
AdminDAOImpl daoImpl = new AdminDAOImpl();
LoginDAOImpl loginImpl = new LoginDAOImpl();
try {
daoImpl.delStudentById(id);
daoImpl.delCardById(id);
loginImpl.delById(id);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("manageStudent.do");
} else if (action.equals("/loadStudnet")) {
request.setCharacterEncoding("utf-8");
long studentid = Long.parseLong(request.getParameter("id"));
StudentDAOImpl daoImpl = new StudentDAOImpl();
LoginDAOImpl login = new LoginDAOImpl();
Student student = daoImpl.findById(studentid);
Login mm = login.findById(studentid);
request.setAttribute("student", student);
request.setAttribute("mm", mm.getMm());
RequestDispatcher rd = request
.getRequestDispatcher("admin/loadStudent.jsp");
rd.forward(request, response);
} else if (action.equals("/updateStudent")) {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
long studentid = Long.parseLong(request.getParameter("studentid"));
String xingming = request.getParameter("xingming");
String xingbie = request.getParameter("xingbie");
int nianling = Integer.parseInt(request.getParameter("nianling"));
String banji = request.getParameter("banji");
String zhuanye = request.getParameter("zhuanye");
String xueyuan = request.getParameter("xueyuan");
String jiguan = request.getParameter("jiguan");
String zhuzhi = request.getParameter("zhuzhi");
String ruxueshijian = request.getParameter("ruxueshijian");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Student s = new Student();
s.setBanji(banji);
s.setJiguan(jiguan);
s.setNianling(nianling);
try {
s.setRuxueshijian(sdf.parse(ruxueshijian));
} catch (ParseException e1) {
e1.printStackTrace();
}
s.setStudentid(studentid);
s.setXingbie(xingbie);
s.setXingming(xingming);
s.setXuyuan(xueyuan);
s.setZhuanye(zhuanye);
s.setZhuzhi(zhuzhi);
AdminDAOImpl adminDAOImpl = new AdminDAOImpl();
try {
adminDAOImpl.updateStudent(s);
response.sendRedirect("manageStudent.do");
} catch (Exception e) {
e.printStackTrace();
}
LoginDAO dao = new LoginDAOImpl();
String newmm = request.getParameter("mm");
try {
dao.updataById(studentid, newmm);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} else if (action.equals("/addStudent")) {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
long studentid = Long.parseLong(request.getParameter("studentid"));
System.out.println(studentid);
StudentDAOImpl daoImpl = new StudentDAOImpl();
Student s = daoImpl.findById(studentid);
System.out.println(s);
if (s != null) {
response.sendRedirect("admin/addStudentError.jsp");
} else {
// 获取页面传过来数据
String xingming = request.getParameter("xingming");
String mm = request.getParameter("mm");
String xingbie = request.getParameter("xingbie");
int nianling = Integer.parseInt(request
.getParameter("nianling"));
String banji = request.getParameter("banji");
String zhuanye = request.getParameter("zhuanye");
String xueyuan = request.getParameter("xueyuan");
String jiguan = request.getParameter("jiguan");
String zhuzhi = request.getParameter("zhuzhi");
String ruxueshijian = request.getParameter("ruxueshijian");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 创建新的学生
s = new Student();
Login login = new Login(studentid, mm, 1);
Card card = new Card(studentid, "123", xingming, 0, true, studentid);
// 给学生的各个属性赋值
s.setStudentid(studentid);
s.setBanji(banji);
s.setJiguan(jiguan);
s.setNianling(nianling);
try {
s.setRuxueshijian(sdf.parse(ruxueshijian));
} catch (ParseException e1) {
e1.printStackTrace();
}
s.setXingbie(xingbie);
s.setXingming(xingming);
s.setXuyuan(xueyuan);
s.setZhuanye(zhuanye);
s.setZhuzhi(zhuzhi);
// 将学生信息插入数据库
AdminDAOImpl impl = new AdminDAOImpl();
LoginDAOImpl loginImp = new LoginDAOImpl();
try {
impl.addStudent(s);
impl.addCard(card);
loginImp.addLogin(login);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("manageStudent.do");
}
} else if (action.equals("/foodItemManage")) {
// 查找到所有的菜品
StudentDAO dao = new StudentDAOImpl();
List<FoodItem> foodItems = null;
try {
foodItems = dao.findFoodItems();
} catch (Exception e) {
e.printStackTrace();
}
if (foodItems.size() == 0) {
response.sendRedirect("admin/manageFoodItemError.jsp");
} else {
// 转发到食品管理页面
request.setAttribute("foodItems", foodItems);
RequestDispatcher rd = request
.getRequestDispatcher("admin/manageFoodItem.jsp");
rd.forward(request, response);
}
} else if (action.equals("/addFoodItem")) {
// 获取表单的数据
long foodid = Long.parseLong(request.getParameter("foodid"));
String foodname = request.getParameter("foodname");
double danjia = Double.parseDouble(request.getParameter("danjia"));
int chuangkou = Integer.parseInt(request.getParameter("chuangkou"));
// 判断是否存在
AdminDAO dao = new AdminDAOImpl();
FoodItem f = null;
try {
f = dao.findFoodItemById(foodid);
} catch (Exception e1) {
e1.printStackTrace();
}
if (f != null) {
response.sendRedirect("admin/addFoodItemError.jsp");
} else {
// 封装成为FoodItem对象
f = new FoodItem();
f.setChuangkou(chuangkou);
f.setDanjia(danjia);
f.setFoodid(foodid);
f.setFoodname(foodname);
// 保存数据
try {
dao.addFoodItem(f);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("foodItemManage.do");
}
} else if (action.equals("/delFoodItem")) {
long foodid = Long.parseLong(request.getParameter("id"));
// 依据食品编号删除这个对象
AdminDAO dao = new AdminDAOImpl();
try {
dao.delFoodItemById(foodid);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("foodItemManage.do");
} else if (action.equals("/loadFoodItem")) {
long foodid = Long.parseLong(request.getParameter("id"));
// 根据食品编号找到这条记录 并转发到页面
AdminDAO dao = new AdminDAOImpl();
FoodItem f = null;
try {
f = dao.findFoodItemById(foodid);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("f", f);
RequestDispatcher rd = request
.getRequestDispatcher("admin/loadFoodItem.jsp");
rd.forward(request, response);
} else if (action.equals("/updateFoodItem")) {
// 获取表单数据
long foodid = Long.parseLong(request.getParameter("foodid"));
String foodname = request.getParameter("foodname");
double danjia = Double.parseDouble(request.getParameter("danjia"));
int chuangkou = Integer.parseInt(request.getParameter("chuangkou"));
// 依据食品编号查找这个对象
AdminDAO dao = new AdminDAOImpl();
FoodItem f = null;
try {
f = dao.findFoodItemById(foodid);
} catch (Exception e) {
e.printStackTrace();
}
// 为FoodItem设置属性
f.setChuangkou(chuangkou);
f.setDanjia(danjia);
f.setFoodid(foodid);
f.setFoodname(foodname);
// 调用业务逻辑方法修改数据库中数据
try {
dao.updateFoodItem(f);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("foodItemManage.do");
} else if (action.equals("/bookManage")) {
// 查找到所有的图书
StudentDAO dao = new StudentDAOImpl();
List<Book> books = null;
try {
books = dao.findBooks();
} catch (Exception e) {
e.printStackTrace();
}
if (books.size() == 0) {
response.sendRedirect("admin/manageBookError.jsp");
} else {
// 转发到图书管理页面上
request.setAttribute("books", books);
RequestDispatcher rd = request
.getRequestDispatcher("admin/manageBook.jsp");
rd.forward(request, response);
}
} else if (action.equals("/addBook")) {
// 获取表单信息
long bookid = Long.parseLong(request.getParameter("bookid"));
String bookname = request.getParameter("bookname");
String chubanshe = request.getParameter("chubanshe");
String zuozhe = request.getParameter("zuozhe");
String qixian = request.getParameter("qixian");
Integer bookstate = Integer.parseInt(request.getParameter("bookstate"));
// 查询数据库看是否重复
Book b = null;
AdminDAO dao = new AdminDAOImpl();
try {
b = dao.findBookById(bookid);
System.out.println(b);
} catch (Exception e) {
e.printStackTrace();
}
if (b == null) {
// 封装成为Book对象
b = new Book();
b.setBookid(bookid);
b.setBookname(bookname);
b.setBookstate(bookstate);
b.setChubanshe(chubanshe);
b.setQixian(qixian);
b.setZuozhe(zuozhe);
// 掉用业务逻辑保存数据
try {
dao.addBook(b);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("bookManage.do");
} else {
response.sendRedirect("admin/addBookError.jsp");
}
} else if (action.equals("/delBook")) {
long bookid = Long.parseLong(request.getParameter("bookid"));
AdminDAOImpl daoImpl = new AdminDAOImpl();
try {
daoImpl.delBookById(bookid);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("bookManage.do");
} else if (action.equals("/loadBook")) {
long bookid = Long.parseLong(request.getParameter("id"));
// 根据图书编号找到这条记录
AdminDAO dao = new AdminDAOImpl();
Book b = null;
try {
b = dao.findBookById(bookid);
} catch (Exception e) {
e.printStackTrace();
}
// 转发到修改界面
request.setAttribute("b", b);
RequestDispatcher rd = request
.getRequestDispatcher("admin/loadBook.jsp");
rd.forward(request, response);
} else if (action.equals("/updateBook")) {
// 获取表单信息
long bookid = Long.parseLong(request.getParameter("bookid"));
String bookname = request.getParameter("bookname");
String chubanshe = request.getParameter("chubanshe");
String zuozhe = request.getParameter("zuozhe");
String qixian = request.getParameter("qixian");
Integer bookstate = Integer.parseInt(request.getParameter("bookstate"));
// 依据图书编号查询数据
Book b = null;
AdminDAO dao = new AdminDAOImpl();
try {
b = dao.findBookById(bookid);
} catch (Exception e) {
e.printStackTrace();
}
// 设置Book对象的属性值
b.setBookname(bookname);
b.setBookstate(bookstate);
b.setChubanshe(chubanshe);
b.setQixian(qixian);
b.setZuozhe(zuozhe);
// 掉用业务逻辑保存数据
try {
dao.updateBook(b);
} catch (Exception e1) {
e1.printStackTrace();
}
response.sendRedirect("bookManage.do");
} else if (action.equals("/listCards")) {
// 连接数据库 查找所有的一卡通记录
AdminDAOImpl daoImpl = new AdminDAOImpl();
List<Card> cards = null;
try {
cards = daoImpl.findCrads();
} catch (Exception e) {
e.printStackTrace();
}
// 将查到的记录转发到显示页面
if (cards.size() == 0) {
response.sendRedirect("admin/manageCardError.jsp");
} else {
request.setAttribute("cards", cards);
Login login=(Login)session.getAttribute("login");
RequestDispatcher rd=null;
if(login.getType() == 2){
rd = request.getRequestDispatcher("admin/listCards.jsp");
}else {
rd = request.getRequestDispatcher("education/listCards.jsp");
}
rd.forward(request, response);
}
} else if (action.equals("/addCard")) {
// 设置字符编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("text/html;charset=utf-8");
// 获取页面输入的卡号
long cardid = Long.parseLong(request.getParameter("cardid"));
StudentDAOImpl daoImpl = new StudentDAOImpl();
/**
* 判断这个卡号是否存在 存在,,不保存 不存在,再创建并封装成为card对象 并保存到数据库
*
*/
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(card);
if (card == null) {
// 获取页面传入的数值
String mm = request.getParameter("mm");
String username = request.getParameter("username");
double balance = Double.parseDouble(request
.getParameter("balance"));
boolean cardstate = Boolean.parseBoolean(request
.getParameter("cardstate"));
long studentid = Long.parseLong(request
.getParameter("studentid"));
// 封装为card对象
card = new Card();
card.setCardid(cardid);
card.setBalance(balance);
card.setCardstate(cardstate);
card.setMm(mm);
card.setStudentid(studentid);
card.setUsername(username);
// 保存到数据库
AdminDAOImpl impl = new AdminDAOImpl();
try {
impl.addCard(card);
response.sendRedirect("listCards.do");
} catch (Exception e) {
e.printStackTrace();
}
} else {
response.sendRedirect("admin/addCardError.jsp");
}
} else if (action.equals("/findCard")) {
long cardid = Long.parseLong(request.getParameter("cardid"));
StudentDAOImpl daoImpl = new StudentDAOImpl();
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
if (card == null) {
response.sendRedirect("admin/manageCardStateError.jsp");
} else {
request.setAttribute("card", card);
RequestDispatcher rd = request
.getRequestDispatcher("admin/manageCardState.jsp");
rd.forward(request, response);
}
} else if (action.equals("/stopCard")) {
long cardid = Long.parseLong(request.getParameter("cardid"));
StudentDAOImpl daoImpl = new StudentDAOImpl();
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
card.setCardstate(false);
AdminDAOImpl impl = new AdminDAOImpl();
try {
impl.updateCard(card);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("listCards.do");
} else if (action.equals("/useCard")) {
long cardid = Long.parseLong(request.getParameter("cardid"));
StudentDAOImpl daoImpl = new StudentDAOImpl();
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
card.setCardstate(true);
AdminDAOImpl impl = new AdminDAOImpl();
try {
impl.updateCard(card);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("listCards.do");
} else if (action.equals("/findFoodRecords")) {
long cardid = Long.parseLong(request.getParameter("cardid"));
// 检验输入的卡号是否正确
StudentDAOImpl daoImpl = new StudentDAOImpl();
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
if (card == null) {
response.sendRedirect("admin/cardIdError.jsp");
} else {
session.setAttribute("cardid", cardid);
List<FoodItem> foodItems = null;
List<CostRecord> records = null;
try {
foodItems = daoImpl.findFoodItemsById(cardid);
records = daoImpl.findCostRecordsById(cardid);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("foodItems", foodItems);
request.setAttribute("records", records);
RequestDispatcher rd = request
.getRequestDispatcher("education/manageFoodRecords.jsp");
rd.forward(request, response);
}
} else if (action.equals("/delFoodRecord")) {
long cardid = Long.parseLong(request.getParameter("cardid"));
long foodid = Long.parseLong(request.getParameter("foodid"));
EducationDAOImpl daoImpl = new EducationDAOImpl();
try {
daoImpl.delFoodRecordsById(cardid, foodid);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("findFoodRecords.do?cardid="
+ session.getAttribute("cardid"));
} else if (action.equals("/addValue")) {
// 获取输入的卡号和金额
long cardid = Long.parseLong(request.getParameter("cardid"));
double value = Double.parseDouble(request.getParameter("value"));
/**
* 调用数据处理逻辑 查看卡的状态是否为可用 可用充值 不可用转发到另一个页面提示
*/
StudentDAOImpl daoImpl = new StudentDAOImpl();
Card card = null;
try {
card = daoImpl.findByCardId(cardid);
} catch (Exception e) {
e.printStackTrace();
}
if (card.getCardstate()) {
AdminDAOImpl impl = new AdminDAOImpl();
card.setBalance(value + card.getBalance());
try {
impl.updateCard(card);
} catch (Exception e) {
e.printStackTrace();
}
// 将这张卡的信息和充值额转发到页面
request.setAttribute("card", card);
request.setAttribute("value", value);
RequestDispatcher rd = request
.getRequestDispatcher("education/listBalance.jsp");
rd.forward(request, response);
} else {
response.sendRedirect("education/cardStateError.jsp");
}
}
else if(action.equals("/repassword")) {
/*
* LoginDAO dao = new LoginDAOImpl(); long id =
* Long.parseLong(request.getParameter("id")); String newmm =
* request.getParameter("mm"); try { dao.updataById(id, newmm); } catch
* (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
* response.sendRedirect("main/login.jsp");
*/
LoginDAO dao = new LoginDAOImpl();
Login login=(Login)session.getAttribute("login");
String oldPassword =request.getParameter("oldPassword");
String newPassword =request.getParameter("newPassword");
if(login.getMm().equals(oldPassword)) {
try { dao.updataById(login.getId(), newPassword); }
catch (Exception e) { // TODO 自动生成的 catch 块
e.printStackTrace();
}
response.sendRedirect("../main/login.jsp");
}
else {
//System.out.println(login.getMm());
response.sendRedirect("../main/passwordError.jsp");
}
}else if (action.equals("/listStudent")) {
AdminDAOImpl daoImpl = new AdminDAOImpl();
List<Student> students = null;
try {
students = daoImpl.findStudents();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("students", students);
RequestDispatcher rd = request
.getRequestDispatcher("education/findbook.jsp");
rd.forward(request, response);
}else if(action.equals("/showclass")){
AdminDAOImpl daoImpl = new AdminDAOImpl();
Map map= new HashMap();
try {
map = daoImpl.showClass();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
request.setAttribute("className", map.get("className"));
request.setAttribute("num", map.get("num"));
RequestDispatcher rd = request
.getRequestDispatcher("admin/showClass.jsp");
rd.forward(request, response);
}
}
}
|
package com.vk.mp3sinc;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
/**
*
* @author picaro
*
*/
public class VkMp3Parser implements IVkMp3Parser{
//private Logger log = new Logger(this.getClass());
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
/**
* replace illegal characters in a filename with "_"
* illegal characters :
* : \ / * ? | < >
* @param name
* @return
*/
public static String sanitizeFilename(String name) {
if (name.length() > 240) name = name.substring(0,240) ;
name = name + ".mp3";
return name.replaceAll("[:\\\\/*?\"|<>]", "_");
}
/**
* Parse all mp3s from the page
*/
public Map<String,String> getAllMp3s(String mp3page) {
Hashtable<String,String> mp3s = new Hashtable<String,String>();
//lower case?
System.out.println("mp" );
int i = 0;
while(mp3page.indexOf("class=\"play_btn") > 0 && i++ < 1000){
int startCutPos = mp3page.indexOf("class=\"play_btn");
mp3page = mp3page.substring(startCutPos);
int indexmp = mp3page.indexOf(".mp3") + 4;
if (indexmp < 15) continue;
String mp3 = mp3page.substring(0,indexmp);
mp3 = mp3.substring(mp3.lastIndexOf("http://"));
mp3page = mp3page.substring(mp3page.indexOf("<div class=\"title_wrap"));
indexmp = mp3page.indexOf("</div>") + 6;
String mp3name = Jsoup.parse(mp3page.substring(0,indexmp)).text();
mp3page = mp3page.substring(indexmp);
mp3 = mp3 + "?/" + mp3name;
mp3s.put(mp3name,mp3);
System.out.println("mp3:" + mp3);
}
return mp3s;
}
}
|
package com.gsccs.sme.plat.rtable.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gsccs.sme.api.domain.report.Report;
import com.gsccs.sme.api.domain.report.ReportItem;
import com.gsccs.sme.plat.bass.BaseController;
import com.gsccs.sme.plat.bass.Datagrid;
import com.gsccs.sme.plat.bass.JsonMsg;
import com.gsccs.sme.plat.rtable.service.ReportService;
/**
* 报表控制类
*
* @author x.d zhang
*
*/
@Controller
@RequestMapping("/report")
public class ReportController extends BaseController {
@Autowired
private ReportService reportService;
@RequestMapping(method = RequestMethod.GET)
protected String reportList(HttpServletRequest req) {
return "rtable/report-list";
}
@RequestMapping(value = "/datagrid", method = RequestMethod.POST)
@ResponseBody
public Datagrid reportList(Report report,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "15") int rows,
@RequestParam(defaultValue = "") String orderstr,
HttpServletRequest request, ModelMap map) {
Datagrid grid = new Datagrid();
report.setSvgid(getCurrUser().getOrgid());
List<Report> list = reportService.find(report, orderstr, page, rows);
int count = reportService.count(report);
grid.setRows(list);
grid.setTotal(Long.valueOf(count));
return grid;
}
// 新增
@RequestMapping(value = "/form", method = RequestMethod.GET)
public String showCreateForm(Long id, Model model) {
Report report = null;
if (null != id) {
report = reportService.getReport(id);
}
model.addAttribute("report", report);
return "rtable/report-form";
}
// 附件形式上报
@RequestMapping(value = "/byattach", method = RequestMethod.GET)
public String reportByAttach(Long id, Model model) {
Report report = null;
if (null!= id) {
report = reportService.getReport(id);
}
model.addAttribute("report", report);
ReportItem reportItemT = null;
model.addAttribute("reportItemT", reportItemT);
return "rtable/report-form-byattach";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public JsonMsg create(@RequestBody Report report, Model model) {
JsonMsg msg = new JsonMsg();
if (null == report) {
msg.setSuccess(false);
msg.setMsg("报表新增失败!");
return msg;
}
try {
report.setSvgid(getCurrSvg().getId());
reportService.addReport(report);
msg.setSuccess(true);
msg.setMsg("添加成功!");
} catch (Exception e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("报表新增失败!");
}
return msg;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
public JsonMsg update(@RequestBody Report report, Model model) {
JsonMsg msg = new JsonMsg();
if (null == report) {
msg.setSuccess(false);
msg.setMsg("修改报表信息失败!");
return msg;
}
try {
reportService.update(report);
msg.setSuccess(true);
msg.setMsg("报表修改成功!");
} catch (Exception e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("报表修改失败!");
}
return msg;
}
// 查看报送情况
@RequestMapping(value = "/list", method = RequestMethod.GET)
protected String list(Long id, HttpServletRequest req, Model model,
ReportItem reportItem) {
Report report = reportService.getReport(id);
model.addAttribute("report", report);
reportItem.setReportid(id);
List<ReportItem> list = reportService.find(reportItem, "", 1, 15);
model.addAttribute("list", list);
return "rtable/reportitem-list";
}
// 删除
@RequestMapping(value = "/delete", method = RequestMethod.GET)
@ResponseBody
public JsonMsg del(Long id, HttpServletRequest request) {
JsonMsg msg = new JsonMsg();
if (null != id) {
reportService.delReport(id);
msg.setSuccess(true);
msg.setMsg("记录删除成功!");
} else {
msg.setSuccess(false);
msg.setMsg("记录删除失败!");
}
return msg;
}
// 附件删除
@RequestMapping(value = "/attach/delete", method = RequestMethod.POST)
@ResponseBody
public JsonMsg attachDelete(Long attachid) {
JsonMsg msg = new JsonMsg();
if (null == attachid) {
msg.setSuccess(false);
msg.setMsg("附件删除失败!");
return msg;
}
try {
List<Long> attachids = new ArrayList<>();
attachids.add(attachid);
reportService.delAttachs(attachids);
msg.setSuccess(true);
msg.setMsg("附件删除成功!");
} catch (Exception e) {
msg.setSuccess(false);
msg.setMsg("附件删除失败,未知原因!");
}
return msg;
}
}
|
/**
* MongoDB database migrations using MongoBee.
*/
package com.trails.uaa.config.dbmigrations;
|
package com.design.creational.prototype;
import java.util.ArrayList;
public class PrototypeTest {
public static void main(String[] args) {
Employees emp = new Employees(new ArrayList<String>());
emp.loadData();
System.out.println(emp.getEmpList());
Employees emp1 = (Employees) emp.clone();
emp1.getEmpList().remove(1);
System.out.println(emp1.getEmpList());
}
}
|
import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.function.Supplier;
interface Job {
int doJob (int a, int b);
}
class Op {
public static int add(int a, int b) {
return a + b;
}
public int mult(int a, int b) {
return a * b;
}
}
public class Test {
private static int p = 10;
private static int q = 20;
public static void main(String[] args) {
doMath(30, 40);
}
private static void doMath(int l, int m) {
int i1 = compute(new Job(){
@Override
public int doJob(int a, int b) {
return a + b;
}
}, l, m);
System.out.println(i1);
int i2 = compute((a, b) -> a + b, l, m);
System.out.println(i2);
int i3 = compute((a, b) -> a + b, p, q);
System.out.println(i3);
int i4 = compute((a, b) -> Op.add(a, b), l, m);
System.out.println(i4);
int i5 = compute(Op::add, l, m);
System.out.println(i5);
int j1 = compute((a, b) -> a * b, l, m);
System.out.println(j1);
Op operator = new Op();
int j2 = compute((a, b) -> operator.mult(a, b), l, m);
System.out.println(j2);
int j3 = compute(operator::mult, l, m);
System.out.println(j3);
int j4 = compute(new Op()::mult, l, m);
System.out.println(j4);
Supplier<ArrayList<Integer>> lambda1 = () -> new ArrayList<>();
Supplier<ArrayList<Integer>> mr1 = ArrayList::new;
Predicate<String> lambda2 = (s) -> s.startsWith(s);
Predicate<String> lambda3 = (s) -> s.startsWith("A");
Predicate<String> mr3 = String::isEmpty;
}
private static int compute(Job job, int x, int y) {
return job.doJob(x, y);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.