text stringlengths 10 2.72M |
|---|
package com.goldsand.collaboration.server_test.activity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import com.goldsand.collaboration.connection.SocketConnectThreadListener;
import com.goldsand.collaboration.server.Utils;
import com.goldsand.collaboration.server.connection.SocketServerService;
import com.goldsand.collaboration.server.connection.SocketServerService.MyBinder;
import com.goldsand.collaboration.server_test.R;
public class TestServerActivity extends Activity implements ServiceConnection, SocketConnectThreadListener {
private TextView showView;
private Button submitButton;
private EditText editText;
private SocketServerService serverService;
private ScrollView scrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_server_activity);
showView = (TextView) findViewById(R.id.showMessage);
submitButton = (Button) findViewById(R.id.submit);
submitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (serverService != null) {
serverService.sendDataToClient(editText.getText().toString());
}
}
});
scrollView = (ScrollView)findViewById(R.id.scroll_view);
editText = (EditText) findViewById(R.id.input);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = SocketServerService.createServerInIntent();
startService(intent);
bindService(intent, this, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(this);
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
showView.append((String) msg.obj + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
};
};
@Override
public void onNewMessageReceived(String threadName, String message) {
Message message2 = handler.obtainMessage();
message2.obj = message;
message2.sendToTarget();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serverService = ((MyBinder) service).getService();
serverService.addSocketServerMessageListener(this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onSocketConnectStateChange(boolean connected) {
}
@Override
public void onNewMessageReceived(String threadName, Object message) {
Message message2 = handler.obtainMessage();
message2.obj = message.toString();
message2.sendToTarget();
}
}
|
/*
* 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 Interfaces;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HP
*/
public class PanelListarUsuarios extends javax.swing.JPanel {
/**
* Creates new form PanelListarUsuarios
*/
public PanelListarUsuarios() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
btnBuscar = new javax.swing.JButton();
btnLimpiar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
TableUsuarios = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
labelTotalRegistros = new javax.swing.JLabel();
btnNuevo = new javax.swing.JButton();
btnModificar = new javax.swing.JButton();
btnEliminar = new javax.swing.JButton();
btnActualizar = new javax.swing.JButton();
txtBusqueda = new javax.swing.JTextField();
jLabel2.setText("Introduzca Usuario a Buscar");
btnBuscar.setText("Buscar");
btnLimpiar.setText("Limpiar");
TableUsuarios.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(TableUsuarios);
jLabel1.setFont(new java.awt.Font("Wide Latin", 1, 24)); // NOI18N
jLabel1.setText("GESTIONAR USUARIOS");
labelTotalRegistros.setText("TOTAL REGISTROS:");
btnNuevo.setText("Nuevo");
btnModificar.setText("Modificar");
btnEliminar.setText("Eliminar");
btnActualizar.setText("Actualizar");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelTotalRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnNuevo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnModificar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnEliminar)
.addGap(31, 31, 31)
.addComponent(btnActualizar)
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(btnBuscar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnLimpiar))))
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(jLabel1))))
.addContainerGap(30, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnNuevo)
.addComponent(btnModificar)
.addComponent(btnEliminar)
.addComponent(btnActualizar)
.addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnBuscar)
.addComponent(btnLimpiar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelTotalRegistros)
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable TableUsuarios;
private javax.swing.JButton btnActualizar;
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnEliminar;
private javax.swing.JButton btnLimpiar;
private javax.swing.JButton btnModificar;
private javax.swing.JButton btnNuevo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelTotalRegistros;
private javax.swing.JTextField txtBusqueda;
// End of variables declaration//GEN-END:variables
public void setDatos(DefaultTableModel modeloTabla, int total) {
TableUsuarios.setModel(modeloTabla);
labelTotalRegistros.setText("Total Registros: " + total);
}
public JTable getTableUsuarios() {
return TableUsuarios;
}
public JButton getBtnActualizar() {
return btnActualizar;
}
public JButton getBtnBuscar() {
return btnBuscar;
}
public JButton getBtnEliminar() {
return btnEliminar;
}
public JButton getBtnLimpiar() {
return btnLimpiar;
}
public JButton getBtnModificar() {
return btnModificar;
}
public JButton getBtnNuevo() {
return btnNuevo;
}
public JLabel getLabelTotalRegistros() {
return labelTotalRegistros;
}
public JTextField getTxtBusqueda() {
return txtBusqueda;
}
}
|
package lib.hyxen.gcm;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
/**
* Created by redjack on 15/6/29.
*/
public class HXGCMServiceHelper {
static final private String DB_NAME = "GCMServiceDB";
static final private String KEY_REGISTER_ID = "registerID";
static final public int REQUEST_CODE_RECOVER_PLAY_SERVICE = 1;
static final public int REQUEST_RESULT_CANCEL = 1;
//region = Checking Version =
static public void registerWithCheckingVersion(Activity activity, String senderID, HXGCMServiceListener listener)
{
if (!isGooglePlayServiceAvailable(activity, listener)) return;
register(activity, senderID, listener);
}
/**
* Result code will always return 1 -> cancel. Open it when this situation is solved.
*/
// static public void receivedMessageFromOnActivityResult(int requestCode, int resultCode, HXGCMServiceListener listener)
// {
// switch (requestCode)
// {
// case REQUEST_CODE_RECOVER_PLAY_SERVICE:
//
// if (resultCode != REQUEST_RESULT_OK) listener.userCancelUpdateService();
//
// break;
// default:
// }
// }
/**
* Will check Google Service is available or not, if not, will present alert.
*/
static public boolean isGooglePlayServiceAvailable(Activity activity, HXGCMServiceListener listener)
{
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int status = googleAPI.isGooglePlayServicesAvailable(activity);
if (status != ConnectionResult.SUCCESS)
{
if (googleAPI.isUserResolvableError(status)) /// Maybe go update.
{
showErrorDialog(activity, status, listener);
}
else {
if (listener != null) listener.isNotSupportGooglePlayService();
}
return false;
}
return true;
}
static private void showErrorDialog(Activity activity, int code, final HXGCMServiceListener listener)
{
GoogleApiAvailability.getInstance().getErrorDialog(activity, code, REQUEST_CODE_RECOVER_PLAY_SERVICE, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (listener != null) listener.userCancelUpdateAlert();
}
}).show();
}
//endregion
static public void register(Context context, String senderID, HXGCMServiceListener listener)
{
if (!hasPlayServices(context)) return;
String registerID = getRegisterID(context);
// Already register.
if (registerID != null)
{
listener.registerDone(registerID);
return;
}
registerGCMService(context, senderID, listener);
}
static public boolean hasPlayServices(Context context)
{
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS;
}
static private void registerGCMService(final Context context, final String senderID, final HXGCMServiceListener listener)
{
new Thread(new Runnable() {
@Override
public void run() {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String regid;
try {
regid = gcm.register(senderID);
saveRegisterID(context, regid);
if (listener != null) listener.registerDone(regid);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
static private void saveRegisterID(Context context, String registerID)
{
SharedPreferences db = context.getSharedPreferences(DB_NAME, 0);
db.edit()
.putString(KEY_REGISTER_ID, registerID)
.commit();
}
static private String getRegisterID(Context context)
{
return context.getSharedPreferences(DB_NAME, 0).getString(KEY_REGISTER_ID, null);
}
public interface HXGCMServiceListener
{
public void registerDone(String registerID);
public void isNotSupportGooglePlayService();
public void userCancelUpdateAlert();
/**
* Use when update result return from onActivityResult.
*/
// public void userCancelUpdateService();
}
}
|
/* Test 18:
*
* Questo test controlla la deallocazione dalla symbol table dei parametri
* formali.
*/
package packname;
class s1 {
void pippo(int a, int b, int c) {}
void pluto(int a, int b) {}
}
|
package br.com.moryta.myfirstapp.events;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import br.com.moryta.myfirstapp.BaseViewHolder;
import br.com.moryta.myfirstapp.CustomOnItemClickListener;
import br.com.moryta.myfirstapp.R;
import br.com.moryta.myfirstapp.model.Event;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by moryta on 23/08/2017.
*/
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventViewHolder> {
private List<Event> eventList;
private CustomOnItemClickListener itemClickListener;
public EventsAdapter(List<Event> eventList, CustomOnItemClickListener itemClickListener) {
this.eventList = eventList;
this.itemClickListener = itemClickListener;
}
@Override
public EventViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View eventLayout = layoutInflater.inflate(R.layout.row_event, parent, false);
return new EventViewHolder(eventLayout);
}
@Override
public void onBindViewHolder(EventViewHolder holder, final int position) {
Event event = this.eventList.get(position);
holder.configure(event);
}
@Override
public int getItemCount() {
return this.eventList.size();
}
public void update(List<Event> eventList) {
this.eventList = eventList;
notifyDataSetChanged();
}
/**
* View Holder
*/
public class EventViewHolder extends RecyclerView.ViewHolder
implements BaseViewHolder<Event>
, View.OnClickListener
, View.OnLongClickListener {
@BindView(R.id.tvEventTitle)
TextView tvEventTitle;
@BindView(R.id.tvEventDescription)
TextView tvEventDescription;
@BindView(R.id.tvEventPetName)
TextView tvEventPetName;
@BindView(R.id.tvEventDate)
TextView tvEventDate;
private Event event;
public EventViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
@Override
public void configure(Event model) {
this.event = model;
this.tvEventTitle.setText(this.event.getTitle());
this.tvEventDescription.setText(this.event.getDescription());
this.tvEventPetName.setText(this.event.getPet().getName());
this.tvEventDate.setText(this.event.getDate());
}
@Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(this.event.getId(), v);
}
}
@Override
public boolean onLongClick(View v) {
return false;
}
}
}
|
package com.example.pfweather.ui;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.example.pfweather.db.MyDBHelper;
import com.example.pfweather.gson.Weather;
import com.example.pfweather.util.DateUtil;
import com.example.pfweather.util.UpdateUtil;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AMapLocationListener {
private ImageView CityBtn, LocateBtn, UpdateBtn, ShareBtn, CalBtn,
weatherImg, todayImg, afterImg, lateImg, late1Img, late2Img,
late3Img;
private TextView cnameTv, uptimeTv, humidityTv, pm25Tv, pm25statusTv,
tmpTv, weatherTv, windTv, weekTv, comfTv, drsgTv, fluTv, sportTv,
uvTv, todayTv, afterTv, lateTv, late1Tv, late2Tv, late3Tv, time1Tv,
time2Tv, time3Tv;
Weather weather;
public String cname = "呼和浩特";
public AMapLocationClient mLocationClient = null;
public MyDBHelper citydb = new MyDBHelper(this);
public MyDBHelper memorydb = new MyDBHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.weathermain_activity);
initview();//初始化界面
Cursor cursor = citydb.select("city_table");
if (cursor.moveToLast()) {
cursor.moveToLast();
cname = cursor.getString(cursor.getColumnIndex("city_name"));
}
CalBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, CalendarActivity.class);
startActivity(intent);
}
});
LocateBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
initlocate();
new Thread(runnable).start();//新起一个线程下载更新
Toast t3 = Toast.makeText(MainActivity.this, "更新成功",Toast.LENGTH_LONG);
t3.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
t3.setMargin(0f, 0.6f);
t3.show();
}
});
CityBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, CityActivity.class);
startActivityForResult(intent, 0);
}
});
UpdateBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(runnable).start();
Toast t3 = Toast.makeText(MainActivity.this, "更新成功",Toast.LENGTH_SHORT);
t3.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
t3.setMargin(0f, 0.6f);
t3.show();
}
});
ShareBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "我在使用完美天气,欢迎你也来使用!!!");
shareIntent.setType("text/plain");
// 设置分享列表的标题,并且每次都显示分享列表
startActivity(Intent.createChooser(shareIntent, "分享到"));
}
});
new Thread(runnable).start();
}
public void initview(){
CityBtn = (ImageView) findViewById(R.id.title_city);
LocateBtn = (ImageView) findViewById(R.id.title_locate);
LocateBtn = (ImageView) findViewById(R.id.title_locate);
UpdateBtn = (ImageView) findViewById(R.id.title_update);
ShareBtn = (ImageView) findViewById(R.id.title_share);
CalBtn = (ImageView) findViewById(R.id.title_calendar);
cnameTv = (TextView) findViewById(R.id.todayinfo1_cityName);
uptimeTv = (TextView) findViewById(R.id.todayinfo1_updateTime);
humidityTv = (TextView) findViewById(R.id.todayinfo1_humidity);
pm25Tv = (TextView) findViewById(R.id.todayinfo1_pm25);
pm25statusTv = (TextView) findViewById(R.id.todayinfo1_pm25status);
tmpTv = (TextView) findViewById(R.id.todayinfo2_temperature);
weatherTv = (TextView) findViewById(R.id.todayinfo2_weatherState);
windTv = (TextView) findViewById(R.id.todayinfo2_wind);
weekTv = (TextView) findViewById(R.id.todayinfo2_week);
weatherImg = (ImageView) findViewById(R.id.todayinfo2_weatherStatusImg);
comfTv = (TextView) findViewById(R.id.todayinfo3_comf);
drsgTv = (TextView) findViewById(R.id.todayinfo3_drsg);
fluTv = (TextView) findViewById(R.id.todayinfo3_flu);
sportTv = (TextView) findViewById(R.id.todayinfo3_sport);
uvTv = (TextView) findViewById(R.id.todayinfo3_uv);
todayTv = (TextView) findViewById(R.id.todayinfo4_todayinf);
afterTv = (TextView) findViewById(R.id.todayinfo4_afterinf);
lateTv = (TextView) findViewById(R.id.todayinfo4_lateinf);
todayImg = (ImageView) findViewById(R.id.todayinfo4_todayimg);
afterImg = (ImageView) findViewById(R.id.todayinfo4_afterimg);
lateImg = (ImageView) findViewById(R.id.todayinfo4_lateimg);
late1Tv = (TextView) findViewById(R.id.todayinfo5_todayinf);
late2Tv = (TextView) findViewById(R.id.todayinfo5_afterinf);
late3Tv = (TextView) findViewById(R.id.todayinfo5_lateinf);
late1Img = (ImageView) findViewById(R.id.todayinfo5_todayimg);
late2Img = (ImageView) findViewById(R.id.todayinfo5_afterimg);
late3Img = (ImageView) findViewById(R.id.todayinfo5_lateimg);
time1Tv = (TextView) findViewById(R.id.todayinfo5_today);
time2Tv = (TextView) findViewById(R.id.todayinfo5_after);
time3Tv = (TextView) findViewById(R.id.todayinfo5_late);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
cname = data.getStringExtra("data2");
new Thread(runnable).start();
Toast t3 = Toast.makeText(MainActivity.this,"更新成功" + data.getStringExtra("data2"), Toast.LENGTH_LONG);
t3.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
t3.setMargin(0f, 0.6f);
t3.show();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
Weather w = (Weather) data.getSerializable("value");
//Log.i("mylog", "请求城市结果-->" + w.basic.cityName);
citydb.city_insert(cname);
updateView(w);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
Message msg = new Message();
Bundle data = new Bundle();
data.putSerializable("value", UpdateUtil.UpdateWeather(cname));
msg.setData(data);
handler.sendMessage(msg);
}
};
public void updateView(Weather weather) {
cnameTv.setText(weather.basic.cityName);
humidityTv.setText("湿度" + weather.now.hum + "%");
try {
pm25Tv.setText("当前指数" + weather.aqi.city.pm25);
pm25statusTv.setText("空气质量" + weather.aqi.city.qlty);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tmpTv.setText("当前温度" + weather.now.temperature + "°");
weatherTv.setText(weather.now.more.info);
uptimeTv.setText("发布于 " + weather.basic.update.loc);
windTv.setText(weather.now.wind.dir + " " + weather.now.wind.sc + "~"+ weather.now.wind.spd);
weekTv.setText("今天 " + DateUtil.getWeek(0, DateUtil.XING_QI));
comfTv.setText("" + weather.suggestion.comfort.info);
drsgTv.setText("" + weather.suggestion.clothes.info);
fluTv.setText("" + weather.suggestion.cold.info);
sportTv.setText("" + weather.suggestion.sport.info);
uvTv.setText("" + weather.suggestion.uv.info);
todayTv.setText(" " + weather.now.more.info + " "
+ weather.forecastList.get(0).temperature.min + "°~"
+ weather.forecastList.get(0).temperature.max + "°");
afterTv.setText(" " + weather.now.more.info + " "
+ weather.forecastList.get(1).temperature.min + "°~"
+ weather.forecastList.get(1).temperature.max + "°");
lateTv.setText(" " + weather.now.more.info + " "
+ weather.forecastList.get(1).temperature.min + "°~"
+ weather.forecastList.get(2).temperature.max + "°");
UpdateUtil.upweImg(weather.now.more.info, weatherImg);
UpdateUtil.upweImg(weather.now.more.info, todayImg);
UpdateUtil.upweImg(weather.now.more.info, afterImg);
UpdateUtil.upweImg(weather.now.more.info, lateImg);
try {
late1Tv.setText(weather.hourlyList.get(0).cond.txt + "~"
+ weather.hourlyList.get(0).tmp + "°");
late2Tv.setText(weather.hourlyList.get(1).cond.txt + "~"
+ weather.hourlyList.get(1).tmp + "°");
late3Tv.setText(weather.hourlyList.get(2).cond.txt + "~"
+ weather.hourlyList.get(2).tmp + "°");
String late1 = new String(weather.hourlyList.get(0).date);
String a[] = late1.split(" ");
time1Tv.setText(a[1]);
String late2 = new String(weather.hourlyList.get(1).date);
String b[] = late2.split(" ");
time2Tv.setText(b[1]);
String late3 = new String(weather.hourlyList.get(2).date);
String c[] = late3.split(" ");
time3Tv.setText(c[1]);
UpdateUtil.upweImg(weather.hourlyList.get(0).cond.txt, late1Img);
UpdateUtil.upweImg(weather.hourlyList.get(1).cond.txt, late2Img);
UpdateUtil.upweImg(weather.hourlyList.get(2).cond.txt, late3Img);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//初始化定位函数
public void initlocate() {
// 启动定位
mLocationClient = new AMapLocationClient(getApplicationContext());
mLocationClient.setLocationListener(this);
AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
// 设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
// 设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.setInterval(2000);
mLocationOption.setOnceLocation(true);
mLocationClient.setLocationOption(mLocationOption);
// 设置定位参数
mLocationClient.startLocation();
}
//定位回调函数,手动进行实现
@Override
public void onLocationChanged(AMapLocation location) {
cname = location.getCity();
new Thread(runnable).start();
Weather newweather = UpdateUtil.UpdateWeather(location.getCity());
updateView(newweather);
mLocationClient.stopLocation();
}
}
|
package kni.webstore.validator;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import kni.webstore.model.Category;
import kni.webstore.validators.CategoryValidator;
public class CategoryValidatorTest {
private Category category;
private CategoryValidator catValid;
private BindingResult errorLog;
@Before
public void setUp() throws Exception {
catValid = new CategoryValidator();
category = new Category("Category");
errorLog = new BindException(category, "Category");
}
@After
public void tearDown() throws Exception {
errorLog = new BindException(category, "Category");
}
@Test
public void testSupports() {
assertTrue(catValid.supports(category.getClass()));
assertFalse(catValid.supports(Random.class));
}
@Test
public void shouldHasTypeError() {
catValid.validate(new Random(), errorLog);
boolean typeErrorFound = hasError(errorLog.getAllErrors(), "type_error");
assertTrue(typeErrorFound);
}
@Test
public void shouldHasNullError() {
catValid.validate(null, errorLog);
assertTrue(hasError(errorLog.getAllErrors(), "null_error"));
}
@Test
public void shouldHasntTypeError() {
catValid.validate(category, errorLog);
boolean typeErrorFound = hasError(errorLog.getAllErrors(), "type_error");
assertFalse(typeErrorFound);
}
@Test
public void shouldHasExistError() {
Category pierwsza = new Category("Pierwsza");
errorLog = new BindException(pierwsza, "pierwsza");
catValid.validate(pierwsza, errorLog);
assertTrue(hasError(errorLog.getAllErrors(), "exists_error"));
}
@Test
public void shouldHasEmptyError() {
Category empty = new Category(" ");
errorLog = new BindException(empty, "empty");
catValid.validate(empty, errorLog);
assertTrue(hasError(errorLog.getAllErrors(), "empty_error"));
}
@Test
public void shouldToShort() {
Category oneLetter = new Category("s");
errorLog = new BindException(oneLetter, "oneLetter");
catValid.validate(oneLetter, errorLog);
assertTrue(hasError(errorLog.getAllErrors(), "size_error"));
}
@Test
public void shouldToLong() {
Category toLong = new Category();
errorLog = new BindException(toLong, "toLong");
String name = "";
for (int i = 0; i < 36; i++) {
name += "a";
}
assertTrue(name.length() == 36);
toLong.setName(name);
catValid.validate(toLong, errorLog);
}
@Test
public void shouldHasDigitError() {
Category digits = new Category("1234");
errorLog = new BindException(digits, "digits");
catValid.validate(digits, errorLog);
assertTrue(hasError(errorLog.getAllErrors(), "only_digits_error"));
}
@Test
public void shouldNotHasDigitError() {
Category notDigits = new Category("1234m");
errorLog = new BindException(notDigits, "digits");
catValid.validate(notDigits, errorLog);
assertFalse(hasError(errorLog.getAllErrors(), "only_digits_error"));
}
private boolean hasError(List<ObjectError> errors, String code) {
for (ObjectError error : errors) {
if (error.getCode().equals(code))
return true;
}
return false;
}
}
|
// ChatLoginPanel.java
//
// Last modified 1/30/2000 by Alan Frindell
// Last modified : Priyank Patel <pkpatel@cs.stanford.edu>
//
// GUI class for the login panel.
//
// You should not have to modify this class.
package Chat;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class ChatLoginPanel extends JPanel {
JTextField _loginNameField;
JPasswordField _passwordField;
JTextField _portToListenField;
JTextField _portToConnectField;
JTextField _asPortField;
JTextField _tgsPortField;
JTextField _keyStoreNameField;
JPasswordField _keyStorePasswordField;
JLabel _errorLabel;
JButton _connectButton;
JButton _switchButton;
ChatClient _client;
public ChatLoginPanel(ChatClient client) {
_client = client;
try {
componentInit();
} catch (Exception e) {
System.out.println("ChatLoginPanel error: " + e.getMessage());
e.printStackTrace();
}
}
void componentInit() throws Exception {
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridBag);
addLabel(gridBag, "Welcome to High Security Chat", SwingConstants.CENTER,
1, 0, 2, 1);
addLabel(gridBag, "Username: ", SwingConstants.LEFT, 1, 1, 1, 1);
addLabel(gridBag, "Password: ", SwingConstants.LEFT, 1, 2, 1, 1);
addLabel(gridBag, "KeyStore File Name: ", SwingConstants.LEFT, 1, 3, 1, 1);
addLabel(gridBag, "KeyStore Password: ", SwingConstants.LEFT, 1, 4, 1, 1);
addLabel(gridBag, "Port to Listen: ", SwingConstants.LEFT, 1, 5, 1, 1);
addLabel(gridBag, "Port to Connect: ", SwingConstants.LEFT, 1, 6, 1, 1);
addLabel(gridBag, "AS Port: ", SwingConstants.LEFT, 1, 7, 1, 1);
addLabel(gridBag, "TGS Port: ", SwingConstants.LEFT, 1, 8, 1, 1);
_loginNameField = new JTextField();
addField(gridBag, _loginNameField, 2, 1, 1, 1);
_passwordField = new JPasswordField();
_passwordField.setEchoChar('*');
addField(gridBag, _passwordField, 2, 2, 1, 1);
_keyStoreNameField = new JTextField();
addField(gridBag, _keyStoreNameField, 2, 3, 1, 1);
_keyStorePasswordField = new JPasswordField();
_keyStorePasswordField.setEchoChar('*');
addField(gridBag, _keyStorePasswordField, 2, 4, 1, 1);
_portToListenField = new JTextField();
addField(gridBag, _portToListenField, 2, 5, 1, 1);
_portToConnectField = new JTextField();
addField(gridBag, _portToConnectField, 2, 6, 1, 1);
_asPortField = new JTextField();
addField(gridBag, _asPortField, 2, 7, 1, 1);
_tgsPortField = new JTextField();
addField(gridBag, _tgsPortField, 2, 8, 1, 1);
_errorLabel = addLabel(gridBag, " ", SwingConstants.CENTER,
1, 9, 2, 1);
// just for testing purpose
_loginNameField.setText("clienta");
_passwordField.setText("passwordA");
_keyStoreNameField.setText("storeA.jceks");
_keyStorePasswordField.setText("passwordA");
_asPortField.setText("" + Constants.AS_PORT);
_tgsPortField.setText("" + Constants.TGS_PORT);
_portToListenField.setText("" + Constants.CLIENT1_PORT);
_portToConnectField.setText("" + Constants.CLIENT2_PORT);
_errorLabel.setForeground(Color.red);
_connectButton = new JButton("Connect");
_switchButton = new JButton( "Switch Values");
c.gridx = 1;
c.gridy = 10;
c.gridwidth = 2;
gridBag.setConstraints(_connectButton, c);
c.gridx = 2;
gridBag.setConstraints(_switchButton, c);
add(_connectButton);
add(_switchButton);
_connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
connect();
}
});
_switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_loginNameField.setText("clientb");
_passwordField.setText("passwordB");
_keyStoreNameField.setText("storeB.jceks");
_keyStorePasswordField.setText("passwordB");
_portToListenField.setText("" + Constants.CLIENT2_PORT);
_portToConnectField.setText("" + Constants.CLIENT1_PORT);
}
});
}
JLabel addLabel(GridBagLayout gridBag, String labelStr, int align,
int x, int y, int width, int height) {
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel(labelStr);
if (align == SwingConstants.LEFT) {
c.anchor = GridBagConstraints.WEST;
} else {
c.insets = new Insets(10, 0, 10, 0);
}
c.gridx = x;
c.gridy = y;
c.gridwidth = width;
c.gridheight = height;
gridBag.setConstraints(label, c);
add(label);
return label;
}
void addField(GridBagLayout gridBag, JTextField field, int x, int y,
int width, int height) {
GridBagConstraints c = new GridBagConstraints();
field.setPreferredSize(new Dimension(96,
field.getMinimumSize().height));
c.gridx = x;
c.gridy = y;
c.gridwidth = width;
c.gridheight = height;
gridBag.setConstraints(field, c);
add(field);
}
private void connect() {
int portToListen, portToConnect;
int asPort = Constants.AS_PORT;
int tgsPort = Constants.TGS_PORT;
String loginName = _loginNameField.getText();
char[] password = _passwordField.getPassword();
String keyStoreName = _keyStoreNameField.getText();
char[] keyStorePassword = _keyStorePasswordField.getPassword();
if (loginName.equals("")
|| password.length == 0
|| keyStoreName.equals("")
|| keyStorePassword.length == 0
|| _portToListenField.getText().equals("")
|| _portToConnectField.getText().equals("")
|| _asPortField.getText().equals("")
|| _tgsPortField.getText().equals("")) {
_errorLabel.setText("Missing required field.");
return;
} else {
_errorLabel.setText(" ");
}
try {
portToListen = Integer.parseInt(_portToListenField.getText());
portToConnect = Integer.parseInt(_portToConnectField.getText());
asPort = Integer.parseInt(_asPortField.getText());
tgsPort = Integer.parseInt(_tgsPortField.getText());
} catch (NumberFormatException nfExp) {
_errorLabel.setText("Port field is not numeric.");
return;
}
System.out.println("We are connecting to ...");
switch (_client.connect(loginName,
password,
keyStoreName,
keyStorePassword,
portToListen,
portToConnect,
asPort,
tgsPort)) {
case ChatClient.SUCCESS:
// Nothing happens, this panel is now hidden
_errorLabel.setText(" ");
break;
case ChatClient.CONNECTION_REFUSED:
case ChatClient.BAD_HOST:
_errorLabel.setText("Connection Refused!");
break;
case ChatClient.ERROR:
_errorLabel.setText("ERROR! Stop That!");
break;
}
System.out.println("We finished connecting to ...");
}
}
|
package com.zhicai.byteera.activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.zhicai.byteera.R;
import com.zhicai.byteera.activity.community.topic.actiivty.CommunityFragment;
import com.zhicai.byteera.activity.myhome.activity.MyHomeFragment;
import com.zhicai.byteera.activity.product.ProductFragment;
import com.zhicai.byteera.activity.shouyi.LiCaiShouYiFragment;
public class MainFragmentFactory {
public static final int TAB_INCOME = 1;
public static final int TAB_PRODUCT = 2;
public static final int TAB_FIND = 3;
public static final int TAB_MINE = 4;
private Fragment mTab01;
private Fragment mTab02;
private Fragment mTab03;
private Fragment mTab04;
public Fragment createFragment(MainActivity mainActivity, int index) {
FragmentManager fm = mainActivity.getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
hideFragment(transaction);
switch (index) {
case TAB_INCOME:
if (mTab01 == null) {
mTab01 = new LiCaiShouYiFragment();
transaction.add(R.id.realcontent, mTab01);
} else transaction.show(mTab01);
break;
case TAB_PRODUCT:
if (mTab02 == null) {
mTab02 = new ProductFragment();
transaction.add(R.id.realcontent, mTab02);
} else transaction.show(mTab02);
break;
case TAB_FIND:
if (mTab03 == null) {
mTab03 = new CommunityFragment();
transaction.add(R.id.realcontent, mTab03);
} else transaction.show(mTab03);
break;
case TAB_MINE:
if (mTab04 == null) {
mTab04 = new MyHomeFragment();
transaction.add(R.id.realcontent, mTab04);
} else transaction.show(mTab04);
break;
}
transaction.commit();
return getFragment(index);
}
private void hideFragment(FragmentTransaction transaction) {
if (mTab01 != null) transaction.hide(mTab01);
if (mTab02 != null) transaction.hide(mTab02);
if (mTab03 != null) transaction.hide(mTab03);
if (mTab04 != null) transaction.hide(mTab04);
}
public void destroyFragment() {
if (mTab01 != null) mTab01 = null;
if (mTab02 != null) mTab02 = null;
if (mTab03 != null) mTab03 = null;
if (mTab04 != null) mTab04 = null;
}
public Fragment getFragment(int index) {
switch (index) {
case 0:
return mTab01;
case 1:
return mTab02;
case 2:
return mTab03;
case 3:
return mTab04;
}
return null;
}
public void attachFragment(Fragment fragment) {
if (fragment instanceof LiCaiShouYiFragment) mTab01 = fragment;
if (fragment instanceof ProductFragment) mTab02 = fragment;
if (fragment instanceof CommunityFragment) mTab03 = fragment;
if (fragment instanceof MyHomeFragment) mTab04 = fragment;
}
}
|
package com.needii.dashboard.model.form;
public class ShipperTypeCommissionForm {
private Integer idTypeCommisstion;
private String typeCommision;
private Integer typeHireCommission;//typeHireCommission : 1 --> combo, typeHireCommission: 2 --> day
private Integer typeCombo;//typeCombo : 1 --> 7 ngay, typeCombo : 2 --> 15 ngay, typeCombo : 3 : --> 30 ngay
private Long priceTypeCombo;
private Long priceTypeCombo7days;
private Long priceTypeCombo15days;
private Long priceTypeCombo30days;
private Long priceTypeDay;
private Integer ratingPerShipping;
private Long totalBonusShipping;
private Integer ratingPerTotalShipping;
private Integer ratingPerTotalShippingMinimun;
private Integer typeDate;//typeDate: 1 --> tuang, typeDate: 2 --> thang, typeDate: 3 --> nam
public ShipperTypeCommissionForm() {}
public Integer getIdTypeCommisstion() {
return idTypeCommisstion;
}
public void setIdTypeCommisstion(Integer idTypeCommisstion) {
this.idTypeCommisstion = idTypeCommisstion;
}
public String getTypeCommision() {
return typeCommision;
}
public void setTypeCommision(String typeCommision) {
this.typeCommision = typeCommision;
}
public Integer getTypeHireCommission() {
return typeHireCommission;
}
public void setTypeHireCommission(Integer typeHireCommission) {
this.typeHireCommission = typeHireCommission;
}
public Integer getTypeCombo() {
return typeCombo;
}
public void setTypeCombo(Integer typeCombo) {
this.typeCombo = typeCombo;
}
public Long getPriceTypeCombo() {
return priceTypeCombo;
}
public void setPriceTypeCombo(Long priceTypeCombo) {
this.priceTypeCombo = priceTypeCombo;
}
public Long getPriceTypeDay() {
return priceTypeDay;
}
public void setPriceTypeDay(Long priceTypeDay) {
this.priceTypeDay = priceTypeDay;
}
public Integer getRatingPerShipping() {
return ratingPerShipping;
}
public void setRatingPerShipping(Integer ratingPerShipping) {
this.ratingPerShipping = ratingPerShipping;
}
public Long getTotalBonusShipping() {
return totalBonusShipping;
}
public void setTotalBonusShipping(Long totalBonusShipping) {
this.totalBonusShipping = totalBonusShipping;
}
public Integer getRatingPerTotalShipping() {
return ratingPerTotalShipping;
}
public void setRatingPerTotalShipping(Integer ratingPerTotalShipping) {
this.ratingPerTotalShipping = ratingPerTotalShipping;
}
public Integer getRatingPerTotalShippingMinimun() {
return ratingPerTotalShippingMinimun;
}
public void setRatingPerTotalShippingMinimun(Integer ratingPerTotalShippingMinimun) {
this.ratingPerTotalShippingMinimun = ratingPerTotalShippingMinimun;
}
public Integer getTypeDate() {
return typeDate;
}
public void setTypeDate(Integer typeDate) {
this.typeDate = typeDate;
}
public Long getPriceTypeCombo7days() {
return priceTypeCombo7days;
}
public void setPriceTypeCombo7days(Long priceTypeCombo7days) {
this.priceTypeCombo7days = priceTypeCombo7days;
}
public Long getPriceTypeCombo15days() {
return priceTypeCombo15days;
}
public void setPriceTypeCombo15days(Long priceTypeCombo15days) {
this.priceTypeCombo15days = priceTypeCombo15days;
}
public Long getPriceTypeCombo30days() {
return priceTypeCombo30days;
}
public void setPriceTypeCombo30days(Long priceTypeCombo30days) {
this.priceTypeCombo30days = priceTypeCombo30days;
}
}
|
import java.util.ArrayList;
/**
* Created by Abuser on 1/13/2017.
*/
public class OnePlus {
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
if (a.size() > 1)
removeZeroes(a);
if (a.get(a.size() - 1) != 9) {
a.set(a.size() - 1, a.get(a.size() - 1) + 1);
return a;
}
int i = a.size() - 1;
while (i >= 0 && a.get(i) == 9) {
if (i == 0) {
a.set(i, 0);
a.add(0, 1);
} else {
if (a.get(i - 1) != 9) {
a.set(i, 0);
a.set(i - 1, a.get(i - 1) + 1);
break;
} else {
a.set(i, 0);
}
}
i--;
}
return a;
}
private void removeZeroes(ArrayList<Integer> a) {
while (a.get(0) == 0) {
a.remove(0);
}
}
}
|
package ru.otus.sua.L16.frontendservice;
public interface FrontendService {
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.io.StringWriter;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.SerializationHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.core.env.Environment;
/**
* Tests for {@link SerializationHintsWriter}.
*
* @author Sebastien Deleuze
*/
public class SerializationHintsWriterTests {
@Test
void shouldWriteEmptyHint() throws JSONException {
SerializationHints hints = new SerializationHints();
assertEquals("[]", hints);
}
@Test
void shouldWriteSingleHint() throws JSONException {
SerializationHints hints = new SerializationHints().registerType(TypeReference.of(String.class));
assertEquals("""
[
{ "name": "java.lang.String" }
]""", hints);
}
@Test
void shouldWriteMultipleHints() throws JSONException {
SerializationHints hints = new SerializationHints()
.registerType(TypeReference.of(String.class))
.registerType(TypeReference.of(Environment.class));
assertEquals("""
[
{ "name": "java.lang.String" },
{ "name": "org.springframework.core.env.Environment" }
]""", hints);
}
@Test
void shouldWriteSingleHintWithCondition() throws JSONException {
SerializationHints hints = new SerializationHints().registerType(TypeReference.of(String.class),
builder -> builder.onReachableType(TypeReference.of("org.example.Test")));
assertEquals("""
[
{ "condition": { "typeReachable": "org.example.Test" }, "name": "java.lang.String" }
]""", hints);
}
private void assertEquals(String expectedString, SerializationHints hints) throws JSONException {
StringWriter out = new StringWriter();
BasicJsonWriter writer = new BasicJsonWriter(out, "\t");
SerializationHintsWriter.INSTANCE.write(writer, hints);
JSONAssert.assertEquals(expectedString, out.toString(), JSONCompareMode.NON_EXTENSIBLE);
}
}
|
package jesk.desktopgui;
import jesk.system.MouseButton;
public interface IDraggable {
public boolean canDrag(MouseButton button, int x, int y);
public void dragBy(int x, int y);
} |
package liu.java.lang.Enums;
public class Test {
}
|
package com.birivarmi.birivarmiapp.data;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.birivarmi.birivarmiapp.model.Admin;
import com.birivarmi.birivarmiapp.model.Category;
import com.birivarmi.birivarmiapp.model.CategoryDescription;
import com.birivarmi.birivarmiapp.model.CategoryDescriptionPK;
import com.birivarmi.birivarmiapp.model.CategoryStats;
import com.birivarmi.birivarmiapp.model.CategoryStatsPK;
import com.birivarmi.birivarmiapp.repository.AdminRepository;
import com.birivarmi.birivarmiapp.repository.CategoryDescriptionRepository;
import com.birivarmi.birivarmiapp.repository.CategoryRepository;
import com.birivarmi.birivarmiapp.repository.CategoryStatsRepository;
import com.birivarmi.birivarmiapp.util.BirivarmiConstantsUtil;
@Controller
@RequestMapping("/birivarmi/birivarmiapp/data/v1/category")
public class CategoryDataController {
@Autowired
CategoryRepository categoryRepository;
@Autowired
AdminRepository adminRepository;
@Autowired
CategoryDescriptionRepository categoryDescriptionRepository;
@Autowired
CategoryStatsRepository categoryStatsRepository;
@RequestMapping(method= RequestMethod.POST)
public ResponseEntity<Category> createOrUpdateCategory(
@RequestParam(value="id", required = false) Long id,
@RequestParam(value="enabled", required = false) String enabled,
@RequestParam(value="expirationDays", required = false) Integer expirationDays,
@RequestParam(value="iconPath", required = false ) String iconPath,
@RequestParam(value="position", required = false) Integer position,
@RequestParam(value="priceEnabled", required = false) String priceEnabled,
@RequestParam(value="updaterId", required = true) Long updaterId,
@RequestParam(value="parentId", required = false) Long parentId,
@RequestParam(value="name", required = false) String name,
@RequestParam(value="description", required = false) String description,
@RequestParam(value="localCode", required = false) String localCode
){
Category category = null;
Date today = new Date();
//create new
if(id==null){
category = new Category();
category.setEnabled(BirivarmiConstantsUtil.CHAR_FALSE);
category.setExpirationDays(0);
category.setIconPath("");
if(parentId !=null){
Category parentCategory = categoryRepository.findOne(parentId);
category.setParentId(parentCategory);
}else{
category.setParentId(null);
}
category.setPosition(0);
category.setPriceEnabled(BirivarmiConstantsUtil.CHAR_FALSE);
category.setUpdateDate(today);
Admin admin = adminRepository.findOne(updaterId);
category.setUpdaterId(admin);
category.setUpdateStatus(BirivarmiConstantsUtil.UPDATE_STATUS_INSERT);
categoryRepository.save(category);
CategoryDescription categoryDescription = new CategoryDescription();
categoryDescription.setDescription(description);
categoryDescription.setName(name);
String slug = name.replaceAll(" ", "_").toLowerCase();
categoryDescription.setSlug(slug);
categoryDescription.setUpdateDate(today);
categoryDescription.setUpdaterId(admin);
categoryDescription.setUpdateStatus(BirivarmiConstantsUtil.UPDATE_STATUS_INSERT);
CategoryDescriptionPK categoryDescriptionPK = new CategoryDescriptionPK();
categoryDescriptionPK.setCategory(category);
categoryDescriptionPK.setLocalCode(localCode);
categoryDescription.setId(categoryDescriptionPK);
categoryDescriptionRepository.save(categoryDescription);
CategoryStats categoryStats = new CategoryStats();
CategoryStatsPK categoryStatsPK = new CategoryStatsPK();
categoryStatsPK.setCategory(category);
categoryStats.setId(categoryStatsPK);
categoryStats.setNumItems(new Long(0));
categoryStats.setUpdateDate(today);
categoryStats.setUpdaterId(admin);
categoryStats.setUpdateStatus(BirivarmiConstantsUtil.UPDATE_STATUS_INSERT);
categoryStatsRepository.save(categoryStats);
return new ResponseEntity<Category>(category, HttpStatus.OK);
}else{
//update
category = categoryRepository.findOne(id);
if(category!=null){
if(enabled!=null){
category.setEnabled(enabled.equalsIgnoreCase(String.valueOf(BirivarmiConstantsUtil.CHAR_TRUE))? BirivarmiConstantsUtil.CHAR_TRUE: BirivarmiConstantsUtil.CHAR_FALSE);
}else{
//do nothing.
}
if(expirationDays!=null){
category.setExpirationDays(expirationDays);
}else{
//do nothing.
}
if(iconPath!=null){
category.setIconPath(iconPath);
}else{
//do nothing.
}
if(position!=null){
category.setPosition(position);
}else{
//do nothing.
}
if(priceEnabled!=null){
category.setPriceEnabled(priceEnabled.equalsIgnoreCase(String.valueOf(BirivarmiConstantsUtil.CHAR_TRUE))? BirivarmiConstantsUtil.CHAR_TRUE: BirivarmiConstantsUtil.CHAR_FALSE);
}else{
//do nothing.
}
Admin admin = adminRepository.findOne(updaterId);
category.setUpdaterId(admin);
if(parentId !=null){
Category parentCategory = categoryRepository.findOne(parentId);
category.setParentId(parentCategory);
}else{
//do nothing.
}
category.setUpdateDate(today);
category.setUpdateStatus(BirivarmiConstantsUtil.UPDATE_STATUS_UPDATE);
categoryRepository.save(category);
if(localCode!=null && name!=null){
CategoryDescriptionPK categoryDescriptionPK = new CategoryDescriptionPK();
categoryDescriptionPK.setCategory(category);
categoryDescriptionPK.setLocalCode(localCode);
CategoryDescription categoryDescription = categoryDescriptionRepository.findOne(categoryDescriptionPK);
if(categoryDescription!=null){
categoryDescription.setName(name);
categoryDescription.setUpdateDate(today);
categoryDescription.setUpdaterId(admin);
categoryDescription.setUpdateStatus(BirivarmiConstantsUtil.UPDATE_STATUS_UPDATE);
categoryDescriptionRepository.save(categoryDescription);
}else{
//do nothing.
}
}else{
//do nothing.
}
return new ResponseEntity<Category>(category, HttpStatus.OK);
}else{
return new ResponseEntity<Category>(category, HttpStatus.BAD_REQUEST);
}
}
}
}
|
package com.nitnelave.CreeperHeal.block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
/**
* Skull implementation of CreeperBlock, to store and replace the orientation,
* the owner, etc...
*
* @author nitnelave
*
*/
class CreeperHead extends CreeperBlock
{
/*
* Constructor.
*/
protected CreeperHead(BlockState blockState)
{
super(blockState);
}
/*
* (non-Javadoc)
*
* @see com.nitnelave.CreeperHeal.block.CreeperBlock#update(boolean)
*/
@Override
public void update()
{
super.update();
Skull skull = (Skull) blockState;
Skull newSkull = ((Skull) blockState.getBlock().getState());
newSkull.setRotation(skull.getRotation());
newSkull.setSkullType(skull.getSkullType());
if (skull.hasOwner())
newSkull.setOwner(skull.getOwner());
newSkull.update(true);
}
}
|
package com.yujing.rxjava.activity;
import android.annotation.SuppressLint;
import com.blankj.rxbus.RxBus;
import com.blankj.rxbus.RxBus.Callback;
import com.yujing.rxjava.R;
import com.yujing.rxjava.contract.RxBusMessage;
import com.yujing.rxjava.databinding.ActivityMain2Binding;
import com.yujing.utils.YShow;
import io.reactivex.android.schedulers.AndroidSchedulers;
@SuppressLint("CheckResult")
public class MainActivity2 extends BaseActivity<ActivityMain2Binding> {
final String TAG = "MainActivity2";
@Override
protected Integer getContentLayoutId() {
return R.layout.activity_main2;
}
@SuppressLint("CheckResult")
@Override
protected void initData() {
RxBus.getDefault().subscribeSticky(this, "newActivity", AndroidSchedulers.mainThread(), newActivity);
binding.btn1.setOnClickListener(v -> bt1());
binding.btn2.setOnClickListener(v -> bt2());
binding.btn3.setOnClickListener(v -> bt3());
binding.btn4.setOnClickListener(v -> bt4());
binding.btn1.setText("1.封装RxBus");
binding.btn2.setText("2.发送doublue");
binding.btn3.setText("3.延迟关闭");
binding.btn4.setText("4.");
}
private void bt1() {
RxBus.getDefault().post(new RxBusMessage<>("1", "发送文字"));
}
private void bt2() {
RxBus.getDefault().post(new RxBusMessage<>("2", 123.45));
}
private void bt3() {
YShow.show(this, "延迟5秒关闭");
delayedShowFinish(5);
}
private void bt4() {
}
Callback newActivity = new Callback<String>() {
@Override
public void onEvent(String s) {
binding.textView.setText(binding.textView.getText() + s);
}
};
@Override
public void onFail(String errorMsg) {
}
@Override
public void onSuccess(String type, Object object) {
}
@Override
public void onEvent(RxBusMessage<?> rxBusMessage) {
switch (rxBusMessage.getType()) {
case "1":
binding.textView.setText((String) rxBusMessage.getObject());
break;
case "2":
binding.textView.setText(rxBusMessage.getObject().toString());
break;
}
}
} |
package com.tsystems.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
/**
* Order consist of set of Products, Address, Client and If Client chose self
* delivery method, then Order's Address is null.
*
* @author Ivan Kornelyuk
*
*/
@Entity
@Table(name = "ORDERS")
public class Order {
@Id
@GeneratedValue()
@Column(unique = true, nullable = false)
private Long id;
@OneToOne
@NotNull(message = "This field can't be null!")
private Person client;
@OneToOne
private Address address;
@Enumerated(EnumType.STRING)
@NotNull(message = "This field must be filled in!")
@Column(name = "payment_method")
private PaymentMethod payMethod;
@Enumerated(EnumType.STRING)
@NotNull(message = "This field must be filled in!")
@Column(name = "delivery_method")
private DeliveryMethod deliveryMethod;
@NotNull(message = "This field must be filled in!")
@ManyToMany
@JoinTable(name = "ORDER_PRODUCT", joinColumns = { @JoinColumn(name = "order_id") }, inverseJoinColumns = {
@JoinColumn(name = "product_id") })
private List<Product> products;
private Boolean paid;
@Enumerated(EnumType.STRING)
@NotNull(message = "This field must be filled in!")
@Column(name = "order_status")
private OrderStatus status;
@NotNull(message = "This field can't be null!")
@DecimalMin(value = "0.01", message = "Order's cost can't be equal 0!")
private Float cost;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "creation_date")
private java.util.Date creationDate;
@Temporal(TemporalType.DATE)
@Column(name = "delivery_date")
private java.util.Date deliveryDate;
@Column(name = "comment_for_order")
private String commentsForOrder;
public Person getClient() {
return client;
}
public Address getAddress() {
return address;
}
public PaymentMethod getPayMethod() {
return payMethod;
}
public DeliveryMethod getDeliveryMethod() {
return deliveryMethod;
}
public List<Product> getProducts() {
return products;
}
public Boolean getPaid() {
return paid;
}
public OrderStatus getStatus() {
return status;
}
public void setClient(Person client) {
this.client = client;
}
public void setAddress(Address address) {
this.address = address;
}
public void setPayMethod(PaymentMethod payMethod) {
this.payMethod = payMethod;
}
public void setDeliveryMethod(DeliveryMethod deliveryMethod) {
this.deliveryMethod = deliveryMethod;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public void setPaid(Boolean paid) {
this.paid = paid;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
public Long getId() {
return id;
}
@Deprecated
public void setId(Long id) {
this.id = id;
}
public Float getCost() {
return cost;
}
public void setCost(Float cost) {
this.cost = cost;
}
}
|
/*
* 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 controller;
import controller.exceptions.IllegalOrphanException;
import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.Customer;
import model.Orderdetail;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.Orders;
/**
*
* @author aimmy
*/
public class OrdersJpaController implements Serializable {
public OrdersJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Orders orders) throws PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Customer customerid = orders.getCustomerid();
if (customerid != null) {
customerid = em.getReference(customerid.getClass(), customerid.getCustomerid());
orders.setCustomerid(customerid);
}
Orderdetail orderdetail = orders.getOrderdetail();
if (orderdetail != null) {
orderdetail = em.getReference(orderdetail.getClass(), orderdetail.getOrderid());
orders.setOrderdetail(orderdetail);
}
em.persist(orders);
if (customerid != null) {
customerid.getOrdersList().add(orders);
customerid = em.merge(customerid);
}
if (orderdetail != null) {
Orders oldOrdersOfOrderdetail = orderdetail.getOrders();
if (oldOrdersOfOrderdetail != null) {
oldOrdersOfOrderdetail.setOrderdetail(null);
oldOrdersOfOrderdetail = em.merge(oldOrdersOfOrderdetail);
}
orderdetail.setOrders(orders);
orderdetail = em.merge(orderdetail);
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findOrders(orders.getOrderid()) != null) {
throw new PreexistingEntityException("Orders " + orders + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Orders orders) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Orders persistentOrders = em.find(Orders.class, orders.getOrderid());
Customer customeridOld = persistentOrders.getCustomerid();
Customer customeridNew = orders.getCustomerid();
Orderdetail orderdetailOld = persistentOrders.getOrderdetail();
Orderdetail orderdetailNew = orders.getOrderdetail();
List<String> illegalOrphanMessages = null;
if (orderdetailOld != null && !orderdetailOld.equals(orderdetailNew)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Orderdetail " + orderdetailOld + " since its orders field is not nullable.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
if (customeridNew != null) {
customeridNew = em.getReference(customeridNew.getClass(), customeridNew.getCustomerid());
orders.setCustomerid(customeridNew);
}
if (orderdetailNew != null) {
orderdetailNew = em.getReference(orderdetailNew.getClass(), orderdetailNew.getOrderid());
orders.setOrderdetail(orderdetailNew);
}
orders = em.merge(orders);
if (customeridOld != null && !customeridOld.equals(customeridNew)) {
customeridOld.getOrdersList().remove(orders);
customeridOld = em.merge(customeridOld);
}
if (customeridNew != null && !customeridNew.equals(customeridOld)) {
customeridNew.getOrdersList().add(orders);
customeridNew = em.merge(customeridNew);
}
if (orderdetailNew != null && !orderdetailNew.equals(orderdetailOld)) {
Orders oldOrdersOfOrderdetail = orderdetailNew.getOrders();
if (oldOrdersOfOrderdetail != null) {
oldOrdersOfOrderdetail.setOrderdetail(null);
oldOrdersOfOrderdetail = em.merge(oldOrdersOfOrderdetail);
}
orderdetailNew.setOrders(orders);
orderdetailNew = em.merge(orderdetailNew);
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
String id = orders.getOrderid();
if (findOrders(id) == null) {
throw new NonexistentEntityException("The orders with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Orders orders;
try {
orders = em.getReference(Orders.class, id);
orders.getOrderid();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The orders with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Orderdetail orderdetailOrphanCheck = orders.getOrderdetail();
if (orderdetailOrphanCheck != null) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Orders (" + orders + ") cannot be destroyed since the Orderdetail " + orderdetailOrphanCheck + " in its orderdetail field has a non-nullable orders field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
Customer customerid = orders.getCustomerid();
if (customerid != null) {
customerid.getOrdersList().remove(orders);
customerid = em.merge(customerid);
}
em.remove(orders);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Orders> findOrdersEntities() {
return findOrdersEntities(true, -1, -1);
}
public List<Orders> findOrdersEntities(int maxResults, int firstResult) {
return findOrdersEntities(false, maxResults, firstResult);
}
private List<Orders> findOrdersEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Orders.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Orders findOrders(String id) {
EntityManager em = getEntityManager();
try {
return em.find(Orders.class, id);
} finally {
em.close();
}
}
public int getOrdersCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Orders> rt = cq.from(Orders.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
|
package com.example.okta_cust_sign_in.base;
import android.app.Activity;
import android.content.Context;
import androidx.fragment.app.Fragment;
import com.example.okta_cust_sign_in.interfaces.AppLoadingView;
import com.example.okta_cust_sign_in.interfaces.AppMessageView;
import com.example.okta_cust_sign_in.interfaces.AppNavigation;
import com.example.okta_cust_sign_in.interfaces.AppNavigationProvider;
import com.example.okta_cust_sign_in.interfaces.IOktaAuthenticationClientProvider;
import com.example.okta_cust_sign_in.interfaces.IOktaClientProvider;
import com.okta.authn.sdk.client.AuthenticationClient;
import com.okta.sdk.client.Client;
import com.okta.sdk.client.ClientBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class BaseFragment extends Fragment {
private static String TAG = "BaseFragment";
private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
protected Future lastTask = null;
protected AuthenticationClient authenticationClient;
protected AppNavigation navigation;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AppLoadingView
&& context instanceof AppMessageView
&& context instanceof IOktaAuthenticationClientProvider){
authenticationClient = ((IOktaAuthenticationClientProvider)context).provideAuthenticationClient();
navigation = ((AppNavigationProvider)context).provideNavigation();
}
}
protected void showLoading() {
Activity activity = getActivity();
if((activity instanceof AppLoadingView)) {
((AppLoadingView) activity).show();
}
}
protected void hideLoading() {
Activity activity = getActivity();
if((activity instanceof AppLoadingView)) {
((AppLoadingView) activity).hide();
}
}
protected void showMessage(String message) {
Activity activity = getActivity();
if((activity instanceof AppMessageView)) {
((AppMessageView) activity).showMessage(message);
}
}
protected void submit(Runnable task) {
if(!executor.isShutdown()) {
lastTask = executor.submit(task);
}
}
protected void schedule(Runnable task, long delay, TimeUnit unit) {
if(!executor.isShutdown()) {
lastTask = executor.schedule(task, delay, unit);
}
}
private void unsubscribe() {
executor.shutdownNow();
}
protected void runOnUIThread(Runnable task) {
if(getActivity() != null) {
getActivity().runOnUiThread(task);
}
}
@Override
public void onDestroy() {
super.onDestroy();
unsubscribe();
}
}
|
public class AutomobileVenduta {
private String modello;
private int cilind;
private float prezzo;
private final int CILMAX = 5000;
private final int CILMIN = 500;
public void AutomobileVenduta(String modello, int cilind, float prezzo){
this.modello = modello;
if(cilind<=CILMAX && cilind>=CILMIN)
this.cilind=cilind;
else
this.cilind = CILMIN;
if (prezzo>=0){
this.prezzo = prezzo;
}else
this.prezzo = 0;
}
public int getCilind(){ return cilind;}
public float getPrezzo() {
return prezzo;
}
public String getModello(){return modello;}
public void setCilind(int cilind) {
if(cilind<=CILMAX && cilind>=CILMIN)
this.cilind=cilind;
else
this.cilind = CILMIN;
}
public void setPrezzo(float prezzo) {
if (prezzo>=0)
this.prezzo = prezzo;
else
this.prezzo = 0;
}
public void setModello(String modello) {
this.modello = modello;
}
public boolean isPiùCara(AutomobileVenduta a){
if(a.prezzo > prezzo){ //bisogna mettere un comando comparatore non il maggiore, cercalo sulle slide
}
}
@Override
public String toString() {
return modello + "-" + cilind + "€" + prezzo;
}
}
|
/*
* Arrays.sort()
*
* array transfered by a copy or reference?
*
*/
package Sort;
import java.util.Arrays;
/**
*
* @author YNZ
*/
public class ArraysSort {
public static void main(String[] args) {
int[] intArray = {20, 30, 40 ,65, 23, 12};
System.out.println(Arrays.toString(intArray));
Arrays.sort(intArray);
System.out.println(Arrays.toString(intArray));
}
}
|
package br.com.mixfiscal.prodspedxnfe.gui.job;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import br.com.mixfiscal.prodspedxnfe.gui.config.JobManagerConfig;
public class JobManager implements ServletContextListener {
private final Logger log = LogManager.getLogger(JobManager.class);
private final Map<String, Class<? extends Job>> mapJobs = new HashMap<String, Class<? extends Job>>();;
private final JobManagerConfig jobManagerConfig = JobManagerConfig.getInstance();
public JobManager() {
mapJobs.put(VaccumJob.NOME_JOB, VaccumJob.class);
mapJobs.put(AtualizadorInfosFiscaisCSVJob.NOME_JOB, AtualizadorInfosFiscaisCSVJob.class);
mapJobs.put(AtualizadorInfosFiscaisViewJob.NOME_JOB, AtualizadorInfosFiscaisViewJob.class);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
agendarJobs();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
try{
SchedulerFactoryQuartzJob
.getStdSchedulerFactory()
.shutdown();
log.info("Scheduler do Quartz finalizado.");
}catch(Exception ex){
log.error("Houve um erro ao tentar finalizar o Scheduler do Quartz.", ex);
}
}
private void agendarJobs() {
if(!jobManagerConfig.isJobsAtivos())
return;
log.info("INICIANDO AGENDAMENTO DOS JOBS DA APLICAÇÃO");
for (String nomeJob : mapJobs.keySet()) {
agendarJob(nomeJob);
}
log.info("FINALIZANDO O AGENDDAMENTO DOS JOBS DA APLICAÇÃO");
}
private void agendarJob(String nomeJob) {
try{
JobDetail job = newJob(mapJobs.get(nomeJob))
.withIdentity(nomeJob)
.build();
if (nomeJob.equals(VaccumJob.NOME_JOB)) {
job.getJobDataMap().put(VaccumJob.CAMINHO_VACCUM_EXEC_PROP, jobManagerConfig.getCaminhoExecutavelVacuum());
}
Trigger trigger = newTrigger()
.withIdentity(nomeJob + "_Trigger")
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule(jobManagerConfig.getPeriodicidade(nomeJob)))
.build();
SchedulerFactoryQuartzJob
.getStdSchedulerFactory()
.scheduleJob(job, trigger);
log.info(String.format("Job '%s' agendado com sucesso", nomeJob));
}catch(Exception ex){
log.error(String.format("Houve um erro ao tentar agendar o job '%s'", nomeJob), ex);
}
}
}
|
package duke;
public class Task {
public boolean isDone;
public String eventName;
public String eventType;
public Task(boolean done, String eventName, String eventType) {
this.isDone = done;
this.eventName = eventName;
this.eventType = eventType;
}
/**
* This function sets a task to be done
*/
public void setDone() {
this.isDone = true;
}
@Override
public String toString() {
if (this.isDone == true) {
return "[X] " + eventName;
} else {
return "[ ] " + eventName;
}
}
}
|
package com.yifenqian;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<ImageView> imageViews = new ArrayList<ImageView>();
imageViews.add((ImageView)findViewById(R.id.image1));
imageViews.add((ImageView)findViewById(R.id.image2));
imageViews.add((ImageView)findViewById(R.id.image3));
imageViews.add((ImageView)findViewById(R.id.image4));
imageViews.add((ImageView)findViewById(R.id.image5));
new MainLoadTask("http://yifenqian.fr/app/api/v1/info/", imageViews).execute();
}
// @Override
// public void onClick(View arg0) {
// Button b = (Button)findViewById(R.id.my_button);
// b.setClickable(false);
// new LongRunningGetIO().execute();
// }
} |
package com.mingyin.serviceB;
import com.mingyin.api.User;
import com.netflix.discovery.converters.Auto;
import feign.Param;
import hello.MyApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ServiceB")
public class ServiceBController {
@Autowired
private ServiceAClient serviceA;
@Autowired
private ServiceAApi serviceAApi;
@RequestMapping(value = "/sayHello/{id}", method = RequestMethod.GET)
public String greeting(@PathVariable("id") Long id,
@RequestParam("name") String name,
@RequestParam("age") Integer age) {
return serviceA.sayHello(id, name, age);
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String createUser(@RequestBody User user) {
return serviceA.createUser(user);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable("id") Long id, @RequestBody User user) {
return serviceA.updateUser(id, user);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable("id") Long id) {
return serviceA.deleteUser(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getById(@PathVariable("id") Long id) {
return serviceA.getById(id);
}
@RequestMapping(value = "/getname", method = RequestMethod.GET)
public String getname(@Param("name") String name) {
System.out.println("_________________________________________________");
System.out.println(name);
return serviceAApi.getName(name);
}
}
|
package com.nitharshanaan.android.movieindex;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by nitha on 11/28/2017.
*/
public class NetworkUtil {
public static final String QUERY_KEY = "api_key";
public static final String QUERY_SORT = "sort_by";
public NetworkUtil() {
}
public static URL buildUrl(String baseUrl, String api) {
Uri uri = Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(QUERY_KEY, api)
.build();
URL url = null;
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
public static String getJson(URL url) throws IOException {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
InputStream stream = connection.getInputStream();
Scanner scanner = new Scanner(stream);
scanner.useDelimiter("\\A");
boolean hasData = scanner.hasNext();
if (hasData) {
return scanner.next();
} else {
return null;
}
} catch (Exception e) {
Log.d("Error", e.toString());
return null;
} finally {
connection.disconnect();
}
}
public static ArrayList<Movie> parseJSON(String json) {
final String TITLE = "title";
final String LANGUAGE = "original_language";
final String RATING = "vote_average";
final String THUMBNAIL = "poster_path";
final String RESULTS = "results";
final String OVERVIEW = "overview";
final String RELEASE_DATE = "release_date";
final String BACKDROP = "backdrop_path";
final String BASE_IMAGE_URL = "https://image.tmdb.org/t/p/w500";
ArrayList<Movie> movies = new ArrayList<>();
try {
JSONObject jsonMovieMasterObject = new JSONObject(json);
JSONArray jsonMasterArray = jsonMovieMasterObject.getJSONArray(RESULTS);
int numberOfMoviesFetched = jsonMasterArray.length();
for (int i = 0; i < numberOfMoviesFetched; i++) {
JSONObject movieJSON = jsonMasterArray.getJSONObject(i);
Movie movie = new Movie(
movieJSON.getString(TITLE),
movieJSON.getString(LANGUAGE),
BASE_IMAGE_URL + movieJSON.getString(THUMBNAIL),
String.valueOf(movieJSON.getInt(RATING)),
movieJSON.getString(OVERVIEW),
movieJSON.getString(RELEASE_DATE),
BASE_IMAGE_URL + movieJSON.getString(BACKDROP)
);
movies.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
return movies;
}
}
|
package org.dbdoclet.test.option;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.dbdoclet.log.Logger;
import org.dbdoclet.service.ExecResult;
import org.dbdoclet.service.ExecServices;
import org.dbdoclet.service.FileServices;
public class UseAppendixTests extends OptionTestCase {
private static Log logger = LogFactory.getLog(UseAppendixTests.class.getName());
public UseAppendixTests(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(UseAppendixTests.class);
}
public void testUseAppendix1() {
try {
String sourceFileName = FileServices.appendFileName(sourcePath, "UseAppendix.java");
String destPath = FileServices.appendPath(tmpPath, "UseAppendix1");
String[] cmd = { "dbdoclet", "-d" , destPath, sourceFileName };
ExecResult result = ExecServices.exec(cmd);
logger.info(result.getOutput());
String fileName = FileServices.appendFileName(destPath, "Reference.xml");
String buffer = FileServices.readToString(fileName);
if (buffer.indexOf("<appendix>") != -1) {
fail("Appendices shouldn't be created!");
}
} catch (Exception oops) {
logger.fatal(getName() + " failed!", oops);
fail("Exception: " + oops.getClass().getName());
}
}
public void testUseAppendix2() {
try {
String sourceFileName = FileServices.appendFileName(sourcePath, "UseAppendix.java");
String destPath = FileServices.appendPath(tmpPath, getName());
String[] cmd = { "dbdoclet", "-d" , destPath, "--use-appendix", sourceFileName };
ExecResult result = ExecServices.exec(cmd);
logger.info(result.getOutput());
String fileName = FileServices.appendFileName(destPath, "Reference.xml");
String buffer = FileServices.readToString(fileName);
if (buffer.indexOf("<appendix>") == -1) {
fail("Appendices should be created!");
}
} catch (Exception oops) {
fail("Exception: " + oops.getClass().getName());
}
}
}
|
package demo.apps.maptracker.common;
import com.google.android.gms.maps.model.LatLng;
public class Segment {
public LatLng start;
public LatLng finish;
public double LengthInMeters;
public Segment(LatLng start, LatLng finish, double len) {
this.start = start;
this.finish = finish;
this.LengthInMeters = len;
}
} |
package aula_0330.lista3;
import java.util.ArrayList;
public class LabirintoMain {
public static void main(String[] args) {
ArrayList<Sala> salas = new ArrayList<Sala>();
Sala sala1 = new Santuario();
sala1 = new CamaraGas();
Sala sala2 = new CamaraGas();
Sala sala3 = new CamaraGas();
salas.add(sala1);
salas.add(sala2);
salas.add(sala3);
for(Sala sala : salas){
System.out.println(sala.visitaSala());
}
}
}
|
import java.util.*;
class ques1d21
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter String S : ");
String s=sc.nextLine();
Stack st=new Stack();
for(int i=0;i<s.length();i++)
st.push(s.charAt(i));
s="";
while(!st.empty())
s=s+st.pop();
System.out.println("OUTPUT : S = "+s);
}
}
|
package com.bluetooth.iss.iss.listeners;
/**
* Created by Ilja Kosynkin on 10.01.2016.
* Copyright
*/
public interface IDeviceChooser {
void wasDeviceChosen(boolean isDeviceChosen);
}
|
package com.zd.christopher.transaction;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.zd.christopher.bean.Entity;
import com.zd.christopher.dao.EntityDAO;
import com.zd.christopher.reflector.Reflector;
@Service
public class BaseTransaction<TEntity extends Entity> implements IBaseTransaction<TEntity>
{
@Resource
private EntityDAO<TEntity> entityDAO;
protected Class<TEntity> entityClass;
public Class<TEntity> getEntityClass()
{
return entityClass;
}
public void setEntityClass(Class<TEntity> entityClass)
{
this.entityClass = entityClass;
}
public void add(TEntity entity)
{
entityDAO.add(entity);
}
public void update(TEntity entity)
{
entityDAO.update(entity);
}
public void delete(TEntity entity)
{
entityDAO.setEntityClass((Class<TEntity>) entity.getClass());
Integer id = (Integer) Reflector.getFieldValue(entity, "id");
entityDAO.delete(id);
}
public TEntity find(TEntity entity)
{
entityDAO.setEntityClass((Class<TEntity>) entity.getClass());
Integer id = (Integer) Reflector.getFieldValue(entity, "id");
return entityDAO.find(id);
}
public List<TEntity> findAll()
{
entityDAO.setEntityClass(getEntityClass());
return entityDAO.findAll();
}
public Long countAll()
{
entityDAO.setEntityClass(getEntityClass());
return entityDAO.countAll();
}
public List<TEntity> findByIds(List<TEntity> entityList)
{
entityDAO.setEntityClass(getEntityClass());
List<Integer> idList = new ArrayList<Integer>();
for(TEntity entity : entityList)
idList.add((Integer) Reflector.getFieldValue(entity, "id"));
return entityDAO.findByIds((Integer[]) idList.toArray());
}
public List<TEntity> findByIdsByPage(List<TEntity> entityList, Integer count, Integer page)
{
entityDAO.setEntityClass(getEntityClass());
List<Integer> idList = new ArrayList<Integer>();
for(TEntity entity : entityList)
idList.add((Integer) Reflector.getFieldValue(entity, "id"));
return entityDAO.findByIdsByPage((Integer[]) idList.toArray(), count, page);
}
}
|
import java.io.*;
import java.util.*;
public class Osero{
public static void main(String[] args){
int r=10, l=10, p=0, flag=3;
Ban osero = new Ban();
System.out.println("---Osero game start!!---");
osero.initMap();
while(flag==3){
Scanner scan = new Scanner(System.in);
System.out.println("you have " + p);
while(r>7){
System.out.println("Where do you put on?(row)");
r = scan.nextInt();
}
while(l>7){
System.out.println("Where do you put on?(len)");
l = scan.nextInt();
}
osero.updateMap(r, l, p);
osero.printMap(p);
flag = osero.isGameFinish();
p = (p+1) % 2;
r = 10;
l = 10;
}
System.out.println("game finished");
}
}
|
package com.pan.al.array;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* 数组中重复的数字
* 在一个长度为n的数组里面的所有数字都在0~n-1的范围里,找出重复的数字
*
*/
public class Duplication {
/**
* 交换俩个数
* @param arr
* @param i
* @param j
*/
public void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* 数组下标与数字比较的方式
* 时间复杂度O(n),空间复杂度O(1)
* 解析
* 当扫描下标为i的数字时,首先比较这个数字m和i是否相等,
* 是:接着扫描下个数字
* 否:nums[i]与nums[m]比较,
* 等:找到重复的数字了;
* 否:交换,在继续重复上面的过程
* @param nums
* @return
*/
public boolean duplication(int[] nums,Integer temp){
if(nums==null||nums.length<=0)
{
return false;
}
for (int i=0;i<nums.length;++i)
{
if(nums[i]<0||nums[i]>nums.length-1)
{
return false;
}
while(nums[i]!=i)
{
if(nums[i]==nums[nums[i]])
{
temp=nums[i];
return true;
}
swap(nums,i,nums[i]);
}
}
return false;
}
/**
*
* 给定一个整数数组,判断是否存在重复元素。
*
* 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
*/
public static boolean containsDuplicate(int[] nums) {
for (int i = 1; i < nums.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (nums[i] > nums[j]) {
break;
} else if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
/**
* 此方法还没前面一个方法来的效率快,耗时短
* @param nums
* @return
*/
public static boolean containsDuplicate1(int[] nums) {
Map<Integer, Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
for(Integer key:map.keySet())
{
if(map.containsKey(nums[i]))
{
return true;
}
}
map.put(nums[i],i);
}
return false;
}
/**
* 在一个二维数组里,每一行都是按照从左到右递增的顺序排列,每一列都是从上到下递增排序,输入一个数,判断二维
* 数组中是否有这个数
* @param matrix
* @param rows 行
* @param columns 列
* @param number 数
* @return
*/
public boolean find(int[][] matrix,int rows,int columns,int number)
{
boolean found=false;
if(matrix==null)
{
found=false;
}
if(matrix!=null &&rows>0&&columns>0)
{
int row=0;
int column=columns-1;
while(row<rows&&column>=0)
{
if(matrix[row][column]==number)
{
found=true;
break;
}
else if(matrix[row][column]>number)
{
--column;
}else{
++row;
}
}
}
return found;
}
}
|
package com.yc.education.controller.customer;
import com.github.pagehelper.PageInfo;
import com.yc.education.controller.BaseController;
import com.yc.education.controller.account.AccountInputInvoiceController;
import com.yc.education.controller.account.AccountPayableController;
import com.yc.education.controller.account.AccountPrepaymentController;
import com.yc.education.controller.purchase.PurchaseInvoiceController;
import com.yc.education.model.basic.SupplierBasic;
import com.yc.education.service.basic.SupplierBasicService;
import com.yc.education.util.AppConst;
import com.yc.education.util.StageManager;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
/**
* @Description 供应商查询
* @Author BlueSky
* @Date 2019-01-29 16:03
*/
@Controller
public class SupplierMiniController extends BaseController implements Initializable {
@Autowired
private SupplierBasicService iSupplierBasicService;
@FXML VBox menu_first; // 第一页
@FXML VBox menu_prev; // 上一页
@FXML VBox menu_next; // 下一页
@FXML VBox menu_last; // 最后一页
@FXML CheckBox che_recently; //显示最近
@FXML CheckBox che_stop_compay; //显示暂停来往公司
@FXML TextField num; //最近多少笔
//查询更多供应商
@FXML private TableView tableView_supplier; //供应商查询
@FXML private TableColumn supid; //id
@FXML private TableColumn findsupplierid; //供应商编号
@FXML private TableColumn findsuppliername; //
@Override
public void initialize(URL location, ResourceBundle resources) {
setMenuValue(1);
}
/**
* @Description 查找
* @Author BlueSky
* @Date 16:04 2019/4/15
**/
@FXML
public void textQuery(){
setMenuValue(1);
}
/**
* 给翻页菜单赋值
* @param page
*/
private void setMenuValue(int page){
int rows = pageRows(che_recently,num);
int types = 0;
if(che_stop_compay.isSelected()){
types = 1;
}
List<SupplierBasic> list = iSupplierBasicService.selectSupplierBasicNotSotp(types,page, rows);
if(list != null && list.size() >0){
PageInfo<SupplierBasic> pageInfo = new PageInfo<>(list);
menu_first.setUserData(pageInfo.getFirstPage());
menu_prev.setUserData(pageInfo.getPrePage());
menu_next.setUserData(pageInfo.getNextPage());
menu_last.setUserData(pageInfo.getLastPage());
loadMoreSupplier(list);
}
}
/**
* 分页
* @param event
*/
public void pages(MouseEvent event){
Node node =(Node)event.getSource();
if(node.getUserData() != null){
int page =Integer.parseInt(String.valueOf(node.getUserData()));
setMenuValue(page);
}
}
/**
* 现有供应商查询
*/
public void loadMoreSupplier(List<SupplierBasic> supplierBasics){
ObservableList<SupplierBasic> list =FXCollections.observableArrayList();
tableView_supplier.setEditable(true);
findsupplierid.setCellValueFactory(new PropertyValueFactory("idnum"));
findsuppliername.setCellValueFactory(new PropertyValueFactory("supdes"));
for (SupplierBasic supplierBasics1:supplierBasics) {
list.add(supplierBasics1);
}
tableView_supplier.setItems(list); //tableview添加list
tableView_supplier.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<SupplierBasic>() {
@Override
public void changed(ObservableValue<? extends SupplierBasic> observableValue, SupplierBasic oldItem, SupplierBasic newItem) {
if(newItem.getIdnum() != null && !("".equals(newItem.getIdnum()))){
tableView_supplier.setUserData(newItem.getId());
}
}
});
tableView_supplier.setOnMouseClicked((MouseEvent t) -> {
if (t.getClickCount() == 2) {
closeSureWin();
}
});
}
public void closeSureWin(){
long id =(long)tableView_supplier.getUserData();
SupplierBasic supplierBasic = iSupplierBasicService.selectByKey(id);
if(supplierBasic != null){
// 账款 - 预付账款
AccountPrepaymentController accountPrepaymentController = (AccountPrepaymentController)StageManager.CONTROLLER.get("AccountPrepaymentController");
if(accountPrepaymentController != null){
accountPrepaymentController.customer_no.setText(supplierBasic.getIdnum());
accountPrepaymentController.customer_no_str.setText(supplierBasic.getSupname());
}
// 账款 - 进项发票
AccountInputInvoiceController accountInputInvoiceController = (AccountInputInvoiceController)StageManager.CONTROLLER.get("AccountInputInvoiceControllerSupplier");
if(accountInputInvoiceController != null){
accountInputInvoiceController.supplier_no.setText(supplierBasic.getIdnum());
accountInputInvoiceController.supplier_str.setText(supplierBasic.getSupname());
}
// 账款 - 应付账款冲账
AccountPayableController accountPayableControllerSupplier = (AccountPayableController)StageManager.CONTROLLER.get("AccountPayableControllerSupplier");
if(accountPayableControllerSupplier != null){
accountPayableControllerSupplier.supplier_no.setText(supplierBasic.getIdnum());
accountPayableControllerSupplier.supplier_no_str.setText(supplierBasic.getSupname());
}
// 账款 - 应付账款 Ben
PurchaseInvoiceController purchaseInvoiceControllerSupplierBen = (PurchaseInvoiceController)StageManager.CONTROLLER.get("PurchaseInvoiceControllerSupplierBen");
if(purchaseInvoiceControllerSupplierBen != null){
purchaseInvoiceControllerSupplierBen.supplierOrderStart.setText(supplierBasic.getIdnum());
}
// 账款 - 应付账款 End
PurchaseInvoiceController purchaseInvoiceControllerSupplierEnd = (PurchaseInvoiceController)StageManager.CONTROLLER.get("PurchaseInvoiceControllerSupplierEnd");
if(purchaseInvoiceControllerSupplierEnd != null){
purchaseInvoiceControllerSupplierEnd.supplierOrderEnd.setText(supplierBasic.getIdnum());
}
}
closeWin();
}
//关闭当前窗体
@FXML
public void closeWin(){
Stage stage=(Stage)tableView_supplier.getScene().getWindow();
StageManager.CONTROLLER.remove("AccountPrepaymentController");
StageManager.CONTROLLER.remove("AccountInputInvoiceControllerSupplier");
StageManager.CONTROLLER.remove("AccountPayableControllerSupplier");
StageManager.CONTROLLER.remove("PurchaseInvoiceControllerSupplierBen");
StageManager.CONTROLLER.remove("PurchaseInvoiceControllerSupplierEnd");
stage.close();
}
}
|
import java.util.*;
import java.lang.Iterable;
class Drawcards2
{
//__Data member:__
int x=0; //used as a function return value
int stop = 0; //if stop equals 1, the game will end.
//Process of drawing cards (the process of the game)
//__Class method:__
void drawingprocess(Player0 p0,Player1 p1,Player2 p2,Player3 p3,Computer2 pc2,Shuffle2 shuf2,Card cd){
//Continue next round if no one wins
while(stop!=1)
{
//Player0 draw a card from Player1
int D0 = (int)(Math.random()*(p1.numberofhc())); //Decide which card will be drawn
System.out.println("Player0 draws a card from Player1. "+cd.getcard(p1.getcard(D0)));
p0.setcard(p1.getcard(D0)); //Add the card into P0's hand-card
p1.remove(D0); //Remove the card from P1's hand-card
p0.sorthc(); //Sort the hand-card of P0
p0.dropcard(); //Drop cards from P1's hand-card if a pair form
p0.output(cd);
p1.output(cd);
x = pc2.checkwinner(p0,p1,p2,p3,shuf2,cd);//Check if anyone wins after this process
if(x==1)
{
stop=1;
continue;
}
//Player1 draw a card from Player2
int D1 = (int)(Math.random()*(p2.numberofhc()));
System.out.println("Player1 draws a card from Player2. "+cd.getcard(p2.getcard(D1)));
p1.setcard(p2.getcard(D1));
p2.remove(D1);
p1.sorthc();
p1.dropcard();
p1.output(cd);
p2.output(cd);
x = pc2.checkwinner(p0,p1,p2,p3,shuf2,cd);
if(x==1)
{
stop=1;
continue;
}
//Player2 draw a card from Player3
int D2 = (int)(Math.random()*(p3.numberofhc()));
System.out.println("Player2 draws a card from Player3. "+cd.getcard(p3.getcard(D2)));
p2.setcard(p3.getcard(D2));
p3.remove(D2);
p2.sorthc();
p2.dropcard();
p2.output(cd);
p3.output(cd);
x = pc2.checkwinner(p0,p1,p2,p3,shuf2,cd);
if(x==1)
{
stop=1;
continue;
}
//Player3 draw a card from Player0
int D3 = (int)(Math.random()*(p0.numberofhc()));
System.out.println("Player3 draws a card from Player0. "+cd.getcard(p0.getcard(D3)));
p3.setcard(p0.getcard(D3));
p0.remove(D3);
p3.sorthc();
p3.dropcard();
p3.output(cd);
p0.output(cd);
x = pc2.checkwinner(p0,p1,p2,p3,shuf2,cd);
if(x==1)
{
stop=1;
continue;
}
}
}
//reset variable
void resetvar(){
x=0;
stop = 0;
}
} |
package org.typhon.client.model;
import java.util.*;
import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.typhon.client.service.*;
public class Similarity {
private static final Logger logger = LoggerFactory.getLogger(Similarity.class);
private String name;
private float values;
private List<Song> sourceObj;
private List<String
> source;
private List<Song> targetObj;
private List<String
> target;
public void setName (String name){
this.name = name;
}
public String getName(){
return name;
}
public void setValues (float values){
this.values = values;
}
public float getValues(){
return values;
}
public List<String
> getSource(){
return source;
}
public void setSource(List<String
> source){
this.source = source;
}
public List<String
> getTarget(){
return target;
}
public void setTarget(List<String
> target){
this.target = target;
}
public List<Song> getSongObj() {
SongService songService = new SongService("http://localhost:8097");
List<Song> result = new ArrayList<Song>();
for (String
typeObj : source) {
try {
result.add(songService.findById(typeObj));
}
catch (Exception e) {
logger.error(e.getMessage());
}
}
return result;
}
public List<Song> getSongObj() {
SongService songService = new SongService("http://localhost:8097");
List<Song> result = new ArrayList<Song>();
for (String
typeObj : target) {
try {
result.add(songService.findById(typeObj));
}
catch (Exception e) {
logger.error(e.getMessage());
}
}
return result;
}
}
|
package com.example.adnan.inventoryapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by Adnan on 8/21/2016.
*/
public class sqlHandler extends SQLiteOpenHelper {
public static final String Database_Name = "Products.db";
public static final String Table_Name = "products";
public static final String Table_Name2 = "sales";
// public static final String Coloumn_ID = "_id";
// public static final String Coloumn_Products = "products";
public static final int Database_Version = 5;
public static ArrayList<signatureProducts> arrayList;
public static ArrayList<signatureSales> arrayList2;
adaptorProducts adaptor;
public sqlHandler(Context context) {
super(context, Database_Name, null, Database_Version);
arrayList = new ArrayList<>();
arrayList2 = new ArrayList<>();
}
@Override
public void onCreate(SQLiteDatabase db) {
String table = "CREATE TABLE IF NOT EXISTS " + Table_Name + "(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , name TEXT , quantity INTEGER , price INTEGER )";
db.execSQL(table);
String table2 = "CREATE TABLE IF NOT EXISTS " + Table_Name2 + "(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , name TEXT , quantity INTEGER , price INTEGER ,sale INTEGER)";
db.execSQL(table2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS sales");
db.execSQL("DROP TABLE IF EXISTS products");
onCreate(db);
}
public void insertProduct(signatureProducts s) {
ContentValues content = new ContentValues();
content.put("name", s.getName());
content.put("quantity", s.getQuantity());
content.put("price", s.getPrice());
SQLiteDatabase db = getWritableDatabase();
db.insert("products", null, content);
db.close();
}
//
public void deleteProduct(int id, String tableName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + tableName + " WHERE ID =" + id + ";");
db.close();
}
public void updateValue(signatureProducts signatureProducts) {
SQLiteDatabase db = getWritableDatabase();
ContentValues content = new ContentValues();
content.put("name", signatureProducts.getName());
content.put("quantity", signatureProducts.getQuantity());
content.put("price", signatureProducts.getPrice());
db.update(Table_Name, content, "ID=?", new String[]{String.valueOf(signatureProducts.getId())});
db.close();
}
public ArrayList<signatureProducts> retrive() {
arrayList.clear();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + Table_Name;
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()) {
int id = Integer.parseInt(c.getString(0));
String name = c.getString(1);
int quantity = c.getInt(2);
int price = c.getInt(3);
arrayList.add(new signatureProducts(name, quantity, id, price));
}
db.close();
return arrayList;
}
public void insertSales(signatureSales s) {
ContentValues content = new ContentValues();
content.put("name", s.getName());
content.put("quantity", s.getQuantity());
content.put("price", s.getPrice());
content.put("sale", s.getSales());
SQLiteDatabase db = getWritableDatabase();
db.insert("sales", null, content);
db.close();
}
public ArrayList<signatureSales> retriveSales() {
arrayList2.clear();
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+Table_Name2;
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()) {
int id = Integer.parseInt(c.getString(0));
String name = c.getString(1);
int quantity = c.getInt(2);
int price = c.getInt(3);
int sales = c.getInt(4);
arrayList2.add(new signatureSales(name, sales, quantity, price, id));
}
db.close();
return arrayList2;
}
}
|
package noiter.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/")
public class HomeController {
@RequestMapping({"/", "/home"})
public String getContent() {
return "first-page";
}
} |
package cn.com.signheart.component.core.core.service;
import cn.com.signheart.component.core.core.model.TbPlatFormConfig;
import java.sql.SQLException;
import java.util.List;
/**
* Created by ao.ouyang on 16-1-11.
*/
public interface IPlatFormCfgService {
/**
* 查询所有配置
* @return
* @throws SQLException
*/
List<TbPlatFormConfig> listAllCfg() throws SQLException;
}
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.neuron.mytelkom.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.neuron.mytelkom.model.Ticket;
import java.util.LinkedList;
public class MyTicketAdapter extends BaseAdapter
{
static class ViewHolder
{
TextView txtDate;
TextView txtNo;
TextView txtProductNo;
TextView txtStatus;
ViewHolder()
{
}
}
Activity activity;
LinkedList listItem;
public MyTicketAdapter(Activity activity1, LinkedList linkedlist)
{
activity = activity1;
listItem = linkedlist;
}
public int getCount()
{
return listItem.size();
}
public Object getItem(int i)
{
return null;
}
public long getItemId(int i)
{
return 0L;
}
public View getView(int i, View view, ViewGroup viewgroup)
{
View view1 = view;
ViewHolder viewholder;
if (view1 == null)
{
viewholder = new ViewHolder();
view1 = ((LayoutInflater)activity.getSystemService("layout_inflater")).inflate(0x7f03003a, null);
viewholder.txtNo = (TextView)view1.findViewById(0x7f0a00eb);
viewholder.txtDate = (TextView)view1.findViewById(0x7f0a00ed);
viewholder.txtStatus = (TextView)view1.findViewById(0x7f0a00ee);
viewholder.txtProductNo = (TextView)view1.findViewById(0x7f0a00ec);
view1.setTag(viewholder);
} else
{
viewholder = (ViewHolder)view1.getTag();
}
viewholder.txtNo.setText((new StringBuilder("Ticket No : ")).append(((Ticket)listItem.get(i)).getTicketNo()).toString());
viewholder.txtDate.setText(((Ticket)listItem.get(i)).getComplaintDatetime());
viewholder.txtProductNo.setText((new StringBuilder("Product No :")).append(((Ticket)listItem.get(i)).getProductNo()).toString());
viewholder.txtStatus.setText((new StringBuilder("Status :")).append(((Ticket)listItem.get(i)).getCompaintStatus()).toString());
return view1;
}
}
|
package org.squonk.camel.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.squonk.camel.CamelCommonConstants;
import org.squonk.dataset.Dataset;
import org.squonk.dataset.DatasetMetadata;
import org.squonk.types.io.JsonHandler;
import org.squonk.util.CommonMimeTypes;
import java.io.InputStream;
/**
* Created by timbo on 05/07/16.
*/
public class DatasetToJsonProcessor implements Processor {
private final Class type;
public DatasetToJsonProcessor(Class type) {
this.type = type;
}
@Override
public void process(Exchange exchange) throws Exception {
Dataset dataset = exchange.getIn().getBody(Dataset.class);
if (dataset == null) {
throw new IllegalStateException("Could not read Dataset. Should be present as the body.");
}
String acceptEncoding = exchange.getIn().getHeader("Accept-Encoding", String.class);
boolean gzip = "gzip".equals(acceptEncoding);
InputStream is = dataset.getInputStream(gzip);
exchange.getIn().setBody(is);
DatasetMetadata meta = dataset.getMetadata();
if (meta != null) {
String json = JsonHandler.getInstance().objectToJson(meta);
exchange.getIn().setHeader(CamelCommonConstants.HEADER_METADATA, json);
}
if (gzip) {
exchange.getIn().setHeader("Content-Encoding", "gzip");
}
exchange.getIn().setHeader("Content-Type", CommonMimeTypes.MIME_TYPE_DATASET_MOLECULE_JSON);
}
}
|
package com.appfountain.external;
import java.util.List;
import com.appfountain.model.Question;
/**
* {"questions":[{"valid":true,"body":"body","created":"2013-10-04T17:29:43",
* "category_id"
* :1,"id":1,"user_id":1,"title":"\u305f\u3044\u308d\u3064","updated"
* :"2013-10-04T17:29:43"}], "status":true}
*/
public class QuestionsSource extends BaseSource {
private List<Question> questions;
public List<Question> getQuestions() {
return questions;
}
}
|
package com.qa.PetClinicJUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class PetClinicOwnerInformation {
@FindBy(xpath = "/html/body/app-root/app-owner-detail/div/div/h2[1]")
private WebElement ownerInformationPageTitle;
public String getOwnerInformationPageTitle() {
return ownerInformationPageTitle.getText();
}
}
|
package com.allstate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by sameer on 2/1/17.
*/
public class QuoteTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void quoteCreateWithNameAndPrice (){
Quote quote = new Quote("Apple", 50);
assertEquals("Apple", quote.getName());
assertEquals(50, quote.getPrice());
}
} |
/* Copyright (c) 2019 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode.algorithms;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import java.util.ArrayList;
import java.util.List;
import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.YZX;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC;
import static org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection.BACK;
/**
* This class uses the Vuforia localizer to determine positioning and orientation of robot on the SKYSTONE FTC field.
* In order to use an object of this class, it must be initialized with the robot's hardwareMap as
* a parameter. The method initView() must then be called. Because the view does not automatically
* update, the method updateView() must be called in the while active loop.
* <p>
* When images are located, Vuforia is able to determine the position and orientation of the
* image relative to the camera. This sample code then combines that information with a
* knowledge of where the target images are on the field, to determine the location of the camera.
* <p>
* From the Audience perspective, the Red Alliance station is on the right and the
* Blue Alliance Station is on the left.
* <p>
* Eight perimeter targets are distributed evenly around the four perimeter walls
* Four Bridge targets are located on the bridge uprights.
* Refer to the Field Setup manual for more specific location details
* <p>
* A final calculation then uses the location of the camera on the robot to determine the
* robot's location and orientation on the field.
* <p>
* For coordinate system: origin is on floor at center of field
* x axis is perp. to y axis; building zone is positive and loading zone is negative
* y axis runs through bridges; blue side is positive and red side is negative
* z axis goes through center of field; up is positive
* no clue yet which direction is zero degrees and which direction is positive degrees
* going with assumption that degrees go from 0 to 359 and that positive is counterclockwise
* -1 is red alliance, 1 is blue alliance
* <p>
* To get the x and y of a stone, call getStoneX and getStoneY respectively
* <p>
* To get the number, x, and y of a sky stone, call getSkyStonePosition, getSkyStoneX, and getSkyStoneY, respectively
* TODO: make wiring work
* TODO: make sure that code works
* TODO: confirm how the angle system works, and adjust it if necessary
*/
public class VuforiaAutoNav {
/**
*
*/
private static final String TFOD_MODEL_ASSET = "Skystone.tflite";
private static final String LABEL_FIRST_ELEMENT = "Stone";
private static final String LABEL_SECOND_ELEMENT = "Skystone";
private static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
private static final boolean PHONE_IS_PORTRAIT = false;
/*
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "ATUUQRD/////AAABmWvkn/HpKkiTkmH+kqcdQa87+E5nnizSTMHex9sTxsSbub3m/AzfdamdYGP7pwr/6Ea3A5aHYC35fc9Nw8wFLofmMHwKHSwnm6wC/kS6oEspjXxlk7p3YKgHpe9iWIuvYVHDI211sVIxCg+wd8DvtdoFulhQ+dLLSajTNryZpsKgOJRHKnq4KREOb3jticHQpvTWDrM3O3yya3F5KEOBUr5ekhLxz06M7VpmIeuCc6FTw3RxRQ6qtqKfXxCzCK0ziyyDyMlBCie0WH1gvI1kKhk3modRIaJfaTcAw54REWyTfIhhV3A4Nyp/99j1FYonm94fu/gvOemiGDI1WWotAOSYqxnLmru7vN7kSzlsKits";
// Since ImageTarget trackables use mm to specifiy their dimensions, we must use mm for all the physical dimension.
// We will define some constants and conversions here
private static final float mmPerInch = 25.4f;
private static final float mmTargetHeight = (6) * mmPerInch; // the height of the center of the target image above the floor
// Constant for Stone Target (currently unused)
private static final float stoneZ = 2.00f * mmPerInch;
// Constants for the center support targets
private static final float bridgeZ = 6.42f * mmPerInch;
private static final float bridgeY = 23 * mmPerInch;
private static final float bridgeX = 5.18f * mmPerInch;
private static final float bridgeRotY = 59; // Units are degrees
private static final float bridgeRotZ = 180;
// Constants for perimeter targets
private static final float halfField = 72 * mmPerInch;
private static final float quadField = 36 * mmPerInch;
// Class Members
private OpenGLMatrix lastLocation = null;
private VuforiaLocalizer vuforia = null;
private TFObjectDetector tfod;
/**
* This is the webcam we are to use. As with other hardware devices such as motors and
* servos, this device is identified using the robot configuration tool in the FTC application.
*/
WebcamName webcamName = null;
private boolean targetVisible = false;
private float phoneXRotate = 0;
private float phoneYRotate = 0;
private float phoneZRotate = 0;
private ArrayList<Stone> Stones = new ArrayList<>();
private HardwareMap hardwareMap;
private Telemetry telemetry;
List<VuforiaTrackable> allTrackables = new ArrayList<VuforiaTrackable>();
private int[] skyStonePositions = {-1, -1};
private float robotX = 0;
private float robotY = 0;
private float robotZ = 0;
private float robotAngle = 0;
private int alliance = 0;
private boolean allianceDetection = true; // determines whether the robot will automatically detect the alliance it is on
/**
* gets the alliance
*
* @return alliance (1 is blue, -1 is red)
*/
public int getAlliance() {
return alliance;
}
/**
* sets the alliance
*
* @param alliance Indicates alliance (1 is blue, -1 is red)
*/
public void setAlliance(int alliance) {
this.alliance = alliance;
}
/**
* gets the hardware map
*
* @return hardware map
*/
public HardwareMap getHardwareMap() {
return hardwareMap;
}
/**
* sets the hardware map
*
* @param hardwareMap hardware map
*/
public void setHardwareMap(HardwareMap hardwareMap) {
this.hardwareMap = hardwareMap;
}
/**
* gets the telemetry
*
* @return telemetry
*/
public Telemetry getTelemetryMap() {
return telemetry;
}
/**
* sets the telemetry
*
* @param telemetry telemetry
*/
public void setTelemetry(Telemetry telemetry) {
this.telemetry = telemetry;
}
/**
* list of vuforia trackables
*
* @return vuforia trackables
*/
public List<VuforiaTrackable> getAllTrackables() {
return allTrackables;
}
/**
* sets vuforia trackables
*
* @param allTrackables vuforia trackables
*/
public void setAllTrackables(List<VuforiaTrackable> allTrackables) {
this.allTrackables = allTrackables;
}
public float getRobotX() {
return robotX;
}
public void setRobotX(float robotX) {
this.robotX = robotX;
}
public float getRobotY() {
return robotY;
}
public void setRobotY(float robotY) {
this.robotY = robotY;
}
public float getRobotZ() {
return robotZ;
}
public void setRobotZ(float robotZ) {
this.robotZ = robotZ;
}
public void setRobotPosition(float robotX, float robotY, float robotZ) {
this.setRobotX(robotX);
this.setRobotY(robotY);
this.setRobotZ(robotZ);
}
public float getRobotAngle() {
return robotAngle;
}
public void setRobotAngle(float robotAngle) {
this.robotAngle = robotAngle;
}
public ArrayList<Stone> getStones() {
return Stones;
}
public void setStones(ArrayList<Stone> stones) {
Stones = stones;
}
public Stone getStone(int index) {
return Stones.get(index);
}
public void setStone(int index, Stone stone) {
Stones.set(index, stone);
}
public void addStone(int kind, float top, float bottom, float left, float right) {
Stone stone = new Stone(kind, top, bottom, left, right);
this.getStones().add(stone);
}
public void addStone(float top, float bottom, float left, float right) {
Stone stone = new Stone(top, bottom, left, right);
this.getStones().add(stone);
}
public void addStone(Stone stone) {
this.getStones().add(stone);
}
public void clearStones() {
this.getStones().clear();
}
public int[] getSkyStonePositions() {
return skyStonePositions;
}
public void setSkyStonePositions(int[] skyStonePositions) {
this.skyStonePositions = skyStonePositions;
}
/**
* Gets the relative position of one of the sky stones
*
* @param index the stone to return (0 for left one, 1 for right one)
* @return the sky stone position (they are indexed from 0 to 5 from left to right when looking away from the field wall)
*/
public int getSkyStonePosition(int index) {
return skyStonePositions[index];
}
public void setSkyStonePosition(int index, int skyStonePosition) {
this.skyStonePositions[index] = skyStonePosition;
}
/**
* gets the X coordinate of the center of a stone
*
* @param stoneNum Indicates stone number (they are indexed from 0 to 5 from left to right when looking away from the field wall)
* @param alliance Indicates alliance (1 is blue, -1 is red)
* @return stone center x
*/
public float getStoneCenterX(int stoneNum, int alliance) {
if (stoneNum < 0 || stoneNum > 5) {
return 0;
} else {
if (alliance == 1) {
return 28 + 8 * stoneNum;
} else if (alliance == -1) {
return 28 + 8 * (5 - stoneNum);
} else {
return 0;
}
}
}
/**
* gets the Y coordinate of the center of a stone
*
* @param stoneNum Indicates stone number (they are indexed from 0 to 5 from left to right when looking away from the field wall)
* @param alliance Indicates alliance (1 is blue, -1 is red)
* @return stone center y
*/
public float getStoneCenterY(int stoneNum, int alliance) {
if (alliance == 1) {
return 22;
} else if (alliance == -1) {
return -22;
} else {
return 0;
}
}
/**
* gets the X coordinate of the center of a sky stone stone
*
* @param index Indicates sky stone number
* @param alliance Indicates alliance (1 is blue, -1 is red)
* @return stone center x
*/
public float getSkyStoneCenterX(int index, int alliance) {
int stoneNum = this.getSkyStonePosition(index);
if (stoneNum < 0 || stoneNum > 5) {
return 0;
} else {
if (alliance == 1) {
return 28 + 8 * stoneNum;
} else if (alliance == -1) {
return 28 + 8 * (5 - stoneNum);
} else {
return 0;
}
}
}
/**
* gets the Y coordinate of the center of a sky stone
*
* @param index Indicates sky stone number
* @param alliance Indicates alliance (1 is blue, -1 is red)
* @return stone center y
*/
public float getSkyStoneCenterY(int index, int alliance) {
if (alliance == 1) {
return 22;
} else if (alliance == -1) {
return -22;
} else {
return 0;
}
}
/**
* gets the X coordinate of the center of a stone
*
* @param stoneNum Indicates stone number (they are indexed from 0 to 5 from left to right when looking away from the field wall)
* @return stone center x
*/
public float getStoneCenterX(int stoneNum) {
return this.getStoneCenterX(stoneNum, this.getAlliance());
}
/**
* gets the Y coordinate of the center of a stone
*
* @param stoneNum Indicates stone number (they are indexed from 0 to 5 from left to right when looking away from the field wall)
* @return stone center y
*/
public float getStoneCenterY(int stoneNum) {
return this.getStoneCenterY(stoneNum, this.getAlliance());
}
/**
* gets the X coordinate of the center of a sky stone stone
*
* @param index Indicates sky stone number
* @return stone center x
*/
public float getSkyStoneCenterX(int index) {
return this.getSkyStoneCenterX(index, this.getAlliance());
}
/**
* gets the Y coordinate of the center of a sky stone
*
* @param index Indicates sky stone number
* @return stone center y
*/
public float getSkyStoneCenterY(int index) {
return this.getSkyStoneCenterX(index, this.getAlliance());
}
/**
* gets allianceDetection, which determines whether the robot should detect its alliance
*
* @return allianceDetection
*/
public boolean isAllianceDetection() {
return allianceDetection;
}
/**
* gets allianceDetection, which determines whether the robot should detect its alliance
*
* @return allianceDetection
*/
public boolean allianceDetectionOn() {
return allianceDetection;
}
/**
* sets allianceDetection, which determines whether the robot should detect its alliance
*
* @param allianceDetection
*/
public void setAllianceDetection(boolean allianceDetection) {
this.allianceDetection = allianceDetection;
}
/**
* sets allianceDetection to true, which determines whether the robot should detect its alliance
*/
public void turnOnAllianceDetection() {
this.allianceDetection = true;
}
/**
* sets allianceDetection to false, which determines whether the robot should detect its alliance
*/
public void turnOffAllianceDetection() {
this.allianceDetection = false;
}
/**
* Because this class is not an opmode, the opmode using it needs to feed in its hardware map and telemetry.
*
* @param hardwareMap
* @param telemetry
*/
public VuforiaAutoNav(HardwareMap hardwareMap, Telemetry telemetry) {
this.hardwareMap = hardwareMap;
this.telemetry = telemetry;
this.initView();
}
/**
* Because this class is not an opmode, the opmode using it needs to feed in its hardware map and telemetry.
*
* @param hardwareMap
* @param alliance
* @param telemetry
*/
public VuforiaAutoNav(HardwareMap hardwareMap, Telemetry telemetry, int alliance) {
this.hardwareMap = hardwareMap;
this.telemetry = telemetry;
this.initView();
this.setAlliance(alliance);
this.turnOffAllianceDetection();
}
/**
* This method initializes the webcam and navigation system and should always be used first.
*/
public void initView() {
/*
* Retrieve the camera we are to use.
*/
webcamName = hardwareMap.get(WebcamName.class, "Webcam 1");
/*
* Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine.
* We can pass Vuforia the handle to a camera preview resource (on the RC phone);
* If no camera monitor is desired, use the parameter-less constructor instead (commented out below).
*/
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
// VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
parameters.vuforiaLicenseKey = VUFORIA_KEY;
/**
* We also indicate which camera on the RC we wish to use.
*/
parameters.cameraName = webcamName;
// Instantiate the Vuforia engine
vuforia = ClassFactory.getInstance().createVuforia(parameters);
// Load the data sets for the trackable objects. These particular data
// sets are stored in the 'assets' part of our application.
VuforiaTrackables targetsSkyStone = this.vuforia.loadTrackablesFromAsset("Skystone");
// skystones have a variable position, so we can't use them.
// VuforiaTrackable stoneTarget = targetsSkyStone.get(0);
// stoneTarget.setName("Stone Target");
VuforiaTrackable blueRearBridge = targetsSkyStone.get(1);
blueRearBridge.setName("Blue Rear Bridge");
VuforiaTrackable redRearBridge = targetsSkyStone.get(2);
redRearBridge.setName("Red Rear Bridge");
VuforiaTrackable redFrontBridge = targetsSkyStone.get(3);
redFrontBridge.setName("Red Front Bridge");
VuforiaTrackable blueFrontBridge = targetsSkyStone.get(4);
blueFrontBridge.setName("Blue Front Bridge");
VuforiaTrackable red1 = targetsSkyStone.get(5);
red1.setName("Red Perimeter 1");
VuforiaTrackable red2 = targetsSkyStone.get(6);
red2.setName("Red Perimeter 2");
VuforiaTrackable front1 = targetsSkyStone.get(7);
front1.setName("Front Perimeter 1");
VuforiaTrackable front2 = targetsSkyStone.get(8);
front2.setName("Front Perimeter 2");
VuforiaTrackable blue1 = targetsSkyStone.get(9);
blue1.setName("Blue Perimeter 1");
VuforiaTrackable blue2 = targetsSkyStone.get(10);
blue2.setName("Blue Perimeter 2");
VuforiaTrackable rear1 = targetsSkyStone.get(11);
rear1.setName("Rear Perimeter 1");
VuforiaTrackable rear2 = targetsSkyStone.get(12);
rear2.setName("Rear Perimeter 2");
// For convenience, gather together all the trackable objects in one easily-iterable collection */
allTrackables.addAll(targetsSkyStone);
/**
* In order for localization to work, we need to tell the system where each target is on the field, and
* where the phone resides on the robot. These specifications are in the form of <em>transformation matrices.</em>
* Transformation matrices are a central, important concept in the math here involved in localization.
* See <a href="https://en.wikipedia.org/wiki/Transformation_matrix">Transformation Matrix</a>
* for detailed information. Commonly, you'll encounter transformation matrices as instances
* of the {@link OpenGLMatrix} class.
*
* If you are standing in the Red Alliance Station looking towards the center of the field,
* - The X axis runs from your left to the right. (positive from the center to the right)
* - The Y axis runs from the Red Alliance Station towards the other side of the field
* where the Blue Alliance Station is. (Positive is from the center, towards the BlueAlliance station)
* - The Z axis runs from the floor, upwards towards the ceiling. (Positive is above the floor)
*
* Before being transformed, each target image is conceptually located at the origin of the field's
* coordinate system (the center of the field), facing up.
*/
// Set the position of the Stone Target. Since it's not fixed in position, assume it's at the field origin.
// Rotated it to to face forward, and raised it to sit on the ground correctly.
// This can be used for generic target-centric approach algorithms
// stoneTarget.setLocation(OpenGLMatrix
// .translation(0, 0, stoneZ)
// .multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
//Set the position of the bridge support targets with relation to origin (center of field)
blueFrontBridge.setLocation(OpenGLMatrix
.translation(-bridgeX, bridgeY, bridgeZ)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 0, bridgeRotY, bridgeRotZ)));
blueRearBridge.setLocation(OpenGLMatrix
.translation(-bridgeX, bridgeY, bridgeZ)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 0, -bridgeRotY, bridgeRotZ)));
redFrontBridge.setLocation(OpenGLMatrix
.translation(-bridgeX, -bridgeY, bridgeZ)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 0, -bridgeRotY, 0)));
redRearBridge.setLocation(OpenGLMatrix
.translation(bridgeX, -bridgeY, bridgeZ)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 0, bridgeRotY, 0)));
//Set the position of the perimeter targets with relation to origin (center of field)
red1.setLocation(OpenGLMatrix
.translation(quadField, -halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 180)));
red2.setLocation(OpenGLMatrix
.translation(-quadField, -halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 180)));
front1.setLocation(OpenGLMatrix
.translation(-halfField, -quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 90)));
front2.setLocation(OpenGLMatrix
.translation(-halfField, quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 90)));
blue1.setLocation(OpenGLMatrix
.translation(-quadField, halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 0)));
blue2.setLocation(OpenGLMatrix
.translation(quadField, halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 0)));
rear1.setLocation(OpenGLMatrix
.translation(halfField, quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
rear2.setLocation(OpenGLMatrix
.translation(halfField, -quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
//
// Create a transformation matrix describing where the phone is on the robot.
//
// Info: The coordinate frame for the robot looks the same as the field.
// The robot's "forward" direction is facing out along X axis, with the LEFT side facing out along the Y axis.
// Z is UP on the robot. This equates to a bearing angle of Zero degrees.
//
// The phone starts out lying flat, with the screen facing Up and with the physical top of the phone
// pointing to the LEFT side of the Robot.
// The two examples below assume that the camera is facing forward out the front of the robot.
// We need to rotate the camera around it's long axis to bring the correct camera forward.
if (CAMERA_CHOICE == BACK) {
phoneYRotate = -90;
} else {
phoneYRotate = 90;
}
// Rotate the phone vertical about the X axis if it's in portrait mode
if (PHONE_IS_PORTRAIT) {
phoneXRotate = 90;
}
// Next, translate the camera lens to where it is on the robot.
// In this example, it is centered (left to right), but forward of the middle of the robot, and above ground level.
// the robot 15.68 is inches wide and 16.25 inches long (measured from wheel to wheel)
// the camera's lens is 0.415 inches from the front of the 3d printed mount
final float CAMERA_FORWARD_DISPLACEMENT = 2.035f * mmPerInch; // eg: Camera is 2.035 Inches in front of robot-center
final float CAMERA_VERTICAL_DISPLACEMENT = 9.4f * mmPerInch; // Camera is 9.4 Inches above ground
final float CAMERA_LEFT_DISPLACEMENT = 0.215f * mmPerInch; // Camera is 0.215 Inches to the left of robot-center
OpenGLMatrix robotFromCamera = OpenGLMatrix
.translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT, CAMERA_VERTICAL_DISPLACEMENT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, YZX, DEGREES, phoneYRotate, phoneZRotate, phoneXRotate));
/** Let all the trackable listeners know where the phone is. */
for (VuforiaTrackable trackable : allTrackables) {
((VuforiaTrackableDefaultListener) trackable.getListener()).setPhoneInformation(robotFromCamera, parameters.cameraDirection);
}
// WARNING:
// In this sample, we do not wait for PLAY to be pressed. Target Tracking is started immediately when INIT is pressed.
// This sequence is used to enable the new remote DS Camera Preview feature to be used with this sample.
// CONSEQUENTLY do not put any driving commands in this loop.
// To restore the normal opmode structure, just un-comment the following line:
// waitForStart();
// Note: To use the remote camera preview:
// AFTER you hit Init on the Driver Station, use the "options menu" to select "Camera Stream"
// Tap the preview window to receive a fresh image.
targetsSkyStone.activate();
// Disable Tracking when we are done;
if (ClassFactory.getInstance().canCreateTFObjectDetector()) {
initTfod();
}
/**
* Activate TensorFlow Object Detection before we wait for the start command.
* Do it here so that the Camera Stream window will have the TensorFlow annotations visible.
**/
if (tfod != null) {
tfod.activate();
}
}
/**
* This method updates the robot's position, angle, and field of view.
*/
public void updateView() {
// check all the trackable targets to see which one (if any) is visible.
targetVisible = false;
for (VuforiaTrackable trackable : allTrackables) {
if (((VuforiaTrackableDefaultListener) trackable.getListener()).isVisible()) {
// telemetry.addData("Visible Target", trackable.getName());
targetVisible = true;
// getUpdatedRobotLocation() will return null if no new information is available since
// the last time that call was made, or if the trackable is not currently visible.
OpenGLMatrix robotLocationTransform = ((VuforiaTrackableDefaultListener) trackable.getListener()).getUpdatedRobotLocation();
if (robotLocationTransform != null) {
lastLocation = robotLocationTransform;
}
break;
}
}
// Provide feedback as to where the robot is located (if we know).
if (targetVisible) {
// express position (translation) of robot in inches.
VectorF translation = lastLocation.getTranslation();
this.setRobotPosition(translation.get(0) / mmPerInch, translation.get(1) / mmPerInch, translation.get(2) / mmPerInch);
telemetry.addData("Pos (in)", "{X, Y, Z} = %.1f, %.1f, %.1f",
translation.get(0) / mmPerInch, translation.get(1) / mmPerInch, translation.get(2) / mmPerInch);
// express the rotation of the robot in degrees.
Orientation rotation = Orientation.getOrientation(lastLocation, EXTRINSIC, XYZ, DEGREES);
this.setRobotAngle(rotation.thirdAngle);
telemetry.addData("Rot (deg)", "{Roll, Pitch, Heading} = %.0f, %.0f, %.0f", rotation.firstAngle, rotation.secondAngle, rotation.thirdAngle);
telemetry.update();
if (this.getAlliance() == 0 && this.allianceDetectionOn()) {
this.setAlliance((int) Math.signum(this.getRobotY()));
}
}
if (tfod != null) {
// getUpdatedRecognitions() will return null if no new information is available since
// the last time that call was made.
List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions();
if (updatedRecognitions != null) {
ArrayList<Stone> stoneView = new ArrayList<>();
// step through the list of recognitions and display boundary info.
this.clearStones();
for (Recognition recognition : updatedRecognitions) {
int kind = 0;
if (recognition.getLabel().equals("Skystone")) {
kind = 1;
}
Stone newStone = new Stone(kind, recognition.getTop(), recognition.getBottom(), recognition.getLeft(), recognition.getRight());
stoneView.add(newStone);
}
for (int i = 0; i < updatedRecognitions.size(); i++) {
float currentPosition = stoneView.get(0).getCenterX();
int currentStone = 0;
for (int j = 1; j < updatedRecognitions.size() - i - 1; j++) {
if (stoneView.get(j).getCenterX() < currentPosition) {
currentPosition = stoneView.get(j).getCenterX();
currentStone = j;
}
}
this.addStone(stoneView.get(currentStone));
stoneView.remove(currentStone);
}
if (updatedRecognitions.size() == 6 && (this.getSkyStonePosition(0) == -1 || this.getSkyStonePosition(1) == -1)) {
for (int i = 0; i < 6; i++) {
if (this.getStone(i).getKind() == 1) {
if (this.getSkyStonePosition(0) == -1) {
this.setSkyStonePosition(0, i);
} else {
this.setSkyStonePosition(1, i);
}
}
}
}
}
}
}
private void initTfod() {
int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier(
"tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName());
TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId);
tfodParameters.minimumConfidence = 0.8;
tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia);
tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_FIRST_ELEMENT, LABEL_SECOND_ELEMENT);
}
}
|
package no.ntnu.stud.ubilearn.fragments;
import java.util.HashMap;
import no.ntnu.stud.ubilearn.R;
import no.ntnu.stud.ubilearn.User;
import no.ntnu.stud.ubilearn.db.TrainingDAO;
import no.ntnu.stud.ubilearn.models.CasePatient;
import no.ntnu.stud.ubilearn.models.CasePatientStatus;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
/**
* class for the patient case
* @author ingeborgoftedal
*
*/
@SuppressLint("ValidFragment")
public class PatientCaseFragment extends Fragment{
private String _name, _age, _gender, _pasientInfo;
private int _level;
private CasePatient patient;
private TextView statusText;
//Empty constructor for validFragment
public PatientCaseFragment() {
}
public PatientCaseFragment(CasePatient patient) {
this.patient = patient;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
_name = patient.getName();
_age = patient.getAge();
_gender = patient.getGender();
_pasientInfo = patient.getInfo();
_level = patient.getLevel();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.training_case, container, false);
TextView name = (TextView) rootView.findViewById(R.id.case_PatientName);
name.setText(_name);
TextView age = (TextView) rootView.findViewById(R.id.case_patientAge);
age.setText("Alder: " + _age);
TextView gender = (TextView) rootView.findViewById(R.id.case_patientGender);
gender.setText("Kjønn: " + _gender);
TextView pasientInfo = (TextView) rootView.findViewById(R.id.case_patientInfoField);
pasientInfo.setText(_pasientInfo);
RatingBar level = (RatingBar)rootView.findViewById(R.id.training_ratingBar);
TrainingDAO trainingDAO = new TrainingDAO(getActivity());
trainingDAO.open();
level.setEnabled(false);
statusText = (TextView)rootView.findViewById(R.id.training_status);
/**
* sjekker om casen er klart eller ikke og setter rating etter hvor mange spm som er klart
*/
if(User.getInstance().getHouseStatus(patient.getObjectId()).getHighScore() > 0){
statusText.setText("Gratulerer, du har klart denne casen " + "\n" +User.getInstance().getHouseStatus(patient.getObjectId()).getHighScore() + "/" + (trainingDAO.getPatientQuizzes(patient)).size());
if(User.getInstance().getHouseStatus(patient.getObjectId()).getHighScore() < trainingDAO.getPatientQuizzes(patient).size()){
level.setRating(1);
}
else{
level.setRating(2);
}
}
else{
statusText.setText("Du har ikke klart casen ennå " + "\n" +User.getInstance().getHouseStatus(patient.getObjectId()).getHighScore() + "/" + (trainingDAO.getPatientQuizzes(patient)).size());
}
trainingDAO.close();
Button next = (Button)rootView.findViewById(R.id.training_case_next);
next.setOnClickListener(new OnClickListener() {//neste knapp til Quiz fra pasientCase
@Override
public void onClick(View v) {
TrainingDAO trainingDAO = new TrainingDAO(getActivity());
trainingDAO.open();
if(trainingDAO.getPatientQuizzes(patient) != null){
Fragment fragment = new QuizFragment(patient);
getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("quiz").commit();
}else{
Toast.makeText(getActivity(), "No quiz avaliable", Toast.LENGTH_SHORT).show();
}
trainingDAO.close();
}
});
//tilbake knapp fra pasientcase
Button back = (Button)rootView.findViewById(R.id.training_case_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFragmentManager().popBackStack();
}
});
return rootView;
}
}
|
package com.java.domain;
public class StuBean {
private Integer id;//学号
private String name;//姓名
private String password;//密码
private String position;//位置
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public String toString() {
return "StuBean [id=" + id + ", name=" + name + ", password=" + password + ", position=" + position + "]";
}
}
|
package com.robin.springboot.demo.java_designPatterns.adapter;
/**
* 目标功能接口,所包含的方法都是或者大多数是目标方法
*/
public interface B {
void b();
}
|
package com.invillia.acme.persistence;
import com.invillia.acme.persistence.custom.CustomOrderItemRepository;
import com.invillia.acme.persistence.entity.OrderItem;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface OrderItemRepository extends PagingAndSortingRepository<OrderItem, Long>, CustomOrderItemRepository {
}
|
package com.flp.ems.view;
import java.util.HashSet;
import java.util.Scanner;
import com.flp.ems.domain.Employee;
public class BootClass {
public static void main(String[] args) {
int x=0;
do{
System.out.println("Enter 1 to Create employee ");
System.out.println("Enter 2 to Modify Employee Info");
System.out.println("Enter 3 to Remove Employee");
System.out.println("Enter 4 to View all employee");
System.out.println("Enter 5 to Search employree by kinId,email Id");
System.out.println("Enter 6 to exit the Operation");
Scanner sc = new Scanner(System.in);
int userinput_value=sc.nextInt();
if(userinput_value==6)
x=6;
menuSelection(userinput_value);
}while(x!=6);
System.out.println("Operation Successful");
}
public static void menuSelection(int userinput_value){
UserInteraction ui=new UserInteraction();
Employee e=new Employee();
int value=userinput_value;
switch(value)
{
case 1:
ui.AddEmployee();
break;
case 2:
ui.ModifyEmployee();
break;
case 3:
ui.RemoveEmployee();
break;
case 4:
ui.getAllEmployee();
break;
case 5:
ui.SearchEmployee();
break;
//default:
//System.out.println("wrong input");
}
}
}
|
package com.scalefocus.java.domain.local;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name = "series")
public class Series extends Projection{
@OneToMany(
mappedBy = "series",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Season> seasons = new HashSet<>();
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinColumn(name = "director_id")
private Director director;
@ManyToMany(mappedBy = "series",cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private Set<Writer> writers = new HashSet<>();
@ManyToMany(mappedBy = "series", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private Set<Actor> actors = new HashSet<>();
public void addSeason(Season season) {
seasons.add(season);
season.setSeries(this);
}
public void removeSeason(Season season) {
seasons.remove(season);
season.setSeries(null);
}
public void addActor(Actor actor) {
actors.add(actor);
actor.getSeries().add(this);
}
public void removeActor(Actor actor) {
actors.remove(actor);
actor.setSeries(null);
}
public void addWriter(Writer writer) {
writers.add(writer);
writer.getSeries().add(this);
}
}
|
package com.model.pojo;
public class Friend {
private int id;
private String frindName;
private int rationLevel;
private String knowTime;
private String knowWay;
private String myname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFrindName() {
return frindName;
}
public void setFrindName(String frindName) {
this.frindName = frindName;
}
public int getRationLevel() {
return rationLevel;
}
public void setRationLevel(int rationLevel) {
this.rationLevel = rationLevel;
}
public String getKnowTime() {
return knowTime;
}
public void setKnowTime(String knowTime) {
this.knowTime = knowTime;
}
public String getKnowWay() {
return knowWay;
}
public void setKnowWay(String knowWay) {
this.knowWay = knowWay;
}
public String getMyname() {
return myname;
}
public void setMyname(String myname) {
this.myname = myname;
}
}
|
package com.gxtc.huchuan.ui.circle.file.folder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.recyclerview.RecyclerView;
import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.FolderListAdapter;
import com.gxtc.huchuan.bean.CircleBean;
import com.gxtc.huchuan.bean.CircleFileBean;
import com.gxtc.huchuan.bean.FolderBean;
import com.gxtc.huchuan.bean.MineCircleBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.dialog.CircleFileShieldDialogV5;
import com.gxtc.huchuan.pop.PopFileAction;
import com.gxtc.huchuan.ui.circle.dynamic.SyncIssueInCircleActivity;
import com.gxtc.huchuan.ui.circle.file.CircleFileActivity;
import com.gxtc.huchuan.ui.circle.file.filelist.FileAuditActivity;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.widget.MyActionSheetDialog;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by Gubr on 2017/3/30.
*/
public class FolderListActivity extends BaseTitleActivity implements FolderListContract.View,
View.OnClickListener, BaseRecyclerAdapter.OnReItemOnClickListener {
private static final String TAG = "FolderListActivity";
public static final int LOGINREQUEST = 1;
private final int GOTO_CIRCLE_REQUESTCODE = 1 << 3;
@BindView(R.id.recyclerview) RecyclerView recyclerview;
private String title;
private FolderListContract.Presenter presenter;
private FolderListAdapter mFolderListAdapter;
private String type;
private int groupId;
private String mUsercode;
private int mMemberType;
private CircleBean mBean;
private AlertDialog dialog;
private CircleFileShieldDialogV5 shieldDialog;
private List<Integer> mGroupIds = new ArrayList<>();//同步的圈子id
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_folde_list);
}
@Override
public void initView() {
new FolderListPresenter(this);
Intent intent = getIntent();
groupId = intent.getIntExtra("data", -1);
mUsercode = intent.getStringExtra("usercode");
mMemberType = intent.getIntExtra("memberType", 0);
mBean = (CircleBean) intent.getSerializableExtra("bean");
getBaseHeadView().showBackButton(this);
if (mMemberType != 0) {
getBaseHeadView().showHeadRightImageButton(R.drawable.person_circle_manage_icon_add, this);
}
getBaseHeadView().showTitle("文件");
recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
recyclerview.setLoadMoreView(R.layout.model_footview_loadmore);
}
@Override
public void initListener() {
recyclerview.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
presenter.getData(true, groupId, mFolderListAdapter.getItemCount(),15);
}
});
}
@Override
public void initData() {
presenter.getData(false, groupId, 0,15);
}
private void showChangeFolderDialog(final FolderBean bean) {
DialogUtil.showTopicInputDialog(this, "填写文件夹名", "请填写新的文件夹名", bean.getFolderName(),
new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = (String) v.getTag();
if (TextUtils.isEmpty(str)) {
} else {
presenter.createFolder(UserManager.getInstance().getToken(),
bean.getGroupId(), str, "" + bean.getId());
}
}
});
}
private void showCreateFolderDialog() {
DialogUtil.showTopicInputDialog(this, "填写文件夹名", "请填写新的文件夹名", null,
new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = (String) v.getTag();
if (TextUtils.isEmpty(str)) {
} else {
presenter.createFolder(UserManager.getInstance().getToken(), groupId,
str, null);
}
}
});
}
private void showSysDialog() {
DialogUtil.showSysDialog(this,
new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_issue_tongbu:
Intent intent = new Intent(FolderListActivity.this, SyncIssueInCircleActivity.class);
intent.putExtra("default", "-1");
FolderListActivity. this.startActivityForResult(intent, 666);
break;
case R.id.tv_cancel:
break;
case R.id.tv_sure:
break;
}
}
});
}
@Override
@OnClick({R.id.tv_input_search})
public void onClick(View view) {
switch (view.getId()) {
case R.id.headBackButton:
finish();
break;
case R.id.HeadRightImageButton:
if (mMemberType == 0) {
showCreateFolderDialog();
}else{
showCreateFileDialog(view);
}
break;
case R.id.tv_input_search:
//这里跳到空的文件列表进行搜索
CircleFileActivity.startActivity(this, mBean, -1, 1);
break;
}
}
private PopFileAction mPopComment;
private void showEditDialog(View v,final FolderBean bean){
if(mPopComment == null){
mPopComment = new PopFileAction(this,false);
}
int[] location = new int[2];
v.getLocationOnScreen(location);
int dalta = (getResources().getDimensionPixelSize(R.dimen.px700dp) - v.getWidth()) / 2;
mPopComment.showAtLocation(v, Gravity.CENTER|Gravity.TOP, location[0] - dalta, location[1] - 30);
mPopComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sys_btn:
showSysDialog();
break;
case R.id.move_btn:
break;
case R.id.rename_btn:
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showChangeFolderDialog(bean);
}
} else {
showLoginDialog();
}
break;
case R.id.down_btn:
break;
case R.id.delete_btn:
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showDeleteFolderDialog(FolderListActivity.this, bean);
}
} else {
showLoginDialog();
}
break;
}
}
});
}
@Override
public void showFolderData(final List<FolderBean> datas) {
if (mFolderListAdapter == null) {
mFolderListAdapter = new FolderListAdapter(this, datas, R.layout.item_circle_folder,
recyclerview);
mFolderListAdapter.setOnReItemOnLongClickListener(new BaseRecyclerAdapter.OnReItemOnLongClickListener() {
@Override
public void onItemLongClick(View v, int position) {
showEditDialog(v,datas.get(position));
}
});
mFolderListAdapter.setFolderClickNameClickListener(
new FolderListAdapter.OnFolderClickListener() {
@Override
public void onOpenFolderClick(FolderBean bean) {
CircleFileActivity.startActivity(FolderListActivity.this, mBean,
bean.getId(), 2);
}
@Override
public void onRenameClick(View view, FolderBean bean) {
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showChangeFolderDialog(bean);
}
} else {
showLoginDialog();
}
}
@Override
public void onDeleteClick(View view, FolderBean bean) {
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showDeleteFolderDialog(FolderListActivity.this, bean);
}
} else {
showLoginDialog();
}
}
});
recyclerview.setAdapter(mFolderListAdapter);
}else{
recyclerview.notifyChangeData(datas,mFolderListAdapter);
}
}
private void showLoginDialog() {
}
@Override
public void showLoMore(List<FolderBean> datas) {
if (mFolderListAdapter != null) {
recyclerview.changeData(datas, mFolderListAdapter);
}
}
@Override
public void setPresenter(FolderListContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
@Override
public void showLoadFinish() {
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {
getBaseEmptyView().showEmptyView();
}
@Override
public void showReLoad() {
}
@Override
public void loadFinish() {
if (recyclerview != null) {
recyclerview.loadFinish();
}
}
@Override
public void showFileData(List<CircleFileBean> datas) {
}
@Override
public void createFolder(int grouid, String folderName, String fileid) {
List<FolderBean> list = mFolderListAdapter.getList();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId() == Integer.valueOf(fileid)) {
list.get(i).setFolderName(folderName);
recyclerview.notifyItemChanged(i);
return;
}
}
}
private void showCreateFileDialog(View view){
shieldDialog = new CircleFileShieldDialogV5(this);
shieldDialog
.showAnim(null)
.dismissAnim(null)
.anchorView(view)
.dimEnabled(true)
.dimEnabled(false)
.gravity(Gravity.BOTTOM)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_create_folder:
showCreateFolderDialog();
break;
case R.id.tv_audit_file:
FileAuditActivity.startActivity(FolderListActivity.this,mBean,4);
break;
}
}
});
shieldDialog.show();
}
@Override
public void createFolder(FolderBean bean) {
if (mFolderListAdapter != null && mFolderListAdapter.getItemCount() > 0) {
mFolderListAdapter.getList().add(0, bean);
recyclerview.notifyChangeData();
} else {
ArrayList<FolderBean> folderBeen = new ArrayList<>();
folderBeen.add(bean);
mFolderListAdapter = new FolderListAdapter(this, folderBeen,
R.layout.item_circle_folder, recyclerview);
mFolderListAdapter.setFolderClickNameClickListener(
new FolderListAdapter.OnFolderClickListener() {
@Override
public void onOpenFolderClick(FolderBean bean) {
Log.d(TAG, "onOpenFolderClick: "+mBean.getMemberType());
CircleFileActivity.startActivity(FolderListActivity.this, mBean,
bean.getId(), 2);
// if (mBean.getMemberType()==0){
// }else{
// Log.d(TAG, "onOpenFolderClick: 打开FileAUditActivity");
// FileAuditActivity.startActivity(FolderListActivity.this,mBean,bean.getId());
// }
}
@Override
public void onRenameClick(View view, FolderBean bean) {
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showChangeFolderDialog(bean);
}
} else {
showLoginDialog();
}
}
@Override
public void onDeleteClick(View view, FolderBean bean) {
if (UserManager.getInstance().isLogin()) {
if (mMemberType != 0) {
showDeleteFolderDialog(FolderListActivity.this, bean);
}
} else {
showLoginDialog();
}
}
});
recyclerview.setAdapter(mFolderListAdapter);
}
}
public void showDeleteFolderDialog(final Context context, final FolderBean bean) {
ArrayList<String> itemList = new ArrayList<String>();
itemList.add("删除文件夹以及里面的文件");
final String[] contents = new String[itemList.size()];
final MyActionSheetDialog dialog = new MyActionSheetDialog(context,
itemList.toArray(contents), null);
dialog.cancelMarginTop(1).
isTitleShow(false).titleTextSize_SP(14.5f).widthScale(1f).cancelMarginBottom(
0).cornerRadius(0f).dividerHeight(1).itemTextColor(
getResources().getColor(R.color.black)).cancelText(
getResources().getColor(R.color.black)).cancelText("取消").show();
dialog.setOnOperItemClickL(new OnOperItemClickL() {
@Override
public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
switch (position) {
case 0:
//删除文件夹以及里面的文件
removeFolder(bean);
break;
}
String animType = contents[position];
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void removeFolder(final FolderBean bean) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = DialogUtil.showInputDialog(this, false, "", "确认删除文件夹以及里面的文件?", new View.OnClickListener() {
@Override
public void onClick(View v) {
if (UserManager.getInstance().isLogin()) {
presenter.deleteFolder(UserManager.getInstance().getToken(),groupId,bean.getId());
} else {
Toast.makeText(FolderListActivity.this, "登录后才能操作", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
}
@Override
public void deleteFolder(int grouid, int folderId) {
List<FolderBean> list = mFolderListAdapter.getList();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId()==folderId) {
list.remove(i);
recyclerview.notifyChangeData();
}
}
}
@Override
public void saveFolder(int fileId, String name, int fileName) {
}
@Override
public void showError(String info) {
getBaseEmptyView().showEmptyContent(info);
}
@Override
public void showNetError() {
getBaseEmptyView().showNetWorkView(this);
}
@Override
public void onItemClick(View v, int position) {
if (mFolderListAdapter != null) {
FolderBean folderBean = mFolderListAdapter.getList().get(position);
CircleFileActivity.startActivity(this, mBean, folderBean.getId(), 2);
}
}
public void onViewClicked() {}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
recyclerview.reLoadFinish();
presenter.getData(true, groupId, 0,15);
}
if (requestCode == 666 && resultCode == Constant.ResponseCode.ISSUE_TONG_BU) {
ArrayList<MineCircleBean> selectData = data.getParcelableArrayListExtra("select_data");
mGroupIds.clear();
if (selectData.size() > 0) {
ArrayList<String> listGroupName = new ArrayList<>();
for (MineCircleBean bean1 : selectData) {
listGroupName.add(bean1.getGroupName());
mGroupIds.add(bean1.getId());
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(presenter != null) presenter.destroy();
}
}
|
package com.abd.zaher88.androidmovieapp.DataObject;
/**
* Created by Zaher on 2016-07-09.
*/
public class MovieAdapter {
}
|
import edu.princeton.cs.algs4.StdRandom;
public class HelloWorld {
public static void main(String[] args) {
int[] perm = StdRandom.permutation(5);
for (int index: perm) {
System.out.println(index);
}
int[][] m = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
System.out.println(m[3][3]);
}
}
|
package com.lasform.core.business.repository;
import com.lasform.core.model.entity.LocationType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LocationTypeRepository extends JpaRepository<LocationType,Long> {
}
|
/*
* Created on 20/08/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.modules.product.prodsubasset.valueobject;
import java.math.BigInteger;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
/**
* @author rcoelho
*/
public class BaseProdSubAssetListFncVO extends BaseODSFncVO
{
/**
* Constante do Qualificador que descreve o nome do campo do Código da
* Sub Classe da tela
*/
public static final String C_PROD_SUBASSET_CODE_DESCRIPTION = "Código da Sub Classe";
/**
* Constante do Qualificador que descreve o nome do campo da Descrição de
* Sub Classe da tela
*/
public static final String C_PROD_SUBASSET_TEXT_DESCRIPTION = "Descrição da Sub Classe";
/*
* Resultado da consulta
*/
private DataSet m_results;
/*
* Comment for <code> m_prodSubAssetCode </code> @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private BigInteger m_prodSubAssetCodeSrc;
/*
* Comment for <code> m_prodSubAssetText </code> @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_prodSubAssetTextSrc;
/**
* @return Returns the m_results.
*/
public DataSet getResults()
{
return m_results;
}
/**
* @param m_results The m_results to set.
*/
public void setResults( DataSet results_ )
{
this.m_results = results_;
}
/**
* @return Returns prodSubAssetCodeSrc.
*/
public BigInteger getProdSubAssetCodeSrc()
{
return m_prodSubAssetCodeSrc;
}
/**
* @param prodSubAssetCodeSrc_ Field prodSubAssetCodeSrc to be setted.
*/
public void setProdSubAssetCodeSrc( BigInteger prodSubAssetCodeSrc_ )
{
m_prodSubAssetCodeSrc = prodSubAssetCodeSrc_;
}
/**
* @return Returns prodSubAssetTextSrc.
*/
public String getProdSubAssetTextSrc()
{
return m_prodSubAssetTextSrc;
}
/**
* @param prodSubAssetTextSrc_ Field prodSubAssetTextSrc to be setted.
*/
public void setProdSubAssetTextSrc( String prodSubAssetTextSrc_ )
{
m_prodSubAssetTextSrc = prodSubAssetTextSrc_;
}
}
|
package com.qumla.service.test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.qumla.domain.PagingFilter;
import com.qumla.domain.search.SearchResult;
import com.qumla.domain.tag.Tag;
import com.qumla.service.impl.TagDaoMapper;
import com.qumla.service.impl.TagServiceImpl;
import com.qumla.web.controller.RequestWrapper;
public class TagDaoTest extends AbstractTest{
@Before
public void before() {
super.before(TagDaoMapper.class);
}
@Test
public void saveTag(){
TagDaoMapper mapper=(TagDaoMapper)getMapper(TagDaoMapper.class);
Tag t=new Tag();
t.setTag("c");
t.setType(1);
t.setCount(10);
t.setCountry("HU");
t.setLanguage("english");
mapper.insertTag(t);
Tag t2=mapper.findOne(t.getId());
Assert.assertTrue(t2.getCount()==10);
Assert.assertTrue(t2.getTag().equals("c"));
Assert.assertTrue(t2.getType()==1);
}
@Test
public void incrementDecrementTag(){
TagDaoMapper mapper=(TagDaoMapper)getMapper(TagDaoMapper.class);
mapper.incrementTag("#qumla","HU");
mapper.decrementTag("#qumla","HU");
}
@Test
public void incrementTag(){
TagDaoMapper mapper=(TagDaoMapper)getMapper(TagDaoMapper.class);
TagServiceImpl tsimp=new TagServiceImpl();
tsimp.setMapper(mapper);
Set<String> tags=new HashSet<String>();
tags.add("#ttttttttt");
tags.add("#ttttttttt2");
tsimp.setTags(tags, "HU", "english");
tags=new HashSet<String>();
tags.add("#ttttttttt");
tsimp.setTags(tags, "EN", "hungarian");
tsimp.setTags(tags, "EN", "hungarian");
PagingFilter pf=new PagingFilter(RequestWrapper.getSession().getCountry());
pf.setQuery("#tttt");
pf.setCountryCode("HU");
List<SearchResult> sr=mapper.freeTextQueryTag(pf);
Assert.assertTrue(sr.size()==3);
pf.setQuery("#tttt");
pf.setCountryCode("EN");
sr=mapper.freeTextQueryTag(pf);
Assert.assertTrue(sr.size()==3);
boolean ok=false;
for (SearchResult searchResult : sr) { // there should be one with count 2
Tag t=mapper.findOne(searchResult.getId());
if(t.getCount()==2) ok=true;
}
Assert.assertTrue(ok);
}
@Test
public void testTag(){
TagServiceImpl ts=new TagServiceImpl();
Set<String> tags=ts.parseTags("dfs df sdf sdfs ");
Assert.assertTrue(tags.size()==0);
tags=ts.parseTags("dfs #df #4dd534 #33333 ");
Assert.assertTrue(tags.size()==2);
}
@Test
public void findTag(){
TagDaoMapper mapper=(TagDaoMapper)getMapper(TagDaoMapper.class);
PagingFilter pf=new PagingFilter(RequestWrapper.getSession().getCountry());
pf.setPopular(true);
List<Tag> popular=mapper.getPopularTags(pf);
Assert.assertTrue(popular.size()>0);
pf=new PagingFilter(RequestWrapper.getSession().getCountry());
pf.setQuery("#qumla");
List<Tag> result=mapper.queryTags(pf);
Assert.assertTrue(result.size()>0);
}
@Test
public void freeSearchTag(){
TagDaoMapper mapper=(TagDaoMapper)getMapper(TagDaoMapper.class);
PagingFilter pf=new PagingFilter(RequestWrapper.getSession().getCountry());
pf=new PagingFilter(RequestWrapper.getSession().getCountry());
pf.setQuery("#qumla");
List<SearchResult> result=mapper.freeTextQueryTag(pf);
Assert.assertTrue(result.size()>0);
}
@Test
public void parseTag(){
TagServiceImpl ts=new TagServiceImpl();
Set<String> tags=ts.parseTags("dfs df sdf sdfs ");
Assert.assertTrue(tags.size()==0);
tags=ts.parseTags("dfs #df sdf #4dd534 sdfs ");
Assert.assertTrue(tags.size()==2);
}
}
|
/*
* 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 controller;
import model.Oogmeting;
import model.oogmetingDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author viresh
*/
@WebServlet(name = "InsertOogmeting", urlPatterns = {"/InsertOogmeting"})
public class insertOogmetingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn;
String strklant = (String) request.getParameter("klant");
int klant = Integer.parseInt(strklant);
String breekkracht = (String) request.getParameter("breekkracht");
String brekingshoek = (String) request.getParameter("brekingshoek");
String sterkte = (String) request.getParameter("sterkte");
try {
conn = database.getMySQLConnection();
String errorString = null;
Oogmeting oogmeting;
oogmeting = new Oogmeting(klant,breekkracht,brekingshoek,sterkte);
if (errorString == null) {
oogmetingDao.insertOogmeting((com.mysql.jdbc.Connection) conn, oogmeting);
if (errorString == null) {
response.sendRedirect(request.getContextPath() + "/oogmeting");
request.setAttribute("errorString", errorString);
request.setAttribute("oogmeting", oogmeting);
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(insertOogmetingServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(insertOogmetingServlet.class.getName()).log(Level.SEVERE, null, ex);
}
// Store infomation to request attribute, before forward to views.
}
} |
package com.mpls.v2.controller;
import com.mpls.v2.dto.TechnologiesDto;
import com.mpls.v2.model.Technologies;
import com.mpls.v2.service.TechnologiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import static com.mpls.v2.dto.utils.builder.Builder.map;
@RestController
@RequestMapping("/technologies")
public class TechnologiesController {
@Autowired
TechnologiesService technologiesService;
@PostMapping("/save")
private ResponseEntity<TechnologiesDto> save(@RequestBody TechnologiesDto technologies) {
return new ResponseEntity<>(map(technologiesService.save(map(technologies, Technologies.class)), TechnologiesDto.class), HttpStatus.OK);
}
@GetMapping("/find-all")
private ResponseEntity<List<TechnologiesDto>> getList() {
return new ResponseEntity<>(technologiesService.findAll().stream()
.map(technologies -> map(technologies, TechnologiesDto.class)).collect(Collectors.toList()), HttpStatus.OK);
}
@GetMapping("/find-one/{id}")
private ResponseEntity<TechnologiesDto> findOne(@PathVariable Long id) {
return new ResponseEntity<>(map(technologiesService.findOne(id), TechnologiesDto.class), HttpStatus.OK);
}
@DeleteMapping("/delete/{id}")
private ResponseEntity delete(@PathVariable Long id) {
return new ResponseEntity(technologiesService.delete(id) ? HttpStatus.OK : HttpStatus.CONFLICT);
}
@GetMapping("/find-by-name")
private ResponseEntity<TechnologiesDto> findByName(@RequestParam String name){
return new ResponseEntity<>(map(technologiesService.findByName(name),TechnologiesDto.class),HttpStatus.OK);
}
}
|
package org.kuali.ole.describe.controller;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.kuali.ole.OLEConstants;
import org.kuali.ole.OleEditorResponseHandler;
import org.kuali.ole.describe.bo.OleWorkBibDocument;
import org.kuali.ole.describe.bo.OleWorkEHoldingsDocument;
import org.kuali.ole.describe.bo.OleWorkHoldingsDocument;
import org.kuali.ole.describe.form.WorkbenchForm;
import org.kuali.ole.describe.service.DiscoveryHelperService;
import org.kuali.ole.describe.service.DocstoreHelperService;
import org.kuali.ole.docstore.discovery.model.SearchCondition;
import org.kuali.ole.docstore.discovery.model.SearchParams;
import org.kuali.ole.docstore.discovery.service.QueryService;
import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
import org.kuali.ole.docstore.model.bo.*;
import org.kuali.ole.docstore.model.enums.DocCategory;
import org.kuali.ole.docstore.model.enums.DocFormat;
import org.kuali.ole.docstore.model.enums.DocType;
import org.kuali.ole.docstore.model.xmlpojo.ingest.Content;
import org.kuali.ole.docstore.model.xmlpojo.ingest.Request;
import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument;
import org.kuali.ole.docstore.model.xmlpojo.ingest.Response;
import org.kuali.ole.docstore.model.xmlpojo.work.einstance.oleml.EHoldings;
import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
import org.kuali.ole.docstore.model.xstream.work.oleml.WorkEHoldingOlemlRecordProcessor;
import org.kuali.ole.pojo.OleBibRecord;
import org.kuali.ole.pojo.OleEditorResponse;
import org.kuali.ole.select.businessobject.OleCopy;
import org.kuali.ole.select.document.OLEEResourceRecordDocument;
import org.kuali.ole.select.service.impl.OleExposedWebServiceImpl;
import org.kuali.ole.service.OLEEResourceSearchService;
import org.kuali.ole.sys.context.SpringContext;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.api.identity.PersonService;
import org.kuali.rice.kim.api.permission.PermissionService;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.web.controller.UifControllerBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: PP7788
* Date: 11/21/12
* Time: 2:45 PM
* To change this template use File | Settings | File Templates.
*/
@Controller
@RequestMapping(value = "/describeworkbenchcontroller")
public class WorkbenchController extends UifControllerBase {
private static final Logger LOG = Logger.getLogger(WorkbenchController.class);
private OLEEResourceSearchService oleEResourceSearchService;
private DocumentService documentService;
private int totalRecCount;
private int start;
private int pageSize;
public int getTotalRecCount() {
return totalRecCount;
}
public void setTotalRecCount(int totalRecCount) {
this.totalRecCount = totalRecCount;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public boolean getWorkbenchPreviousFlag() {
if (this.start == 0)
return false;
return true;
}
public boolean getWorkbenchNextFlag() {
if (this.start + this.pageSize < this.totalRecCount)
return true;
return false;
}
public String getWorkbenchPageShowEntries() {
return "Showing " + ((this.start == 0) ? 1 : this.start + 1) + " to "
+ (((this.start + this.pageSize) > this.totalRecCount) ? this.totalRecCount : (this.start + this.pageSize))
+ " of " + this.totalRecCount + " entries";
}
public OLEEResourceSearchService getOleEResourceSearchService() {
if (oleEResourceSearchService == null) {
oleEResourceSearchService = GlobalResourceLoader.getService(OLEConstants.OLEEResourceRecord.ERESOURSE_SEARCH_SERVICE);
}
return oleEResourceSearchService;
}
public DocumentService getDocumentService() {
if (this.documentService == null) {
this.documentService = KRADServiceLocatorWeb.getDocumentService();
}
return this.documentService;
}
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
boolean hasSearchPermission = false;
private String eResourceId;
private String tokenId;
@Override
protected UifFormBase createInitialForm(HttpServletRequest httpServletRequest) {
return new WorkbenchForm();
}
/**
* This method converts UifFormBase to WorkbenchForm
*
* @param form
* @param result
* @param request
* @param response
* @return ModelAndView
*/
@Override
@RequestMapping(params = "methodToCall=start")
public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Inside the workbenchForm start method");
WorkbenchForm workbenchForm = (WorkbenchForm) form;
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
workbenchForm.setShowRequestXML(false);
if(request.getParameter(OLEConstants.E_RESOURCE_ID) != null) {
eResourceId = request.getParameter(OLEConstants.E_RESOURCE_ID);
}
if(request.getParameter(OLEConstants.TOKEN_ID) != null) {
tokenId = request.getParameter(OLEConstants.TOKEN_ID);
}
if (workbenchForm.getSearchParams().getDocType() == null) {
workbenchForm.getSearchParams().setDocType(DocType.BIB.getDescription());
}
String eInstance = request.getParameter(OLEConstants.E_INSTANCE);
if (eInstance != null && eInstance.equalsIgnoreCase(OLEConstants.LINK_EXISTING_INSTANCE)) {
//workbenchForm.getSearchParams().setDocType(DocType.HOLDINGS.getDescription());
workbenchForm.setLinkExistingInstance(eInstance);
}
String docType = workbenchForm.getSearchParams().getDocType();
boolean hasSearchPermission = canSearch(GlobalVariables.getUserSession().getPrincipalId());
if (!hasSearchPermission && docType.equalsIgnoreCase(OLEConstants.BIB_DOC_TYPE)) {
boolean hasLinkPermission = canLinkBibForRequisition(GlobalVariables.getUserSession().getPrincipalId());
/*boolean hasPermission = canSearchBib(GlobalVariables.getUserSession().getPrincipalId());*/
if (!hasLinkPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}
/*} else if (!hasSearchPermission && docType.equalsIgnoreCase(OLEConstants.ITEM_DOC_TYPE)) {
boolean hasPermission = canSearchItem(GlobalVariables.getUserSession().getPrincipalId());
if (!hasPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}*/
} else if (!hasSearchPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
workbenchForm.setShowRequestXML(false);
workbenchForm.setMessage(null);
GlobalVariables.getMessageMap().clearErrorMessages();
return super.navigate(workbenchForm, result, request, response);
}
/**
* Used for Test-case
*
* @param result
* @param request
* @param response
* @param workbenchForm
* @return ModelAndView
*/
protected ModelAndView callSuper(BindingResult result, HttpServletRequest request, HttpServletResponse response, WorkbenchForm workbenchForm) {
return super.navigate(workbenchForm, result, request, response);
}
/*private boolean canSearchBib(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.SEARCH_BIB);
}
private boolean canSearchItem(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.SEARCH_ITEM);
}*/
private boolean canSearch(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.DESC_WORKBENCH_SEARCH);
}
private boolean canLinkBibForRequisition(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.SELECT_NMSPC, OLEConstants.LINK_EXISTING_BIB);
}
/**
* @param form
* @param result
* @param request
* @param response
* @return
*/
@RequestMapping(params = "methodToCall=search")
public ModelAndView search(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.info("Inside Search Method");
WorkbenchForm workbenchForm = (WorkbenchForm) form;
workbenchForm.setMessage(null);
String docType = workbenchForm.getSearchParams().getDocType();
boolean hasSearchPermission = canSearch(GlobalVariables.getUserSession().getPrincipalId());
if (!hasSearchPermission && docType.equalsIgnoreCase(OLEConstants.BIB_DOC_TYPE)) {
boolean hasLinkPermission = canLinkBibForRequisition(GlobalVariables.getUserSession().getPrincipalId());
/*boolean hasPermission = canSearchBib(GlobalVariables.getUserSession().getPrincipalId());*/
if (!hasLinkPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}
/*} else if (!hasSearchPermission && docType.equalsIgnoreCase(OLEConstants.ITEM_DOC_TYPE)) {
boolean hasPermission = canSearchItem(GlobalVariables.getUserSession().getPrincipalId());
if (!hasPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}*/
} else if (!hasSearchPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return super.navigate(workbenchForm, result, request, response);
}
workbenchForm.setShowRequestXML(false);
try {
QueryService queryService = QueryServiceImpl.getInstance();
SearchParams searchParams = workbenchForm.getSearchParams();
searchParams.setRows(workbenchForm.getPageSize());
searchParams.setStart(workbenchForm.getStart());
if (workbenchForm.getSearchParams().getDocType().equalsIgnoreCase(DocType.BIB.getDescription())) {
workbenchForm.getSearchParams().setDocCategory(DocCategory.WORK.getCode());
workbenchForm.getSearchParams().setDocFormat("ALL");
workbenchForm.setShowExport(true);
workbenchForm.setLinkToERSFlag(true);
List<OleWorkBibDocument> oleWorkBibDocumentList = new ArrayList<OleWorkBibDocument>();
List<WorkBibDocument> workBibDocumentList = queryService.getBibDocuments(searchParams);
if (workBibDocumentList.isEmpty()) {
GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DESCRIBE_SEARCH_MESSAGE);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
return super.navigate(workbenchForm, result, request, response);
}
for (WorkBibDocument workBibDocument : workBibDocumentList) {
OleWorkBibDocument oleWorkBibDocument = new OleWorkBibDocument();
oleWorkBibDocument.setDocFormat(workBibDocument.getDocFormat());
oleWorkBibDocument.setId(workBibDocument.getId());
oleWorkBibDocument.setTitle(workBibDocument.getTitle());
oleWorkBibDocument.setLocalIds(workBibDocument.getLocalIds());
oleWorkBibDocument.setAuthor(workBibDocument.getAuthor());
oleWorkBibDocument.setStaffOnlyFlag(workBibDocument.getStaffOnlyFlag());
oleWorkBibDocument.setPublicationDate(workBibDocument.getPublicationDate());
if (eResourceId != null) {
oleWorkBibDocument.setOleERSIdentifier(eResourceId);
}
if (tokenId != null) {
oleWorkBibDocument.setTokenId(tokenId);
}
oleWorkBibDocumentList.add(oleWorkBibDocument);
}
workbenchForm.setWorkBibDocumentList(oleWorkBibDocumentList);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
setPageNextPreviousAndEntriesInfo(workbenchForm);
request.getSession().setAttribute("oleWorkBibDocumentList", oleWorkBibDocumentList);
// request.setAttribute("oleWorkBibDocumentList",oleWorkBibDocumentList);
}
if (workbenchForm.getSearchParams().getDocType().equalsIgnoreCase(DocType.HOLDINGS.getCode())) {
workbenchForm.getSearchParams().setDocCategory(DocCategory.WORK.getCode());
workbenchForm.getSearchParams().setDocFormat(DocFormat.OLEML.getCode());
workbenchForm.setShowExport(true);
List<OleWorkHoldingsDocument> oleWorkHoldingsDocuments = new ArrayList<>();
List<WorkHoldingsDocument> workHoldingsDocuments = queryService.getHoldingDocuments(searchParams);
if (workHoldingsDocuments.isEmpty()) {
GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DESCRIBE_SEARCH_MESSAGE);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
return super.navigate(workbenchForm, result, request, response);
}
for (WorkHoldingsDocument workHoldingsDocument : workHoldingsDocuments) {
OleWorkHoldingsDocument oleWorkHoldingsDocument = new OleWorkHoldingsDocument();
oleWorkHoldingsDocument.setBibTitle(workHoldingsDocument.getBibTitle());
oleWorkHoldingsDocument.setBibIdentifier(workHoldingsDocument.getBibIdentifier());
oleWorkHoldingsDocument.setBibUUIDList(workHoldingsDocument.getBibUUIDList());
oleWorkHoldingsDocument.setCallNumber(workHoldingsDocument.getCallNumber());
oleWorkHoldingsDocument.setCallNumberPrefix(workHoldingsDocument.getCallNumberPrefix());
oleWorkHoldingsDocument.setCallNumberType(workHoldingsDocument.getCallNumberType());
oleWorkHoldingsDocument.setCopyNumber(workHoldingsDocument.getCopyNumber());
oleWorkHoldingsDocument.setHoldingsIdentifier(workHoldingsDocument.getHoldingsIdentifier());
oleWorkHoldingsDocument.setStaffOnlyFlag(workHoldingsDocument.getStaffOnlyFlag());
oleWorkHoldingsDocument.setLinkedBibCount(workHoldingsDocument.getLinkedBibCount());
oleWorkHoldingsDocument.setLocalId(workHoldingsDocument.getLocalId());
oleWorkHoldingsDocument.setLocationName(workHoldingsDocument.getLocationName());
oleWorkHoldingsDocument.setInstanceIdentifier(workHoldingsDocument.getInstanceIdentifier());
oleWorkHoldingsDocuments.add(oleWorkHoldingsDocument);
}
workbenchForm.setWorkHoldingsDocumentList(oleWorkHoldingsDocuments);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
setPageNextPreviousAndEntriesInfo(workbenchForm);
}
if (workbenchForm.getSearchParams().getDocType().equalsIgnoreCase(DocType.ITEM.getCode())) {
workbenchForm.getSearchParams().setDocCategory(DocCategory.WORK.getCode());
workbenchForm.getSearchParams().setDocFormat(DocFormat.OLEML.getCode());
List<WorkItemDocument> workItemDocuments = queryService.getItemDocuments(searchParams);
if (workItemDocuments.isEmpty()) {
GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DESCRIBE_SEARCH_MESSAGE);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
return super.navigate(workbenchForm, result, request, response);
}
workbenchForm.setWorkItemDocumentList(workItemDocuments);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
setPageNextPreviousAndEntriesInfo(workbenchForm);
}
if (workbenchForm.getSearchParams().getDocType().equalsIgnoreCase(DocType.EHOLDINGS.getCode())) {
workbenchForm.getSearchParams().setDocCategory(DocCategory.WORK.getCode());
workbenchForm.getSearchParams().setDocFormat(DocFormat.OLEML.getCode());
workbenchForm.setShowExport(true);
List<WorkEHoldingsDocument> workEHoldingsDocuments = queryService.getEHoldingsDocuments(searchParams);
if (workEHoldingsDocuments.isEmpty()) {
GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DESCRIBE_SEARCH_MESSAGE);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
return super.navigate(workbenchForm, result, request, response);
}
List<OleWorkEHoldingsDocument> oleWorkEHoldingsDocuments = new ArrayList<>();
for (WorkEHoldingsDocument workEHoldingsDocument : workEHoldingsDocuments) {
OleWorkEHoldingsDocument oleWorkEHoldingsDocument = new OleWorkEHoldingsDocument();
oleWorkEHoldingsDocument.setAccessStatus(workEHoldingsDocument.getAccessStatus());
oleWorkEHoldingsDocument.setBibIdentifier(workEHoldingsDocument.getBibIdentifier());
oleWorkEHoldingsDocument.setHoldingsIdentifier(workEHoldingsDocument.getHoldingsIdentifier());
oleWorkEHoldingsDocument.setImprint(workEHoldingsDocument.getImprint());
oleWorkEHoldingsDocument.setInstanceIdentifier(workEHoldingsDocument.getInstanceIdentifier());
oleWorkEHoldingsDocument.setLocalId(workEHoldingsDocument.getLocalId());
oleWorkEHoldingsDocument.setPlatForm(workEHoldingsDocument.getPlatForm());
oleWorkEHoldingsDocument.setStatisticalCode(workEHoldingsDocument.getStatisticalCode());
oleWorkEHoldingsDocument.setDocType(workEHoldingsDocument.getDocType());
oleWorkEHoldingsDocument.setId(workEHoldingsDocument.getId());
oleWorkEHoldingsDocument.setDocCategory(workEHoldingsDocument.getDocCategory());
oleWorkEHoldingsDocuments.add(oleWorkEHoldingsDocument);
}
workbenchForm.setWorkEHoldingsDocumentList(oleWorkEHoldingsDocuments);
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
setPageNextPreviousAndEntriesInfo(workbenchForm);
}
} catch (Exception e) {
//e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
LOG.error("Workbenchcontroller Search Exception:" + e);
}
// return getUIFModelAndView(workbenchForm);
return navigate(workbenchForm, result, request, response);
}
/**
* Enable, disable the next and previous and also show the message for number of entries
* @param workbenchForm
* @return
*/
public void setPageNextPreviousAndEntriesInfo(WorkbenchForm workbenchForm) {
this.totalRecCount = workbenchForm.getSearchParams().getTotalRecCount();
this.start = workbenchForm.getSearchParams().getStart();
this.pageSize = workbenchForm.getSearchParams().getRows();
workbenchForm.setPreviousFlag(getWorkbenchPreviousFlag());
workbenchForm.setNextFlag(getWorkbenchNextFlag());
workbenchForm.setPageShowEntries(getWorkbenchPageShowEntries());
}
/**
* search to Get the next documents
* @param form
* @param result
* @param request
* @param response
* @return
*/
@RequestMapping(params = "methodToCall=nextSearch")
public ModelAndView nextSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the nextSearch method");
WorkbenchForm workbenchForm = (WorkbenchForm) form;
SearchParams searchParams = workbenchForm.getSearchParams();
QueryService queryService = QueryServiceImpl.getInstance();
this.start = Math.max(0, this.start + this.pageSize);
searchParams.setStart(this.start);
if (searchParams.getDocType().equalsIgnoreCase("item")) {
List<WorkItemDocument> workItemDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkItemDocumentList(workItemDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("holdings")) {
List<OleWorkHoldingsDocument> oleWorkHoldingsDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkHoldingsDocumentList(oleWorkHoldingsDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("bibliographic")) {
List<WorkBibDocument> workBibDocuments = queryService.getDocuments(searchParams);
List<OleWorkBibDocument> oleWorkBibDocuments = new ArrayList<>();
for (WorkBibDocument workBibDocument : workBibDocuments) {
OleWorkBibDocument oleWorkBibDocument = new OleWorkBibDocument();
oleWorkBibDocument.setDocFormat(workBibDocument.getDocFormat());
oleWorkBibDocument.setId(workBibDocument.getId());
oleWorkBibDocument.setTitle(workBibDocument.getTitle());
oleWorkBibDocument.setLocalIds(workBibDocument.getLocalIds());
oleWorkBibDocument.setAuthor(workBibDocument.getAuthor());
oleWorkBibDocument.setStaffOnlyFlag(workBibDocument.getStaffOnlyFlag());
oleWorkBibDocument.setPublicationDate(workBibDocument.getPublicationDate());
if (eResourceId != null) {
oleWorkBibDocument.setOleERSIdentifier(eResourceId);
}
if (tokenId != null) {
oleWorkBibDocument.setTokenId(tokenId);
}
oleWorkBibDocuments.add(oleWorkBibDocument);
}
workbenchForm.setWorkBibDocumentList(oleWorkBibDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("eholdings")) {
List<OleWorkEHoldingsDocument> oleWorkEHoldingsDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkEHoldingsDocumentList(oleWorkEHoldingsDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
}
return navigate(workbenchForm, result, request, response);
}
/**
* search to Get the previous documents
* @param form
* @param result
* @param request
* @param response
* @return
*/
@RequestMapping(params = "methodToCall=previousSearch")
public ModelAndView previousSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the previousSearch method");
WorkbenchForm workbenchForm = (WorkbenchForm) form;
SearchParams searchParams = workbenchForm.getSearchParams();
QueryService queryService = QueryServiceImpl.getInstance();
this.start = Math.max(0, this.start - this.pageSize);
searchParams.setStart((this.start == 0) ? 0 : this.start);
if (searchParams.getDocType().equalsIgnoreCase("item")) {
List<WorkItemDocument> workItemDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkItemDocumentList(workItemDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("holdings")) {
List<OleWorkHoldingsDocument> oleWorkHoldingsDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkHoldingsDocumentList(oleWorkHoldingsDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("bibliographic")) {
List<WorkBibDocument> workBibDocuments = queryService.getDocuments(searchParams);
List<OleWorkBibDocument> oleWorkBibDocuments = new ArrayList<>();
for (WorkBibDocument workBibDocument : workBibDocuments) {
OleWorkBibDocument oleWorkBibDocument = new OleWorkBibDocument();
oleWorkBibDocument.setDocFormat(workBibDocument.getDocFormat());
oleWorkBibDocument.setId(workBibDocument.getId());
oleWorkBibDocument.setTitle(workBibDocument.getTitle());
oleWorkBibDocument.setLocalIds(workBibDocument.getLocalIds());
oleWorkBibDocument.setAuthor(workBibDocument.getAuthor());
oleWorkBibDocument.setStaffOnlyFlag(workBibDocument.getStaffOnlyFlag());
oleWorkBibDocument.setPublicationDate(workBibDocument.getPublicationDate());
if (eResourceId != null) {
oleWorkBibDocument.setOleERSIdentifier(eResourceId);
}
if (tokenId != null) {
oleWorkBibDocument.setTokenId(tokenId);
}
oleWorkBibDocuments.add(oleWorkBibDocument);
}
workbenchForm.setWorkBibDocumentList(oleWorkBibDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
} else if (searchParams.getDocType().equalsIgnoreCase("eholdings")) {
List<OleWorkEHoldingsDocument> oleWorkEHoldingsDocuments = queryService.getDocuments(searchParams);
workbenchForm.setWorkEHoldingsDocumentList(oleWorkEHoldingsDocuments);
setPageNextPreviousAndEntriesInfo(workbenchForm);
return navigate(workbenchForm, result, request, response);
}
return navigate(workbenchForm, result, request, response);
}
/**
* @param form
* @param result
* @param request
* @param response
* @return
*/
@RequestMapping(params = "methodToCall=clearSearch")
public ModelAndView clearSearch(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
LOG.info("Inside clearSearch Method");
WorkbenchForm workbenchForm = (WorkbenchForm) form;
workbenchForm.setSearchParams(new SearchParams());
List<SearchCondition> searchConditions = workbenchForm.getSearchParams().getSearchFieldsList();
searchConditions.add(new SearchCondition());
searchConditions.add(new SearchCondition());
workbenchForm.getSearchParams().setDocType("bibliographic");
workbenchForm.setWorkBibDocumentList(null);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.setWorkItemDocumentList(null);
workbenchForm.setWorkEHoldingsDocumentList(null);
workbenchForm.setMessage(null);
return getUIFModelAndView(workbenchForm);
// return navigate(workbenchForm, result, request, response);
}
@RequestMapping(params = "methodToCall=select")
public ModelAndView select(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
String selectedRecord = workbenchForm.getWorkBibDocumentList().get(index).getId();
LOG.info("selectedRecord--->" + selectedRecord);
return super.navigate(workbenchForm, result, request, response);
}
@RequestMapping(params = "methodToCall=selectRecords")
public ModelAndView selectRecords(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
List<String> selectedRecordIds = new ArrayList<String>();
List<OleWorkBibDocument> oleWorkBibDocuments = workbenchForm.getWorkBibDocumentList();
for (OleWorkBibDocument oleWorkBibDocument : oleWorkBibDocuments) {
if (oleWorkBibDocument.isSelect()) {
selectedRecordIds.add(oleWorkBibDocument.getId());
}
}
LOG.info("selectedRecords--->" + selectedRecordIds);
return getUIFModelAndView(workbenchForm);
}
/**
* Exports the selected bib records as request XML.
*
* @param form
* @param result
* @param request
* @param response
* @return
* @throws SolrServerException
* @throws IOException
* @throws ServletException
*/
@RequestMapping(params = "methodToCall=export")
public ModelAndView export(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws SolrServerException, IOException, ServletException {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
boolean hasPermission = canExportToRequestXml(GlobalVariables.getUserSession().getPrincipalId());
if (!hasPermission) {
workbenchForm.setMessage("<font size='4' color='red'>" + OLEConstants.SEARCH_AUTHORIZATION_ERROR + "</font>");
return navigate(workbenchForm, result, request, response);
}
workbenchForm.setShowRequestXML(true);
QueryService queryService = QueryServiceImpl.getInstance();
DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
Request docStoreRequest = new Request();
docStoreRequest.setOperation(Request.Operation.ingest.toString());
docStoreRequest.setUser("ole-khuntley");
List<String> selectedRecordIds = new ArrayList<String>();
List<OleWorkBibDocument> oleWorkBibDocuments = workbenchForm.getWorkBibDocumentList();
for (OleWorkBibDocument oleWorkBibDocument : oleWorkBibDocuments) {
if (oleWorkBibDocument.isSelect()) {
selectedRecordIds.add(oleWorkBibDocument.getId());
}
}
LOG.info("selectedRecords--->" + selectedRecordIds);
List<RequestDocument> requestDocumentList = new ArrayList<RequestDocument>();
for (String selectedRecordId : selectedRecordIds) {
RequestDocument requestDocument = new RequestDocument();
requestDocument.setUuid(selectedRecordId);
requestDocument.setId(selectedRecordId);
requestDocumentList.add(requestDocument);
}
List<RequestDocument> checkOutReqDocs = new ArrayList<RequestDocument>();
for (int i = 0; i < requestDocumentList.size(); i++) {
String id = requestDocumentList.get(i).getId();
RequestDocument requestDocument = new RequestDocument();
requestDocument.setCategory(DocCategory.WORK.getCode());
requestDocument.setType(DocType.BIB.getDescription());
requestDocument.setFormat(DocFormat.MARC.getCode());
requestDocument.setId(requestDocumentList.get(i).getId());
List<String> instanceIdList = new ArrayList<String>();
instanceIdList = queryService.queryForInstances(id);
LOG.debug("instance id list-->" + instanceIdList);
List<RequestDocument> linkedRequestDocumentList = new ArrayList<RequestDocument>();
for (String instanceId : instanceIdList) {
RequestDocument linkedReqDocument = new RequestDocument();
linkedReqDocument.setId(instanceId);
linkedReqDocument.setCategory(DocCategory.WORK.getCode());
linkedReqDocument.setType(DocType.INSTANCE.getCode());
linkedReqDocument.setFormat(DocFormat.OLEML.getCode());
String instanceResponse = docstoreHelperService.getContentFromDocStore(instanceId);
Content content = new Content();
if (instanceResponse.contains("Failure")) {
instanceResponse = new String();
content.setContent(instanceResponse);
} else {
Response response1 = new ResponseHandler().toObject(instanceResponse);
content.setContent(response1.getDocuments().get(0).getContent().getContent());
}
linkedReqDocument.setContent(content);
linkedRequestDocumentList.add(linkedReqDocument);
}
requestDocument.setLinkedRequestDocuments(linkedRequestDocumentList);
String bibContent = docstoreHelperService.getContentFromDocStore(requestDocumentList.get(i).getId());
Response bibResponse = new ResponseHandler().toObject(bibContent);
Content content = new Content();
if (bibResponse.getStatus().contains("Failure")) {
bibContent = new String();
content.setContent(bibContent);
} else {
content.setContent(bibResponse.getDocuments().get(0).getContent().getContent());
}
// content.setContent(bibContent);
requestDocument.setContent(content);
requestDocument.setAdditionalAttributes(bibResponse.getDocuments().get(0).getAdditionalAttributes());
checkOutReqDocs.add(requestDocument);
}
docStoreRequest.setRequestDocuments(checkOutReqDocs);
workbenchForm.setRequestXMLTextArea(new RequestHandler().toXML(docStoreRequest));
return getUIFModelAndView(workbenchForm);
}
@RequestMapping(params = "methodToCall=submit")
public ModelAndView submit(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
boolean isValid = false;
BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
Map<String, String> map = new HashMap<>();
List<OleWorkBibDocument> oleWorkBibDocumentList = workbenchForm.getWorkBibDocumentList();
List<Integer> resultList = new ArrayList<>();
for (OleWorkBibDocument oleWorkBibDocument : oleWorkBibDocumentList) {
if (oleWorkBibDocument.isSelect()) {
map.put(OLEConstants.BIB_ID, oleWorkBibDocument.getId());
List<OleCopy> listOfValues = (List<OleCopy>) boService.findMatching(OleCopy.class, map);
if (listOfValues.size() > 0 && (workbenchForm.getMessage() == null || workbenchForm.getMessage().equals(""))) {
for (OleCopy oleCopy : listOfValues) {
resultList.add(oleCopy.getReqDocNum());
}
Set<Integer> resultSet = new HashSet<>(resultList);
resultList = new ArrayList<>(resultSet);
StringBuffer reqIds = new StringBuffer("");
if (resultList.size() > 0) {
int count = 0;
for (; count < resultList.size() - 1; count++) {
reqIds.append(resultList.get(count) + ",");
}
reqIds.append(resultList.get(count));
}
workbenchForm.setMessage(OLEConstants.POPUP_MESSAGE + reqIds.toString() + OLEConstants.PROCEED_MESSAGE);
return getUIFModelAndView(workbenchForm);
}
workbenchForm.setMessage("");
processNewRecordResponseForOLE(oleWorkBibDocument, workbenchForm.getTokenId());
workbenchForm.setSuccessMessage(OLEConstants.LINK_SUCCESS_MESSAGE);
isValid = true;
break;
}
}
if (isValid == false) {
GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.BIB_SELECT);
return getUIFModelAndView(workbenchForm);
}
return getUIFModelAndView(workbenchForm);
}
private void processNewRecordResponseForOLE(OleWorkBibDocument oleWorkBibDocument, String tokenId) throws Exception {
String instanceUUID = null;
List bibInfo = null;
DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
OleBibRecord oleBibRecord = new OleBibRecord();
WorkBibDocument workBibDocument = new WorkBibDocument();
workBibDocument.setId(oleWorkBibDocument.getId());
QueryService queryService = QueryServiceImpl.getInstance();
workBibDocument = queryService.queryForBibTree(workBibDocument);
OleEditorResponse oleEditorResponse = new OleEditorResponse();
instanceUUID = workBibDocument.getWorkInstanceDocumentList().get(0).getInstanceIdentifier();
bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
oleBibRecord.setLinkedInstanceId(instanceUUID);
oleBibRecord.setBibUUID(workBibDocument.getId());
oleEditorResponse.setOleBibRecord(oleBibRecord);
oleEditorResponse.setTokenId(tokenId);
OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean(OLEConstants.OLE_EXPOSED_WEB_SERVICE);
oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
}
public String getURL() {
String url = ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.OLE_EXPOSED_WEB_SERVICE_url);
return url;
}
@RequestMapping(params = "methodToCall=linkToBib")
public ModelAndView linkToBib(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
Map<String, String> map = new HashMap<>();
List<OleWorkBibDocument> oleWorkBibDocumentList = workbenchForm.getWorkBibDocumentList();
List<OleWorkEHoldingsDocument> oleWorkEHoldingsDocuments = workbenchForm.getWorkEHoldingsDocumentList();
List<OleWorkHoldingsDocument> oleWorkHoldingsDocuments = workbenchForm.getWorkHoldingsDocumentList();
List<Integer> resultList = new ArrayList<>();
workbenchForm.setSuccessMessage(null);
/*if(workbenchForm.getSearchParams().getDocType().equals(OLEConstants.BIB_DOC_TYPE)) {
if (oleWorkBibDocumentList!=null && oleWorkBibDocumentList.size()>0){
for (OleWorkBibDocument oleWorkBibDocument:oleWorkBibDocumentList){
if (oleWorkBibDocument.isSelect()){
processNewRecordResponse(oleWorkBibDocument, workbenchForm.getTokenId());
workbenchForm.setSuccessMessage("");
break;
}
else{
workbenchForm.setSuccessMessage(OLEConstants.BIB_ERROR_MESSAGE);
}
}
}
}
else*/
if (workbenchForm.getSearchParams().getDocType().equals(OLEConstants.E_HOLDINGS_DOC_TYPE)) {
if (oleWorkEHoldingsDocuments != null && oleWorkEHoldingsDocuments.size() > 0) {
for (OleWorkEHoldingsDocument oleWorkEHoldingsDocument : oleWorkEHoldingsDocuments) {
if (oleWorkEHoldingsDocument.isSelect()) {
String eResName = "";
Map ersIdMap = new HashMap();
ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceId);
OLEEResourceRecordDocument eResourceDocument = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, ersIdMap);
if (eResourceDocument != null) {
eResName = eResourceDocument.getTitle();
}
processNewEInstanceResponse(oleWorkEHoldingsDocument, workbenchForm.getTokenId());
saveRecordToDocstore(oleWorkEHoldingsDocument, eResourceId, eResName);
workbenchForm.setSuccessMessage("");
break;
} else {
workbenchForm.setSuccessMessage(OLEConstants.EHOLDINGS_ERROR_MESSAGE);
}
}
}
}
else if (workbenchForm.getSearchParams().getDocType().equals(OLEConstants.HOLDINGS_DOC_TYPE)) {
if (oleWorkHoldingsDocuments != null && oleWorkHoldingsDocuments.size() > 0) {
for (OleWorkHoldingsDocument oleWorkHoldingsDocument : oleWorkHoldingsDocuments) {
if (oleWorkHoldingsDocument.isSelect()) {
processNewInstanceResponse(oleWorkHoldingsDocument, workbenchForm.getTokenId());
workbenchForm.setSuccessMessage("");
break;
} else {
workbenchForm.setSuccessMessage(OLEConstants.HOLDINGS_ERROR_MESSAGE);
}
}
}
}
if (eResourceId != null && !eResourceId.isEmpty()) {
Map<String, String> tempId = new HashMap<String, String>();
tempId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceId);
OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
try {
Person principalPerson = SpringContext.getBean(PersonService.class).getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
tempDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(tempDocument.getDocumentNumber(), principalPerson));
if (tempDocument != null) {
try {
tempDocument.setSelectInstance(OLEConstants.OLEEResourceRecord.LINK_EXIST_INSTANCE);
tempDocument.seteInstanceFlag(true);
getOleEResourceSearchService().getNewInstance(tempDocument, tempDocument.getDocumentNumber());
getDocumentService().updateDocument(tempDocument);
} catch (Exception e) {
throw new RiceRuntimeException(
"Exception trying to save document: " + tempDocument
.getDocumentNumber(), e);
}
}
} catch (Exception e) {
throw new RiceRuntimeException(
"Exception trying to save document: " + tempDocument
.getDocumentNumber(), e);
}
}
return getUIFModelAndView(workbenchForm);
}
@RequestMapping(params = "methodToCall=getHoldingsList")
public ModelAndView getHoldingsList(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
workbenchForm.setErrorMessage(null);
List<OleWorkHoldingsDocument> oleworkHoldingsDocumentList=new ArrayList<>();
List<WorkHoldingsDocument> workHoldingsDocumentList=new ArrayList<>();
List<OleWorkBibDocument> oleWorkBibDocumentList = workbenchForm.getWorkBibDocumentList();
if (oleWorkBibDocumentList != null && oleWorkBibDocumentList.size()>0){
for (OleWorkBibDocument oleWorkBibDocument:oleWorkBibDocumentList){
if (oleWorkBibDocument.isSelect()){
QueryService queryService = QueryServiceImpl.getInstance();
OleWorkBibDocument oleWorkBibDocumentResult= (OleWorkBibDocument)queryService.queryForBibTree(oleWorkBibDocument);
List<WorkInstanceDocument> instanceDocumentList =oleWorkBibDocumentResult.getWorkInstanceDocumentList();
if (instanceDocumentList.size()>0){
for (WorkInstanceDocument workInstanceDocument:instanceDocumentList){
workHoldingsDocumentList.add(workInstanceDocument.getHoldingsDocument());
}
for (WorkHoldingsDocument workHoldingsDocument : workHoldingsDocumentList) {
OleWorkHoldingsDocument oleWorkHoldingsDocument = new OleWorkHoldingsDocument();
oleWorkHoldingsDocument.setHoldingsIdentifier(workHoldingsDocument.getHoldingsIdentifier());
oleWorkHoldingsDocument.setBibTitle(workHoldingsDocument.getBibTitle());
oleWorkHoldingsDocument.setBibTitle(oleWorkBibDocument.getTitle());
oleWorkHoldingsDocument.setBibIdentifier(workHoldingsDocument.getBibIdentifier());
oleWorkHoldingsDocument.setBibUUIDList(workHoldingsDocument.getBibUUIDList());
oleWorkHoldingsDocument.setCallNumber(workHoldingsDocument.getCallNumber());
oleWorkHoldingsDocument.setCallNumberPrefix(workHoldingsDocument.getCallNumberPrefix());
oleWorkHoldingsDocument.setCallNumberType(workHoldingsDocument.getCallNumberType());
oleWorkHoldingsDocument.setCopyNumber(workHoldingsDocument.getCopyNumber());
oleWorkHoldingsDocument.setHoldingsIdentifier(workHoldingsDocument.getHoldingsIdentifier());
oleWorkHoldingsDocument.setStaffOnlyFlag(workHoldingsDocument.getStaffOnlyFlag());
oleWorkHoldingsDocument.setLinkedBibCount(workHoldingsDocument.getLinkedBibCount());
oleWorkHoldingsDocument.setLocalId(workHoldingsDocument.getLocalId());
oleWorkHoldingsDocument.setLocationName(workHoldingsDocument.getLocationName());
oleWorkHoldingsDocument.setInstanceIdentifier(workHoldingsDocument.getInstanceIdentifier());
oleworkHoldingsDocumentList.add(oleWorkHoldingsDocument);
}
}
}
}
}
workbenchForm.setWorkHoldingsDocumentList(oleworkHoldingsDocumentList);
workbenchForm.setWorkEHoldingsDocumentList(null);
workbenchForm.getSearchParams().setDocType(OLEConstants.HOLDINGS_DOC_TYPE);
return navigate(workbenchForm, result, request, response);
}
@RequestMapping(params = "methodToCall=getEHoldingsList")
public ModelAndView getEHoldingsList(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
WorkbenchForm workbenchForm = (WorkbenchForm) form;
workbenchForm.setErrorMessage(null);
List<WorkEHoldingsDocument> workEHoldingsDocumentList=new ArrayList<>();
List<OleWorkEHoldingsDocument> oleWorkEHoldingsDocumentList=new ArrayList<>();
List<OleWorkBibDocument> oleWorkBibDocumentList = workbenchForm.getWorkBibDocumentList();
if (oleWorkBibDocumentList != null && oleWorkBibDocumentList.size()>0){
for (OleWorkBibDocument oleWorkBibDocument:oleWorkBibDocumentList){
if (oleWorkBibDocument.isSelect()){
QueryService queryService = QueryServiceImpl.getInstance();
OleWorkBibDocument oleWorkBibDocumentResult= (OleWorkBibDocument)queryService.queryForBibTree(oleWorkBibDocument);
List<WorkEInstanceDocument> eInstanceDocumentList =oleWorkBibDocumentResult.getWorkEInstanceDocumentList();
if (eInstanceDocumentList.size()>0){
for (WorkEInstanceDocument workEInstanceDocument:eInstanceDocumentList){
workEHoldingsDocumentList.add(workEInstanceDocument.getWorkEHoldingsDocument());
}
for (WorkEHoldingsDocument workEHoldingsDocument : workEHoldingsDocumentList) {
OleWorkEHoldingsDocument oleWorkEHoldingsDocument = new OleWorkEHoldingsDocument();
oleWorkEHoldingsDocument.setAccessStatus(workEHoldingsDocument.getAccessStatus());
oleWorkEHoldingsDocument.setPlatForm(workEHoldingsDocument.getPlatForm());
oleWorkEHoldingsDocument.setImprint(workEHoldingsDocument.getImprint());
oleWorkEHoldingsDocument.setStatisticalCode(workEHoldingsDocument.getStatisticalCode());
oleWorkEHoldingsDocument.setLocation(workEHoldingsDocument.getLocation());
oleWorkEHoldingsDocument.setBibIdentifier(workEHoldingsDocument.getBibIdentifier());
oleWorkEHoldingsDocument.setInstanceIdentifier(workEHoldingsDocument.getInstanceIdentifier());
oleWorkEHoldingsDocument.setHoldingsIdentifier(workEHoldingsDocument.getHoldingsIdentifier());
oleWorkEHoldingsDocument.setLocalId(workEHoldingsDocument.getLocalId());
oleWorkEHoldingsDocument.setUrl(workEHoldingsDocument.getUrl());
oleWorkEHoldingsDocument.seteResourceName(workEHoldingsDocument.geteResourceName());
oleWorkEHoldingsDocumentList.add(oleWorkEHoldingsDocument);
}
}
else {
workbenchForm.setErrorMessage("selected bib doesnt have EHoldings");
}
}
}
}
workbenchForm.setWorkEHoldingsDocumentList(oleWorkEHoldingsDocumentList);
workbenchForm.setWorkHoldingsDocumentList(null);
workbenchForm.getSearchParams().setDocType(OLEConstants.E_HOLDINGS_DOC_TYPE);
return navigate(workbenchForm, result, request, response);
}
private void saveRecordToDocstore(OleWorkEHoldingsDocument oleWorkEHoldingsDocument, String eResourceId, String eResName) throws Exception {
DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
WorkEHoldingOlemlRecordProcessor workEHoldingOlemlRecordProcessor = new WorkEHoldingOlemlRecordProcessor();
String eHoldingsId = oleWorkEHoldingsDocument.getHoldingsIdentifier();
String eHoldingsContent = docstoreHelperService.getDocstoreData(eHoldingsId);
EHoldings eHoldings = workEHoldingOlemlRecordProcessor.fromXML(eHoldingsContent);
eHoldings.setEResourceId(eResourceId);
eHoldings.setEResourceTitle(eResName);
eHoldingsContent = workEHoldingOlemlRecordProcessor.toXML(eHoldings);
docstoreHelperService.updateInstanceRecord(eHoldingsId, DocType.EHOLDINGS.getCode(), eHoldingsContent);
}
/*private void processNewRecordResponse(OleWorkBibDocument oleWorkBibDocument,String tokenId) throws Exception {
String instanceUUID = null;
String einstanceUUID=null;
List bibInfo = null;
DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
OleBibRecord oleBibRecord = new OleBibRecord();
WorkBibDocument workBibDocument = new WorkBibDocument();
workBibDocument.setId(oleWorkBibDocument.getId());
QueryService queryService = QueryServiceImpl.getInstance();
workBibDocument = queryService.queryForBibTree(workBibDocument);
OleEditorResponse oleEditorResponse = new OleEditorResponse();
// instanceUUID = workBibDocument.getWorkEInstanceDocumentList().get(1).geteInstanceIdentifier();
instanceUUID = workBibDocument.getWorkInstanceDocumentList().get(0).getInstanceIdentifier();
bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
oleBibRecord.setLinkedInstanceId(instanceUUID);
oleBibRecord.setBibUUID(workBibDocument.getId());
oleEditorResponse.setOleBibRecord(oleBibRecord);
oleEditorResponse.setTokenId(tokenId);
OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean(OLEConstants.OLE_EXPOSED_WEB_SERVICE);
oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
}
*/
private void processNewEInstanceResponse(OleWorkEHoldingsDocument oleWorkEHoldingsDocument, String tokenId) throws Exception {
String instanceUUID = null;
String einstanceUUID = null;
List bibInfo = null;
DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
OleBibRecord oleBibRecord = new OleBibRecord();
WorkBibDocument workBibDocument = new WorkBibDocument();
workBibDocument.setId(oleWorkEHoldingsDocument.getBibIdentifier());
WorkEInstanceDocument workEInstanceDocument = new WorkEInstanceDocument();
workEInstanceDocument.setId(oleWorkEHoldingsDocument.getInstanceIdentifier());
QueryService queryService = QueryServiceImpl.getInstance();
workEInstanceDocument = queryService.queryForEInstanceTree(workEInstanceDocument);
OleEditorResponse oleEditorResponse = new OleEditorResponse();
// instanceUUID = workBibDocument.getWorkEInstanceDocumentList().get(1).geteInstanceIdentifier();
instanceUUID = workEInstanceDocument.getInstanceIdentifier();
bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
oleBibRecord.setLinkedInstanceId(instanceUUID);
oleBibRecord.setBibUUID(workBibDocument.getId());
oleBibRecord.seteInstance(OLEConstants.E_INSTANCE);
oleEditorResponse.setOleBibRecord(oleBibRecord);
oleEditorResponse.setTokenId(tokenId);
OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean(OLEConstants.OLE_EXPOSED_WEB_SERVICE);
oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
}
private void processNewInstanceResponse(OleWorkHoldingsDocument oleWorkHoldingsDocument, String tokenId) throws Exception {
String instanceUUID = null;
String einstanceUUID = null;
List bibInfo = null;
DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
OleBibRecord oleBibRecord = new OleBibRecord();
WorkBibDocument workBibDocument = new WorkBibDocument();
workBibDocument.setId(oleWorkHoldingsDocument.getBibIdentifier());
WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
workInstanceDocument.setId(oleWorkHoldingsDocument.getInstanceIdentifier());
QueryService queryService = QueryServiceImpl.getInstance();
workInstanceDocument = queryService.queryForInstanceTree(workInstanceDocument);
OleEditorResponse oleEditorResponse = new OleEditorResponse();
instanceUUID = workInstanceDocument.getInstanceIdentifier();
bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
oleBibRecord.setLinkedInstanceId(instanceUUID);
oleBibRecord.setBibUUID(workBibDocument.getId());
oleEditorResponse.setOleBibRecord(oleBibRecord);
oleEditorResponse.setTokenId(tokenId);
OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean(OLEConstants.OLE_EXPOSED_WEB_SERVICE);
oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
}
private boolean canExportToRequestXml(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.DESC_WORKBENCH_EXPORT_XML);
}
}
|
package com.jd.jarvisdemonim.entity;
import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Keep;
import org.greenrobot.greendao.annotation.NotNull;
import org.greenrobot.greendao.annotation.ToOne;
/**
* Auther: Jarvis Dong
* Time: on 2017/2/15 0015
* Name:
* OverView: ToOne 是1:1;用于一个对象;
* Usage: ToMany 是1:N;用于集合对象;
* 设置的为内部类,greendao使用;
*/
@Entity
public class TestDemoBean2 {
@Id(autoincrement = true)
private Long id;
private long innerId;
@ToOne(joinProperty = "innerId")
private InnerDemo demo;
/**
* Used to resolve relations
*/
@Generated(hash = 2040040024)
private transient DaoSession daoSession;
/**
* Used for active entity operations.
*/
@Generated(hash = 2019421435)
private transient TestDemoBean2Dao myDao;
@Generated(hash = 215242210)
public TestDemoBean2(Long id, long innerId) {
this.id = id;
this.innerId = innerId;
}
@Generated(hash = 144572231)
public TestDemoBean2() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public long getInnerId() {
return this.innerId;
}
public void setInnerId(long innerId) {
this.innerId = innerId;
}
@Generated(hash = 1697154002)
private transient Long demo__resolvedKey;
/** To-one relationship, resolved on first access. */
// @Generated(hash = 118889204)
@Keep
public InnerDemo getDemo() {
long __key = this.innerId;
if (demo__resolvedKey == null || !demo__resolvedKey.equals(__key)) {
DaoSession daoSession = this.daoSession;
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
InnerDemoDao targetDao = daoSession.getInnerDemoDao();
InnerDemo demoNew = targetDao.load(__key);
synchronized (this) {
demo = demoNew;
demo__resolvedKey = __key;
}
}
return demo;
}
/** called by internal mechanisms, do not call yourself. */
@Generated(hash = 601578255)
public void setDemo(@NotNull InnerDemo demo) {
if (demo == null) {
throw new DaoException(
"To-one property 'innerId' has not-null constraint; cannot set to-one to null");
}
synchronized (this) {
this.demo = demo;
innerId = demo.getId();
demo__resolvedKey = innerId;
}
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 128553479)
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 1942392019)
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 713229351)
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** called by internal mechanisms, do not call yourself. */
@Generated(hash = 695786621)
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getTestDemoBean2Dao() : null;
}
}
//@Entity
//class InnerDemo2 {
// @Id
// private Long id;
// private String target;
// private String color;
//}
|
import ServicesAndInfo.DinoDiet;
import Attractions.Dinosaur;
import ServicesAndInfo.TheatLevel;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DinosaurTest {
Dinosaur Herrerasaurus;
Dinosaur Triceratops;
@Before
public void setup(){
Herrerasaurus = new Dinosaur("Herrerasaurus", DinoDiet.CARNIVORE, TheatLevel.HIGHT);
Triceratops = new Dinosaur("Triceratops", DinoDiet.HERBIVORE, TheatLevel.MEDIUM);
}
@Test
public void hasName() {
assertEquals("Herrerasaurus", Herrerasaurus.getName());
}
@Test
public void canSetName() {
Herrerasaurus.setName("Steve The Dino");
assertEquals("Steve The Dino", Herrerasaurus.getName());
}
@Test
public void hasTreatLevel() {
assertEquals(TheatLevel.MEDIUM,Triceratops.getTheatLevel());
}
@Test
public void canSetThreatLevel() {
Triceratops.setTheatLevel(TheatLevel.HIGHT);
assertEquals(TheatLevel.HIGHT,Triceratops.getTheatLevel());
}
@Test
public void hasDiet() {
assertEquals(DinoDiet.HERBIVORE,Triceratops.getDiet());
}
}
|
package com.model.data;
import org.bson.types.ObjectId;
import com.model.db.Column;
public class Dict {
private String name;
protected ObjectId id;
private String summary;
@Column(name="dictType",linked=DictType.class)
private DictType dictType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public DictType getDictType() {
return dictType;
}
public void setDictType(DictType dictType) {
this.dictType = dictType;
}
}
|
package exemplos.aula10.dip.correto;
/**
* Exemplo retirado do artigo do Baeldung.
* https://www.baeldung.com/solid-principles
*/
public class StandardKeyboard implements Keyboard{
}
|
package com.xh.repair;
import com.xh.base.BaseApplication;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.widget.Toast;
/**
* @version 创建时间:2017-12-14 上午11:14:35 项目:repair 包名:com.xh.util 文件名:AMRP.java
* 作者:lhl 说明:
*/
public class AMRP {
public AMRP(PackageInfo packageInfo, AssetManager assetManager,
Resources resources) {
// TODO Auto-generated constructor stub
if (packageInfo != null)
packageName = packageInfo.packageName;
this.assetManager = assetManager;
this.resources = resources;
this.packageInfo = packageInfo;
mTheme = resources.newTheme();
// Finals适配三星以及部分加载XML出现异常BUG
try {
mTheme.applyStyle(packageInfo.applicationInfo.theme, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public AMRP() {
// TODO Auto-generated constructor stub
}
public Theme mTheme;
public PackageInfo packageInfo;
public String packageName = "";
public AssetManager assetManager;
public Resources resources;
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
if (o == null || !o.getClass().getName().equals(AMRP.class.getName()))
return false;
AMRP a = (AMRP) o;
return a.packageName.equals(packageName);
}
}
|
package prepare;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.bson.Document;
import org.junit.Test;
import base.ChatTestCase;
import java.io.InputStream;
import java.util.Arrays;
public class AdminControllerTest extends ChatTestCase {
@Test
public void testRegister() throws Exception {
String account = "admin";
String password = "123456";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(HOST + "/admin/register");
Document doc = new Document();
doc.put("account", account);
doc.put("pwd", Base64.encodeBase64String(password.getBytes("utf8")));
doc.put("name", "Aplomb");
method.setRequestEntity(new StringRequestEntity(doc.toJson()));
int code = httpClient.executeMethod(method);
assert code == 200;
InputStream is = method.getResponseBodyAsStream();
String responseStr = IOUtils.toString(is, "utf8");
System.out.println("Register response " + responseStr);
Document responseDoc = Document.parse(responseStr);
assert responseDoc.get("code").equals(1);
}
@Test
public void testRegisterEmployee() throws Exception {
String account = "aplomb";
String password = "123456";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(HOST + "/register");
Document doc = new Document();
doc.put("account", account);
doc.put("pwd", Base64.encodeBase64String(password.getBytes("utf8")));
doc.put("name", "Aplomb");
method.setRequestEntity(new StringRequestEntity(doc.toJson()));
int code = httpClient.executeMethod(method);
assert code == 200;
InputStream is = method.getResponseBodyAsStream();
String responseStr = IOUtils.toString(is, "utf8");
System.out.println("Register response " + responseStr);
Document responseDoc = Document.parse(responseStr);
assert responseDoc.get("code").equals(1);
}
@Test
public void testRegisterUser() throws Exception {
String account = "lily";
String password = "123456";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(HOST + "/register");
Document doc = new Document();
doc.put("account", account);
doc.put("pwd", Base64.encodeBase64String(password.getBytes("utf8")));
doc.put("name", "Lily");
method.setRequestEntity(new StringRequestEntity(doc.toJson()));
int code = httpClient.executeMethod(method);
assert code == 200;
InputStream is = method.getResponseBodyAsStream();
String responseStr = IOUtils.toString(is, "utf8");
System.out.println("Register response " + responseStr);
Document responseDoc = Document.parse(responseStr);
assert responseDoc.get("code").equals(1);
}
@Test
public void testNewCompany() throws Exception {
Document user = login("aplomb", "123456");
Document login = (Document)user.get("login");
String aplombId = (String)login.get("id");
user = login("admin", "123456");
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(HOST + "/company");
Document doc = new Document();
doc.put("employeeIds", Arrays.asList(aplombId));
doc.put("name", "MyCompany");
method.setRequestEntity(new StringRequestEntity(doc.toJson()));
method.setRequestHeader(new Header("Cookie", cookieString));
int code = httpClient.executeMethod(method);
assert code == 200;
InputStream is = method.getResponseBodyAsStream();
String responseStr = IOUtils.toString(is, "utf8");
System.out.println("Register response " + responseStr);
Document responseDoc = Document.parse(responseStr);
assert responseDoc.get("code").equals(1);
}
}
|
package de.domistiller.vp.android;
import java.util.ArrayList;
import de.domistiller.vpapi.model.Vertretungsplan;
public interface DataSource {
public ArrayList<String> getDates() throws Exception;
public Vertretungsplan getData(String date) throws Exception;
}
|
package pro.likada.dao.daoImpl;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.likada.dao.OrderPaymentTypeDAO;
import pro.likada.model.OrderPaymentType;
import pro.likada.util.HibernateUtil;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by Yusupov on 3/20/2017.
*/
@SuppressWarnings("unchecked")
@Named("orderPaymentTypeDAO")
@Transactional
public class OrderPaymentTypeDAOImpl implements OrderPaymentTypeDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderPaymentTypeDAOImpl.class);
@Override
public List<OrderPaymentType> getAllOrderPaymentTypes() {
LOGGER.info("Get All OrderPaymentTypes");
Session session = HibernateUtil.getSessionFactory().openSession();
List<OrderPaymentType> orderPaymentTypes = (List<OrderPaymentType>) session.createCriteria(OrderPaymentType.class).setCacheable(true).list();
session.close();
return orderPaymentTypes;
}
@Override
public OrderPaymentType getOrderTypeByName(String name) {
LOGGER.info("Get an Order with name: {}", name);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(OrderPaymentType.class);
criteria.add(Restrictions.eq("name", name));
OrderPaymentType orderPaymentType = (OrderPaymentType) criteria.uniqueResult();
session.close();
return orderPaymentType;
}
}
|
package matrixstudio.ui;
import fr.minibilles.basics.ui.Resources;
public interface RendererContext {
Resources getResources();
}
|
package kafka2kafka;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import kafka.UserAvro;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import java.util.stream.IntStream;
public class ConsumeConfluentAvroTest {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
EnvironmentSettings envSettings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build();
StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env, envSettings);
String tableDDL = "CREATE TABLE WikipediaFeed (\n" +
" user_name STRING,\n" +
" is_new BOOLEAN,\n" +
" content STRING" +
") WITH (\n" +
" 'connector.type' = 'kafka',\n" +
" 'connector.version' = '0.10',\n" +
" 'connector.topic' = 'WikipediaFeed',\n" +
" 'connector.properties.zookeeper.connect' = 'localhost:2181',\n" +
" 'connector.properties.bootstrap.servers' = 'localhost:9092',\n" +
" 'connector.properties.group.id' = 'testGroup3',\n" +
" 'connector.startup-mode' = 'earliest-offset',\n" +
" 'format.type' = 'avro',\n" +
" 'format.avro-schema' =\n" +
" '{ \n" +
" \"type\": \"record\",\n" +
" \"name\": \"UserAvro\",\n" +
" \"fields\": [\n" +
" {\"name\": \"user_name\", \"type\": \"string\"},\n" +
" {\"name\": \"is_new\", \"type\": \"boolean\"},\n" +
" {\"name\": \"content\", \"type\": \"string\"}\n" +
" ]\n" +
" }'" +
")\n";
tableEnvironment.sqlUpdate(tableDDL);
String querySQL = "select user_name, is_new, content \n" +
"from WikipediaFeed\n" ;
tableEnvironment.toAppendStream(tableEnvironment.sqlQuery(querySQL), Row.class).print();
tableEnvironment.execute("KafkaAvro2Kafka");
}
// prepare confluent avro foramt data
private static void produceInputs() throws IOException {
final String[] users = {"leonard", "bob", "joe", "damian", "tania", "phil", "sam", "lauren", "joseph"};
final Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
props.put("schema.registry.url", "http://localhost:8081");
final KafkaProducer<String, UserAvro> producer = new KafkaProducer<>(props);
final Random random = new Random();
IntStream.range(0, 10)
.mapToObj(value -> new UserAvro(users[random.nextInt(users.length)], true, "content"))
.forEach(
record -> {
System.out.println(record.toString()) ;
producer.send(new ProducerRecord<>("WikipediaFeed", record.getUserName(), record));
});
producer.flush();
}
}
|
package util;
import dao.BlockWidthTypeDAO;
import dao.DAO;
import dao.ManualBlockDAO;
import dao.ManualConfDAO;
import dao.ManualDAO;
import dao.ManualPageDAO;
import dao.ManualRowDAO;
import dao.TagDAO;
import dao.UserDAO;
import dao.UserInfoDAO;
import dao.WidthTypeDAO;
import hibernate.HibernateUtil;
import java.lang.reflect.Constructor;
import org.hibernate.Session;
import util.enums.DAOList;
/**
* @author Andriy Yednarovych
*/
public class ServiceManager {
private Session session;
public ServiceManager() {
session = HibernateUtil.getSessionFactory().openSession();
}
public DAO getDAO(DAOList daoItem) {
DAO dao = null;
try {
Class<?> clazz = Class.forName(daoItem.getValue());
Constructor<?> constructor = clazz.getConstructor(Session.class);
dao = (DAO) constructor.newInstance(new Object[] {session});
} catch (Exception e) {
ErrorMsgs.sysLogThis(e);
}
return dao;
}
public <T> T getDAO(Class<T> daoClass) {
DAO dao = null;
try {
Constructor<?> constructor = daoClass.getConstructor(Session.class);
dao = (DAO) constructor.newInstance(new Object[] {session});
} catch (Exception e) {
ErrorMsgs.sysLogThis(e);
}
return daoClass.cast(dao);
}
public UserDAO getUserDAO() {
return new UserDAO(session);
}
public UserInfoDAO getUserInfoDAO() {
return new UserInfoDAO(session);
}
public ManualDAO getManualDAO() {
return new ManualDAO(session);
}
public ManualPageDAO getManualPageDAO() {
return new ManualPageDAO(session);
}
public ManualRowDAO getManualRowDAO() {
return new ManualRowDAO(session);
}
public ManualBlockDAO getManualBlockDAO() {
return new ManualBlockDAO(session);
}
public TagDAO getTagDAO() {
return new TagDAO(session);
}
public WidthTypeDAO getWidthTypeDAO() {
return new WidthTypeDAO(session);
}
public BlockWidthTypeDAO getBlockWidthTypeDAO() {
return new BlockWidthTypeDAO(session);
}
public ManualConfDAO getManualConfDAO() {
return new ManualConfDAO(session);
}
public Session getSession() {
return session;
}
public void beginTransaction() {
session.beginTransaction();
}
public void rollback() {
session.getTransaction().rollback();
}
public void rollbackClose() {
session.getTransaction().rollback();
close();
}
public void commitClose() {
session.getTransaction().commit();
close();
}
public void commit() {
session.getTransaction().commit();
}
public void close() {
if (session.isOpen()) {
session.close();
}
}
public void openSession() {
session = HibernateUtil.getSessionFactory().openSession();
}
}
|
package dubstep;
////@Author - Anunay Rao
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.BooleanValue;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.PrimitiveValue;
import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.create.table.ColDataType;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;
public class OnePassHashJoin {
public static MyTable computeJoin(MyTable t1, MyTable t2) throws IOException {
String joinColumn = null;
String jcl=null;
String jcr=null;
ArrayList<joinSpec> jclist = new ArrayList<joinSpec>();
//System.out.println(t1.tableName + t2.tableName);
if(t1.tableName.contains("|")) {
String tblname[] = t1.tableName.split("\\|");
String tableName1 = tblname[tblname.length -1];
// Can be modified to check for all the join conditions for each table;
for(int i =0; i<tblname.length;i++) {
joinColumn = getJoinColumn(tblname[i], t2.tableName);
if(joinColumn!=null) {
jcl = tblname[i]+"."+joinColumn;
jcr = t2.tableName+"."+joinColumn;
joinSpec js = new joinSpec();
js.jcl = jcl;
js.jcr=jcr;
jclist.add(js);
//break; //To get the most recent join condition for left deep plan
}
}
//joinColumn = getJoinColumn(tableName1, t2.tableName);
}
else {
joinColumn = getJoinColumn(t1.tableName, t2.tableName);
jcl = t1.tableName+"."+joinColumn;
jcr = t2.tableName+"."+joinColumn;
joinSpec js = new joinSpec();
js.jcl = jcl;
js.jcr=jcr;
jclist.add(js);
/*
for(int i=0; i<jclist.size();i++) {
System.out.println(jclist.get(i).jcl + ":::"+ jclist.get(i).jcr);
}
*/
}
//System.out.println("JOIN:"+joinColumn);
ArrayList<ColumnDefinition> jointablecd = new ArrayList();
for(ColumnDefinition cd : t1.tableColDef) {
jointablecd.add(cd);
}
for(ColumnDefinition cd : t2.tableColDef) {
jointablecd.add(cd);
}
/*
for(int i=0; i<jclist.size();i++) {
System.out.println(jclist.get(i).jcl + ":::"+ jclist.get(i).jcr);
}
*/
MyTable joinresult = new MyTable(t1.tableName+"|"+t2.tableName,jointablecd,false);
ArrayList<String> cn = new ArrayList<String>();
ArrayList<ColDataType> cd = new ArrayList<ColDataType>();
for(int i=0;i<t1.columnNames.size();i++) {
cn.add(t1.columnNames.get(i));
cd.add(t1.columnDatatype.get(i));
}
for(int i=0;i<t2.columnNames.size();i++) {
cn.add(t2.columnNames.get(i));
cd.add(t2.columnDatatype.get(i));
}
// System.out.println(cn);
// System.out.println(cd);
joinresult.columnDatatype = cd;
joinresult.columnNames =cn;
HashMap<String,ArrayList<String>> hashtable = new HashMap();
if(joinColumn==null) {
CrossProduct(t1, t2);
String r;
/*
while((r=joinresult.readtuple())!=null) {
System.out.println(r);
}
*/
return joinresult;
//System.out.println("No join Condition");
}
int l,r;
ArrayList<Integer> lind = new ArrayList<Integer>();
ArrayList<Integer> rind = new ArrayList<Integer>();
//int l = getcolIndex(t1.tableColDef, joinColumn);
//int r = getcolIndex(t2.tableColDef, joinColumn);
for(int i=0; i<jclist.size();i++) {
joinSpec js = jclist.get(i);
jcl = js.jcl;
jcr = js.jcr;
l = getcolIndex(t1.columnNames, jcl);
r = getcolIndex(t2.columnNames,jcr);
lind.add(l);
rind.add(r);
}
//System.out.println(lind);
//System.out.println("LIND::"+lind);
//l = getcolIndex(t1.columnNames, jcl);
//r = getcolIndex(t2.columnNames,jcr);
//System.out.println("Left"+l+"Right"+r);
/*
if(t1.tableName.contains("|")) {
String tblname[] = t1.tableName.split("\\|");
String tableName1 = tblname[tblname.length -1];
l = getcolIndex(t1.columnNames,tableName1+"."+joinColumn);
}
else {
l = getcolIndex(t1.columnNames, jcl);
}
r = getcolIndex(t2.columnNames,jcr);
*/
//System.out.println(l+":"+r);
//int hashobjectsize = 2;
String row=null;
if(ConfigureVariables.istpch3 && t1.tableName.contains("customer")) {
HashMap<String, ArrayList<Long>> hm=null ;
Expression e = ConfigureVariables.tableCondition.get("CUSTOMER").get(0);
String str = ((BinaryExpression) e).getRightExpression().toString();
str = str.substring(1, str.length()-1);
int count =0;
if(!ConfigureVariables.firstjoin) {
try {
hm = Main.readMap("CUSTOMER.ind");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Long> set = hm.get(str);
//System.out.println(str);
Collections.sort(set);
FileReader fr;
BufferedReader br;
fr = new FileReader(ConfigureVariables.pathname+t1.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
int skip =0;
//int count =0;
//int r =0;
for(Long j : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(j-skip);
String rowread = br.readLine();
//System.out.println(rowread);
if(rowread==null) {
break;
}
String[] rowval = rowread.split("\\|");
String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
long len = rowread.length() + 1;
skip = (int) (len+j);
}
}
else {
int ind =0;
int size = t1.tuples.size();
while(ind!=size) {
row = t1.tuples.get(ind);
ind = ind+1;
//System.out.println("While:"+t1.tableColDef);
String []rowval = row.split("\\|");
if(checkSelection(rowval, t1.tableColDef,t1.tableName))
{
String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
//System.out.println("Yes");
//System.out.println(row);
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
}
}
}
}
else if(ConfigureVariables.istpch12 && t1.tableName.equalsIgnoreCase("lineitem")) {
Date startdate,enddate;
String sdate=null, edate=null;
NavigableMap<Date, ArrayList<Long>> nm;
NavigableMap<Date, ArrayList<Long>> hnm = null;;
ArrayList<Expression> exp = ConfigureVariables.tableCondition.get("LINEITEM");
ArrayList<Expression> newexp = new ArrayList<Expression>();
ArrayList<Expression> fexp = new ArrayList<Expression>();
for(Expression ex : exp ) {
String sexp = ((BinaryExpression) ex).getLeftExpression().toString();
//System.out.println(sexp);
if(sexp.contains("LINEITEM.RECEIPTDATE")) {
//System.out.println("yes");
fexp.add(ex);
}
else{
newexp.add(ex);
}
}
ConfigureVariables.tableCondition.put("LINEITEM",newexp);
Expression e= fexp.get(0);
if(e instanceof GreaterThanEquals) {
String sidate = ((BinaryExpression) e).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
else {
String eidate = ((BinaryExpression) e).getRightExpression().toString();
//System.out.println(eidate);
edate = eidate.substring(6, 16);
}
//System.out.println(sdate);
Expression e1 = fexp.get(1);
if(!(e1 instanceof GreaterThanEquals)) {
String eidate = ((BinaryExpression) e1).getRightExpression().toString();
edate = eidate.substring(6, 16);
}
else {
String sidate = ((BinaryExpression) e1).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
//String eidate = ((BinaryExpression) e1).getRightExpression().toString();
//String edate = eidate.substring(6, 16);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
startdate = sdf.parse(sdate);
enddate = sdf.parse(edate);
//System.out.println(startdate+"::::"+enddate);
nm = Main.readNMap("LINEITEMR.ind");
// System.out.println("NM SIZE SET:"+nm.size());
hnm = nm.subMap(startdate, true, enddate, false);
// System.out.println("SUBNM SIZE SET:"+hnm.size());
} catch (ParseException e11) {
// TODO Auto-generated catch block
e11.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileReader fr=null;
BufferedReader br=null;
try {
fr = new FileReader(ConfigureVariables.pathname+t1.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
ArrayList<Long> set = new ArrayList<Long>();
for(Date d : hnm.keySet()) {
ArrayList<Long> bytes = hnm.get(d);
set.addAll(bytes);
}
Collections.sort(set);
//System.out.println(t1.tableName+set.size());
int skip =0;
//int count =0;
//int r =0;
for(Long j : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(j-skip);
String rowread = br.readLine();
//System.out.println(rowread);
//System.out.println(rowread);
if(rowread==null) {
break;
}
String rowval[] = rowread.split("\\|");
if(ConfigureVariables.tableCondition.containsKey(t1.tableName)) {
if(checkSelection(rowval, t1.tableColDef, t1.tableName)) {
//String[] rowval = rowread.split("\\|");
String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
hashtable.get(key).add(rowread);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(rowread);
hashtable.put(key,temp);
}
}}
//SelectionOperator.Selection(tuple,ConfigureVariables.tableStrings.get(i).toLowerCase());
long len = rowread.length() + 1;
skip = (int) (len+j);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else{
//System.out.println("400:yes");
int count =0;
if(!ConfigureVariables.firstjoin) {
//System.out.println("FirstJoin:"+t1.tableName);
ArrayList<String> deleterows = new ArrayList<String>();
if(ConfigureVariables.mapdelete.containsKey(t1.tableName)) {
deleterows = ConfigureVariables.mapdelete.get(t1.tableName);
while((row=t1.readtuple())!=null) {
if(!deleterows.contains(row)){
//System.out.println("While:"+t1.tableColDef);
String []rowval = row.split("\\|");
if(checkSelection(rowval, t1.tableColDef,t1.tableName))
{ String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
//System.out.println("Yes");
//System.out.println(row);
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
}
}
}
}
else {
//System.out.println("yes:no delete join"+t1.tableName);
while((row=t1.readtuple())!=null) {
//System.out.println("While:"+t1.tableColDef);
String []rowval = row.split("\\|");
if(checkSelection(rowval, t1.tableColDef,t1.tableName))
{ String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
//System.out.println("Yes");
//System.out.println(row);
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
}
}
//System.out.println("Hashtable size after t1::"+t1.tableName+hashtable.size());
}
// Put Newly inserted rows into hashtable for join
if(ConfigureVariables.mapinsert.containsKey(t1.tableName)) {
for(String s : ConfigureVariables.mapinsert.get(t1.tableName)) {
row = s;
String []rowval = row.split("\\|");
if(checkSelection(rowval, t1.tableColDef,t1.tableName))
{ String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
//System.out.println("Yes");
//System.out.println(row);
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
}
}
}
}
else {
//System.out.println("Making map for"+t1.tableName);
int ind =0;
int size = t1.tuples.size();
while(ind!=size) {
row = t1.tuples.get(ind);
ind = ind+1;
//System.out.println("While:"+t1.tableColDef);
String []rowval = row.split("\\|");
if(checkSelection(rowval, t1.tableColDef,t1.tableName))
{
String key="";
for(int i =0;i<lind.size();i++) {
key += rowval[lind.get(i)];
key +="|";
}
//System.out.println("Yes");
//System.out.println(row);
if(hashtable.containsKey(key)) {
hashtable.get(key).add(row);
}
else {
ArrayList<String> temp = new ArrayList();
temp.add(row);
hashtable.put(key,temp);
}
}
}
}
}
if(ConfigureVariables.istpch5&& t2.tableName.equals("ORDERS")) {
Date startdate,enddate;
String sdate=null, edate=null;
NavigableMap<Date, ArrayList<Long>> nm;
NavigableMap<Date, ArrayList<Long>> hnm = null;;
Expression e = ConfigureVariables.tableCondition.get("ORDERS").get(0);
if(e instanceof GreaterThanEquals) {
String sidate = ((BinaryExpression) e).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
else {
String eidate = ((BinaryExpression) e).getRightExpression().toString();
edate = eidate.substring(6, 16);
}
//System.out.println(sdate);
Expression e1 = ConfigureVariables.tableCondition.get("ORDERS").get(1);
if(!(e1 instanceof GreaterThanEquals)) {
String eidate = ((BinaryExpression) e1).getRightExpression().toString();
edate = eidate.substring(6, 16);
}
else {
String sidate = ((BinaryExpression) e1).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
//String eidate = ((BinaryExpression) e1).getRightExpression().toString();
//String edate = eidate.substring(6, 16);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
startdate = sdf.parse(sdate);
enddate = sdf.parse(edate);
//System.out.println(startdate+"::::"+enddate);
nm = Main.readNMap("ORDERS.ind");
//System.out.println("NM SIZE SET:"+nm.size());
hnm = nm.subMap(startdate, true, enddate, false);
// System.out.println("SUBNM SIZE SET:"+hnm.size());
} catch (ParseException e11) {
// TODO Auto-generated catch block
e11.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileReader fr;
BufferedReader br;
try {
fr = new FileReader(ConfigureVariables.pathname+t2.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
ArrayList<Long> set = new ArrayList<Long>();
for(Date d : hnm.keySet()) {
ArrayList<Long> bytes = hnm.get(d);
set.addAll(bytes);
}
Collections.sort(set);
int skip =0;
//int count =0;
//int r =0;
for(Long i : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(i-skip);
String rowread = br.readLine();
//System.out.println(rowread);
if(rowread==null) {
break;
}
String[] rowval = rowread.split("\\|");
String key="";
for(int k =0;k<rind.size();k++) {
key += rowval[rind.get(k)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+rowread);
//writeresult(s+"|"+row, joinresult);
}
}
long len = rowread.length() + 1;
skip = (int) (len+i);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//System.out.println(t2.tableName+":"+ConfigureVariables.countcheck);
}
else if(ConfigureVariables.istpch3 && t2.tableName.equalsIgnoreCase("orders")) {
Date startdate;
NavigableMap<Date, ArrayList<Long>> nm;
NavigableMap<Date, ArrayList<Long>> hnm = null;;
Expression e = ConfigureVariables.tableCondition.get("ORDERS").get(0);
String sidate = ((BinaryExpression) e).getRightExpression().toString();
String sdate = sidate.substring(6, 16);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
startdate = sdf.parse(sdate);
//System.out.println(startdate+"::::"+enddate);
nm = Main.readNMap("ORDERS.ind");
//System.out.println("NM SIZE SET:"+nm.size());
hnm = nm.headMap(startdate, false);
// System.out.println("SUBNM SIZE SET:"+hnm.size());
} catch (ParseException e11) {
// TODO Auto-generated catch block
e11.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileReader fr;
BufferedReader br;
try {
fr = new FileReader(ConfigureVariables.pathname+t2.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
ArrayList<Long> set = new ArrayList<Long>();
for(Date d : hnm.keySet()) {
ArrayList<Long> bytes = hnm.get(d);
set.addAll(bytes);
}
Collections.sort(set);
int skip =0;
//int count =0;
//int r =0;
for(Long i : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(i-skip);
String rowread = br.readLine();
//System.out.println(rowread);
if(rowread==null) {
break;
}
String[] rowval = rowread.split("\\|");
String key="";
for(int k =0;k<rind.size();k++) {
key += rowval[rind.get(k)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+rowread);
//writeresult(s+"|"+row, joinresult);
}
}
long len = rowread.length() + 1;
skip = (int) (len+i);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else if(ConfigureVariables.istpch3 && t2.tableName.equalsIgnoreCase("lineitem")) {
Date startdate;
NavigableMap<Date, ArrayList<Long>> nm;
NavigableMap<Date, ArrayList<Long>> hnm = null;;
Expression e = ConfigureVariables.tableCondition.get("LINEITEM").get(0);
String sidate = ((BinaryExpression) e).getRightExpression().toString();
String sdate = sidate.substring(6, 16);
//System.out.println(sdate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
startdate = sdf.parse(sdate);
//System.out.println(startdate+"::::"+enddate);
nm = Main.readNMap("LINEITEM.ind");
//System.out.println("NM SIZE SET:"+nm.size());
hnm = nm.tailMap(startdate, false);
// System.out.println("SUBNM SIZE SET:"+hnm.size());
} catch (ParseException e11) {
// TODO Auto-generated catch block
e11.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileReader fr;
BufferedReader br;
try {
fr = new FileReader(ConfigureVariables.pathname+t2.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
ArrayList<Long> set = new ArrayList<Long>();
for(Date d : hnm.keySet()) {
ArrayList<Long> bytes = hnm.get(d);
set.addAll(bytes);
}
Collections.sort(set);
int skip =0;
//int count =0;
//int r =0;
for(Long i : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(i-skip);
String rowread = br.readLine();
//System.out.println(rowread);
if(rowread==null) {
break;
}
String[] rowval = rowread.split("\\|");
String key="";
for(int k =0;k<rind.size();k++) {
key += rowval[rind.get(k)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+rowread);
//writeresult(s+"|"+row, joinresult);
}
}
long len = rowread.length() + 1;
skip = (int) (len+i);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else if(ConfigureVariables.istpch12 && t2.tableName.equalsIgnoreCase("lineitem")) {
Date startdate,enddate;
String sdate=null, edate=null;
NavigableMap<Date, ArrayList<Long>> nm;
NavigableMap<Date, ArrayList<Long>> hnm = null;;
ArrayList<Expression> exp = ConfigureVariables.tableCondition.get("LINEITEM");
ArrayList<Expression> fexp = new ArrayList<Expression>();
for(Expression ex : exp ) {
String sexp = ((BinaryExpression) ex).getLeftExpression().toString();
//System.out.println(sexp);
if(sexp.contains("LINEITEM.RECEIPTDATE")) {
//System.out.println("yes");
fexp.add(ex);
}
}
Expression e= fexp.get(0);
if(e instanceof GreaterThanEquals) {
String sidate = ((BinaryExpression) e).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
else {
String eidate = ((BinaryExpression) e).getRightExpression().toString();
//System.out.println(eidate);
edate = eidate.substring(6, 16);
}
//System.out.println(sdate);
Expression e1 = fexp.get(1);
if(!(e1 instanceof GreaterThanEquals)) {
String eidate = ((BinaryExpression) e1).getRightExpression().toString();
edate = eidate.substring(6, 16);
}
else {
String sidate = ((BinaryExpression) e1).getRightExpression().toString();
sdate = sidate.substring(6, 16);
}
//String eidate = ((BinaryExpression) e1).getRightExpression().toString();
//String edate = eidate.substring(6, 16);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
startdate = sdf.parse(sdate);
enddate = sdf.parse(edate);
//System.out.println(startdate+"::::"+enddate);
nm = Main.readNMap("LINEITEMR.ind");
//System.out.println("NM SIZE SET:"+nm.size());
hnm = nm.subMap(startdate, true, enddate, false);
// System.out.println("SUBNM SIZE SET:"+hnm.size());
} catch (ParseException e11) {
// TODO Auto-generated catch block
e11.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileReader fr=null;
BufferedReader br=null;
try {
fr = new FileReader(ConfigureVariables.pathname+t2.tableName+ConfigureVariables.FILEEXTENSION);
br = new BufferedReader(fr);
ArrayList<Long> set = new ArrayList<Long>();
for(Date d : hnm.keySet()) {
ArrayList<Long> bytes = hnm.get(d);
set.addAll(bytes);
}
Collections.sort(set);
int skip =0;
//int count =0;
//int r =0;
for(Long j : set) {
//System.out.println(i);
//System.out.println(skip);
br.skip(j-skip);
String rowread = br.readLine();
//System.out.println(rowread);
if(rowread==null) {
break;
}
String rowval[] = rowread.split("\\|");
if(ConfigureVariables.tableCondition.containsKey(t2.tableName)) {
if(checkSelection(rowval, t2.tableColDef, t2.tableName)) {
/*if(t2.tableName.equalsIgnoreCase("orders")){
ConfigureVariables.countcheck = ConfigureVariables.countcheck + 1;
}*/
//System.out.println("yes2");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}}
//SelectionOperator.Selection(tuple,ConfigureVariables.tableStrings.get(i).toLowerCase());
long len = rowread.length() + 1;
skip = (int) (len+j);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else {
/*if(t2.tableName.equalsIgnoreCase("nation") ||t2.tableName.equalsIgnoreCase("customer")||t2.tableName.equalsIgnoreCase("lineitem")||t2.tableName.equalsIgnoreCase("supplier") ) {
System.out.println(t2.tableName+":"+"traditional");
}*/
//System.out.println("hello");
//System.out.println("t2 starting.."+t2.tableName);
if(ConfigureVariables.mapdelete.containsKey(t2.tableName)) {
while((row=t2.readtuple())!=null) {
//System.out.println(row);
if(!ConfigureVariables.mapdelete.get(t2.tableName).contains(row)){
String[] rowval = row.split("\\|");
/*if(t2.tableName.equalsIgnoreCase("ORDERS")) {
ConfigureVariables.countcheck = ConfigureVariables.countcheck +1;
}*/
if(ConfigureVariables.tableCondition.containsKey(t2.tableName)) {
if(checkSelection(rowval, t2.tableColDef, t2.tableName)) {
/*if(t2.tableName.equalsIgnoreCase("orders")){
ConfigureVariables.countcheck = ConfigureVariables.countcheck + 1;
}*/
//System.out.println("yes2");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}}
else {
//System.out.println("Hello");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}
}
}
}
else {
//System.out.println("t2:no delete or insert"+t2.tableName);
while((row=t2.readtuple())!=null) {
//System.out.println(row);
String[] rowval = row.split("\\|");
/*if(t2.tableName.equalsIgnoreCase("ORDERS")) {
ConfigureVariables.countcheck = ConfigureVariables.countcheck +1;
}*/
if(ConfigureVariables.tableCondition.containsKey(t2.tableName)) {
if(checkSelection(rowval, t2.tableColDef, t2.tableName)) {
/*if(t2.tableName.equalsIgnoreCase("orders")){
ConfigureVariables.countcheck = ConfigureVariables.countcheck + 1;
}*/
//System.out.println("yes2");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}}
else {
//System.out.println("Hello");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}
}
}
if(ConfigureVariables.mapinsert.containsKey(t2.tableName)) {
for(String str: ConfigureVariables.mapinsert.get(t2.tableName)) {
row = str;
String[] rowval = row.split("\\|");
/*if(t2.tableName.equalsIgnoreCase("ORDERS")) {
ConfigureVariables.countcheck = ConfigureVariables.countcheck +1;
}*/
if(ConfigureVariables.tableCondition.containsKey(t2.tableName)) {
if(checkSelection(rowval, t2.tableColDef, t2.tableName)) {
/*if(t2.tableName.equalsIgnoreCase("orders")){
ConfigureVariables.countcheck = ConfigureVariables.countcheck + 1;
}*/
//System.out.println("yes2");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}}
else {
//System.out.println("Hello");
String key="";
for(int i =0;i<rind.size();i++) {
key += rowval[rind.get(i)];
key +="|";
}
if(hashtable.containsKey(key)) {
ArrayList<String> value = hashtable.get(key);
for(String s: value) {
//System.out.println(s+"|"+row);
joinresult.tuples.add(s+"|"+row);
//writeresult(s+"|"+row, joinresult);
}
}
}
}
}
//System.out.println(t2.tableName+":"+ConfigureVariables.countcheck);
//}
}
// DO NOT FORGET TO DELETE HASHTABLE FILE AFTER JOIN!!!
//File f = new File(ConfigureVariables.temppath+"hashmap.obj");
//if(f.exists()) {
// f.delete();
//}
//System.out.println("End"+joinresult.tableName+"size:"+joinresult.tuples.size());
return joinresult;
}
public static int getcolIndex(ArrayList<String> cn, String col) {
for(int i =0; i<cn.size();i++) {
//System.out.println(cn.get(i)+":"+col);
if(col.equals(cn.get(i))) {
return i;
}
}
return 0;
}
public static String getJoinColumn(String t1, String t2) {
Expression left = null;
Expression right = null;
String tbleft = null;
String tbright =null;
String lcol = null;
String rcol=null;
for(Expression e: ConfigureVariables.joinCondition) {
left = (Expression)((BinaryExpression) e).getLeftExpression();
right = (Expression)((BinaryExpression) e).getRightExpression();
if(left instanceof Column && right instanceof Column) {
//System.out.println("Hello");
tbleft = (String)(((Column) left).getTable().getName());
tbright = (String)(((Column) right).getTable().getName());
lcol =(String)(((Column) left).getColumnName());
rcol = (String)(((Column) right).getColumnName());
//System.out.println(tbleft+":"+tbright+":"+lcol+":"+rcol);
}
if(((t1.equals(tbleft)&& t2.equals(tbright))||((t1.equals(tbright)&& t2.equals(tbleft)))&& lcol.equals(rcol))) {
return lcol;
}
}
return null;
}
public static boolean checkSelection(String[] str, ArrayList<ColumnDefinition> columnDefinitionList, String tableName) {
//System.out.println("Check sel");
PrimitiveValue t[];
t = Tuple.getTupleValSplit(str, columnDefinitionList);
Evaluator eval = new Evaluator(t);
ArrayList<Expression> tc = ConfigureVariables.tableCondition.get(tableName);
//System.out.println("tc::" + tableName +"::"+ tc);
//System.exit(0);
if(tc==null) {
return true;
}
//System.out.println("SIZE:"+tc.size()+tableName+tc);
if(!tc.isEmpty()) {
//System.out.println("NON EMPTY");
int count =0;
for(Expression condition : tc) {
try {
//System.out.println(tableName+":"+condition);
/*if(tableName.equalsIgnoreCase("ORDERS")) {
ConfigureVariables.countcheck = ConfigureVariables.countcheck +1;
}*/
PrimitiveValue result = eval.eval(condition);
BooleanValue boolResult = (BooleanValue)result;
if(boolResult.getValue()) {
count++;
//for( PrimitiveValue v : tuple)
//System.out.print(v.toRawString()+'|');
//System.out.println();
}
else {
return false;
}
if(count == tc.size()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
else {
return true;
}
return true; //Default return type ( Not in use).
}
public static void writeresult(String jrow, MyTable joinresult) {
FileWriter fw = null;
BufferedWriter bw =null;
File f = new File(ConfigureVariables.temppath+joinresult.tableName+ConfigureVariables.FILEEXTENSION);
if(!f.exists()) {
try {
f.createNewFile();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fw = new FileWriter(f.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(jrow+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static MyTable CrossProduct(MyTable t1, MyTable t2) {
FileWriter fw =null;
BufferedWriter bw =null;
File file = new File(ConfigureVariables.temppath+t1.tableName+"|"+t2.tableName+ConfigureVariables.FILEEXTENSION);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
String row1=null;
while((row1=t1.readtuple())!=null) {
String tbl1=t1.tableName;
if(t1.tableName.contains("|")) {
String tbl[] = t1.tableName.split("\\|");
tbl1 = tbl[tbl.length-1];
}
String rowval1[] = row1.split("\\|");
if(checkSelection(rowval1, t1.tableColDef, tbl1)) {
String row2 = null;
while((row2=t2.readtuple())!=null) {
String rowval2[] = row2.split("\\|");
if(checkSelection(rowval2, t2.tableColDef, t2.tableName))
bw.write(row1+"|"+row2+"\n");
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
}
class joinSpec{
String jcl;
String jcr;
}
|
package demo.utility;
import demo.domain.Ad;
import demo.domain.AdRepository;
import demo.domain.Campaign;
import demo.domain.CampaignRepository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class AdsCampaignManager {
private static AdsCampaignManager instance = null;
private static final double minPriceThreshold = 0.0;
// private final AdRepository adRepository;
private final CampaignRepository campaignRepository;
private AdsCampaignManager(CampaignRepository campaignRepository) {
this.campaignRepository = campaignRepository;
}
public static AdsCampaignManager getInstance(CampaignRepository campaignRepository) {
if (instance == null) {
instance = new AdsCampaignManager(campaignRepository);
}
return instance;
}
public List<Ad> DedupeByCampaignId(List<Ad> adsCandidates) {
List<Ad> dedupedAds = new ArrayList<Ad>();
HashSet<Long> campaignIdSet = new HashSet<Long>();
for (Ad ad : adsCandidates) {
if (!campaignIdSet.contains(ad.getCampaignId())) {
dedupedAds.add(ad);
campaignIdSet.add(ad.getCampaignId());
}
}
return dedupedAds;
}
public List<Ad> ApplyBudget(List<Ad> adsCandidates) {
List<Ad> ads = new ArrayList<Ad>();
try {
for (int i = 0; i < adsCandidates.size() - 1; i++) {
Ad ad = adsCandidates.get(i);
Long campaignId = ad.getCampaignId();
double budget = this.campaignRepository.getCampaignByCampaignId(campaignId).getBudget();
System.out.println("AdsCampaignManager ad.costPerClick= " + ad.getCostPerClick());
System.out.println("AdsCampaignManager campaignId= " + campaignId);
System.out.println("AdsCampaignManager budget left = " + budget);
if (ad.getCostPerClick() <= budget && ad.getCostPerClick() >= minPriceThreshold) {
ads.add(ad);
budget = budget - ad.getCostPerClick();
this.campaignRepository.saveAndFlush(new Campaign(campaignId, budget));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ads;
}
}
|
/*
* Copyright 2002-2018 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.core.style;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Utility class that builds pretty-printing {@code toString()} methods
* with pluggable styling conventions. By default, ToStringCreator adheres
* to Spring's {@code toString()} styling conventions.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 1.2.2
*/
public class ToStringCreator {
/**
* Default ToStringStyler instance used by this ToStringCreator.
*/
private static final ToStringStyler DEFAULT_TO_STRING_STYLER =
new DefaultToStringStyler(StylerUtils.DEFAULT_VALUE_STYLER);
private final StringBuilder buffer = new StringBuilder(256);
private final ToStringStyler styler;
private final Object object;
private boolean styledFirstField;
/**
* Create a ToStringCreator for the given object.
* @param obj the object to be stringified
*/
public ToStringCreator(Object obj) {
this(obj, (ToStringStyler) null);
}
/**
* Create a ToStringCreator for the given object, using the provided style.
* @param obj the object to be stringified
* @param styler the ValueStyler encapsulating pretty-print instructions
*/
public ToStringCreator(Object obj, @Nullable ValueStyler styler) {
this(obj, new DefaultToStringStyler(styler != null ? styler : StylerUtils.DEFAULT_VALUE_STYLER));
}
/**
* Create a ToStringCreator for the given object, using the provided style.
* @param obj the object to be stringified
* @param styler the ToStringStyler encapsulating pretty-print instructions
*/
public ToStringCreator(Object obj, @Nullable ToStringStyler styler) {
Assert.notNull(obj, "The object to be styled must not be null");
this.object = obj;
this.styler = (styler != null ? styler : DEFAULT_TO_STRING_STYLER);
this.styler.styleStart(this.buffer, this.object);
}
/**
* Append a byte field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, byte value) {
return append(fieldName, Byte.valueOf(value));
}
/**
* Append a short field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, short value) {
return append(fieldName, Short.valueOf(value));
}
/**
* Append a integer field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, int value) {
return append(fieldName, Integer.valueOf(value));
}
/**
* Append a long field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, long value) {
return append(fieldName, Long.valueOf(value));
}
/**
* Append a float field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, float value) {
return append(fieldName, Float.valueOf(value));
}
/**
* Append a double field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, double value) {
return append(fieldName, Double.valueOf(value));
}
/**
* Append a boolean field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, boolean value) {
return append(fieldName, Boolean.valueOf(value));
}
/**
* Append a field value.
* @param fieldName the name of the field, usually the member variable name
* @param value the field value
* @return this, to support call-chaining
*/
public ToStringCreator append(String fieldName, @Nullable Object value) {
printFieldSeparatorIfNecessary();
this.styler.styleField(this.buffer, fieldName, value);
return this;
}
private void printFieldSeparatorIfNecessary() {
if (this.styledFirstField) {
this.styler.styleFieldSeparator(this.buffer);
}
else {
this.styledFirstField = true;
}
}
/**
* Append the provided value.
* @param value the value to append
* @return this, to support call-chaining.
*/
public ToStringCreator append(Object value) {
this.styler.styleValue(this.buffer, value);
return this;
}
/**
* Return the String representation that this ToStringCreator built.
*/
@Override
public String toString() {
this.styler.styleEnd(this.buffer, this.object);
return this.buffer.toString();
}
}
|
package com.memory.platform.modules.system.base.service.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.memory.platform.common.collect.EList;
import com.memory.platform.common.collect.ListFilter;
import com.memory.platform.core.service.impl.BaseServiceImpl;
import com.memory.platform.hibernate4.criteria.HqlFilter;
import com.memory.platform.modules.system.base.dao.ISystemResourceDao;
import com.memory.platform.modules.system.base.model.SystemDept;
import com.memory.platform.modules.system.base.model.SystemResource;
import com.memory.platform.modules.system.base.model.SystemRole;
import com.memory.platform.modules.system.base.model.SystemUser;
import com.memory.platform.modules.system.base.service.ISystemBasedataLinkService;
import com.memory.platform.modules.system.base.service.ISystemPrivilegeService;
import com.memory.platform.modules.system.base.service.ISystemResourceService;
@Service("systemResourceServiceImpl")
public class SystemResourceServiceImpl extends BaseServiceImpl<SystemResource> implements ISystemResourceService {
@Autowired
@Qualifier("systemResourceDaoImpl")
private ISystemResourceDao systemResourceDao;
@Autowired
@Qualifier("systemPrivilegeServiceImpl")
private ISystemPrivilegeService systemPrivilegeService;
@Autowired
@Qualifier("systemBasedataLinkServiceImpl")
private ISystemBasedataLinkService systemBasedataLinkService;
@Override
public List<SystemResource> loadTreeGrid(HqlFilter hqlFilter) {
List<SystemResource> l = new ArrayList<SystemResource>();
String hql = "select distinct t from SystemResource t join t.syroles role join role.syusers user";
final List<SystemResource> resource_role = find(hql + hqlFilter.getWhereHql(), hqlFilter.getParams());
l.addAll(resource_role);
hql = "select distinct t from SystemResource t join t.syorganizations organization join organization.syusers user";
final List<SystemResource> resource_organization = find(hql + hqlFilter.getWhereHql(), hqlFilter.getParams());
l.addAll(resource_organization);
l = new ArrayList<SystemResource>(new HashSet<SystemResource>(l));// 去重
Collections.sort(l, new Comparator<SystemResource>() {// 排序
@Override
public int compare(SystemResource o1, SystemResource o2) {
if (o1.getOrderCode() == null) {
o1.setOrderCode(1000);
}
if (o2.getOrderCode() == null) {
o2.setOrderCode(1000);
}
return o1.getOrderCode().compareTo(o2.getOrderCode());
}
});
return l;
}
@Override
public List<SystemResource> listResourcesByRoleIds(String[] roleIds) {
List<SystemResource> masterResourceList = new ArrayList<SystemResource>();
if(roleIds == null || roleIds.length < 1) {
return masterResourceList;
}
masterResourceList = systemPrivilegeService.listAccessData(SystemResource.class, SystemRole.class, roleIds,"orderCode");
List<SystemResource> result = filterList(masterResourceList);
return result;
}
@Override
public List<SystemResource> listResourcesByDeptIds(String[] deptIds) {
List<SystemResource> masterResourceList = new ArrayList<SystemResource>();
if(deptIds == null || deptIds.length < 1) {
return masterResourceList;
}
masterResourceList = systemPrivilegeService.listAccessData(SystemResource.class, SystemDept.class, deptIds,"orderCode");
List<SystemResource> result = filterList(masterResourceList);
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
private List filterList(List list) {
List<SystemResource> result = null;
result = EList.filterList(list, new ListFilter<SystemResource, SystemResource>() {
Map<String,SystemResource> map = Maps.newHashMap();
List<SystemResource> result = EList.newArrayList();
@Override
public List<SystemResource> filter(List<SystemResource> inputList) {
if(inputList == null) {
return result;
}
for(SystemResource input : inputList) {
if(input != null && !Strings.isNullOrEmpty(input.getId())) {
if(map.get(input.getId()) == null) {
map.put(input.getId(), input);
result.add(input);
}
}
}
return result;
}
});
return result;
}
@Override
public List<SystemResource> listResourcesByUserId(String userId) {
List<SystemRole> userRoleList = null;
String[] userRoleIds;
userRoleList = systemBasedataLinkService.listLinkData(SystemRole.class, SystemUser.class, userId);
userRoleIds = new String[userRoleList.size()];
for(int i=0;i<userRoleList.size();i++) {
userRoleIds[i] = userRoleList.get(i).getId();
}
List<SystemDept> userDeptList = null;
String[] userDeptIds;
userDeptList = systemBasedataLinkService.listLinkData(SystemDept.class, SystemUser.class, userId);
userDeptIds = new String[userDeptList.size()];
for(int i=0;i<userDeptList.size();i++) {
userDeptIds[i] = userDeptList.get(i).getId();
}
List<SystemResource> result1 = listResourcesByRoleIds(userRoleIds);
List<SystemResource> result2 = listResourcesByDeptIds(userDeptIds);
result1.addAll(result2);
List<SystemResource> result = filterList(result1);
return result;
}
@Override
public List<SystemResource> listResourcesByUserRole(String userId) {
List<SystemRole> userRoleList = null;
String[] userRoleIds;
userRoleList = systemBasedataLinkService.listLinkData(SystemRole.class, SystemUser.class, userId);
userRoleIds = new String[userRoleList.size()];
for(int i=0;i<userRoleList.size();i++) {
userRoleIds[i] = userRoleList.get(i).getId();
}
return listResourcesByRoleIds(userRoleIds);
}
@Override
public List<SystemResource> listResourcesByUserDept(String userId) {
List<SystemDept> userDeptList = null;
String[] userDeptIds;
userDeptList = systemBasedataLinkService.listLinkData(SystemDept.class, SystemUser.class, userId);
userDeptIds = new String[userDeptList.size()];
for(int i=0;i<userDeptList.size();i++) {
userDeptIds[i] = userDeptList.get(i).getId();
}
return listResourcesByDeptIds(userDeptIds);
}
}
|
/*
* Copyright 2011 Matthew Precious
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mattprecious.smsfix;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
/**
* SMS Time Fix main activity window
*
* @author Matthew Precious
*
*/
public class SMSFix extends PreferenceActivity {
private SharedPreferences settings;
private ListPreference offsetMethod;
private EditTextPreference editOffset;
private CheckBoxPreference cdmaBox;
static final int MENU_HELP_ID = 0;
static final int MENU_ABOUT_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
settings = ((PreferenceScreen) findPreference("preferences")).getSharedPreferences();
offsetMethod = (ListPreference) findPreference("offset_method");
editOffset = (EditTextPreference) findPreference("offset");
cdmaBox = (CheckBoxPreference) findPreference("cdma");
// use the global status variable to set the appearance of the "Active"
// checkbox
settings.edit().putBoolean("active", FixService.running).commit();
// register a listener for changes
settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// if "Active" has changed, start or stop the service
if (key.equals("active")) {
toggleService(sharedPreferences.getBoolean(key, false));
}
// update offset and CDMA to reflect the new status or method
// change
toggleOffset();
toggleCDMA();
}
});
// set the offset field to be a decimal numver
// TODO: change this to hours and minutes. received an email where the
// user had a 20 minute offset, so decimals will not work
editOffset.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
// set the initial status of the offset and CDMA
toggleOffset();
toggleCDMA();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_HELP_ID, 0, R.string.menu_help).setIcon(android.R.drawable.ic_menu_help);
menu.add(0, MENU_ABOUT_ID, 0, R.string.menu_about).setIcon(android.R.drawable.ic_menu_info_details);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_HELP_ID:
startActivity(new Intent(SMSFix.this, Help.class));
return true;
case MENU_ABOUT_ID:
startActivity(new Intent(SMSFix.this, About.class));
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* Enable or disable the fixing service.
*
* @param active
*/
public void toggleService(boolean active) {
if (active) {
startService(new Intent(this, FixService.class));
} else {
stopService(new Intent(this, FixService.class));
}
}
/**
* Toggle whether or not the "Offset" option should be enabled.
* If the method is manual and the service is active.
*
*/
public void toggleOffset() {
editOffset.setEnabled(offsetMethod.getValue().equals("manual") && offsetMethod.isEnabled());
}
/**
* Toggle whether or not the "CDMA' option should be enabled.
* If the method is phone and the service is active.
*/
public void toggleCDMA() {
cdmaBox.setEnabled(!offsetMethod.getValue().equals("phone") && offsetMethod.isEnabled());
}
}
|
package ua.siemens.dbtool.dao.hibernate;
import org.springframework.stereotype.Repository;
import ua.siemens.dbtool.dao.WorkPackageDAO;
import ua.siemens.dbtool.model.entities.WorkPackage;
import javax.persistence.Query;
import java.util.Collection;
/**
* The impementation of {@link WorkPackageDAO} interface
*
* @author Perevoznyk Pavlo
* creation date 10 May 2017
* @version 1.0
*/
@Repository
public class WorkPackageDAOhiber extends GenericDAOhiber<WorkPackage, Long> implements WorkPackageDAO {
private final String FIND_BY_PROJECT_ID = "from WorkPackage where project_id = :projectId";
public WorkPackageDAOhiber() {
super(WorkPackage.class);
}
@Override
public Collection<WorkPackage> findAllByProjectID(Long projectID) {
Query query = entityManager.createQuery(FIND_BY_PROJECT_ID);
query.setParameter("projectId", projectID);
return query.getResultList();
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atlassian.theplugin.configuration;
import com.atlassian.theplugin.commons.ServerType;
import com.atlassian.theplugin.commons.cfg.BambooServerCfg;
import com.atlassian.theplugin.commons.cfg.JiraServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerIdImpl;
import com.atlassian.theplugin.idea.config.serverconfig.model.*;
import junit.framework.TestCase;
/**
* User: pmaruszak
*/
public class ServerTreeModelTest extends TestCase {
private ServerTreeModel stm;
private RootNode root;
private JiraServerCfg jiraServerCfg;
private BambooServerCfg bambooServerCfg;
protected void setUp() throws Exception {
super.setUp();
root = new RootNode();
stm = new ServerTreeModel(root);
jiraServerCfg = new JiraServerCfg("jiraServer", new ServerIdImpl(), true);
bambooServerCfg = new BambooServerCfg("bambooServer", new ServerIdImpl());
}
public void testDefaultValue() {
int types = 0;
for (ServerType st : ServerType.values()) {
if (!st.isPseudoServer() && !st.equals(ServerType.FISHEYE_SERVER)) {
++types;
}
}
assertEquals(stm.getChildCount(root), types);
}
public void testAddJiraServer() {
tryTestServer(jiraServerCfg, ServerType.JIRA_SERVER);
}
public void testAddBambooServer() {
tryTestServer(bambooServerCfg, ServerType.BAMBOO_SERVER);
}
private void tryTestServer(ServerCfg serverCfg, ServerType serverType) {
ServerNode serverNode = ServerNodeFactory.getServerNode(serverCfg);
ServerTypeNode typeNode = stm.getServerTypeNode(serverType);
assertTrue(typeNode != null);
stm.insertNodeInto(serverNode, typeNode, serverNode.getChildCount());
assertEquals(typeNode.getChildCount(), 1);
assertEquals(typeNode.getChildAt(0), serverNode);
}
public void testRemoveJiraServer() {
tryTestServer(jiraServerCfg, ServerType.JIRA_SERVER);
tryTestRemoveServer(ServerType.JIRA_SERVER);
}
public void testRemoveBambooServer() {
tryTestServer(bambooServerCfg, ServerType.BAMBOO_SERVER);
tryTestRemoveServer(ServerType.BAMBOO_SERVER);
}
private void tryTestRemoveServer(ServerType serverType) {
ServerTypeNode typeNode = stm.getServerTypeNode(serverType);
typeNode.remove(0);
stm.nodeStructureChanged(typeNode);
assertEquals(typeNode.getChildCount(), 1);
assertTrue(typeNode.getChildAt(0) instanceof ServerInfoNode);
assertEquals(((ServerInfoNode) typeNode.getChildAt(0)).getServerType(), serverType);
}
}
|
package nbi.protocols;
import java.util.List;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.slf4j.LoggerFactory;import org.slf4j.Logger;
/**
* @author robert.lee
* @version $Revision: 1.0 $
*/
public interface SFTPBehavior {
/**
* Method setResources.
* @param manager StandardFileSystemManager
* @param sftpUri String
* @param opts FileSystemOptions
* @param log Logger
* @param messageList List<String>
*/
void setResources(final StandardFileSystemManager manager ,final String sftpUri,final FileSystemOptions opts, final Logger log,final List<String> messageList);
}
|
package logic.bonus;
import controller.Game;
public class DropTargetBonus extends AbstractBonus {
/**
* When this bonus is triggered, a million points are added to the game and
* all bumpers are upgraded.
*
* @param game the game controller object.
*/
@Override
public void trigger(Game game) {
this.timesTriggered++;
game.addScore(1000000);
game.getCurrentTable().upgradeAllBumpers();
}
}
|
package com.icanit.app.entity;
// default package
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* AppMerchant entity. @author MyEclipse Persistence Tools
*/
public class AppMerchant implements java.io.Serializable {
// Fields
public Integer id;
public AppMerchantType appMerchantType;
public String merName,password,location,map,pic,phone,detail;
public double minCost;
public Date regTime;
public Set<AppGoods> appGoodses = new HashSet<AppGoods>(0);
public Set<AppCommunity> appCommunities = new HashSet<AppCommunity>(0);
} |
import java.util.Arrays;
import java.util.Scanner;
public class DiceTest{
private static int N, numbers[], totalCnt;
private static boolean[] isSelected;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); // 주사위 던진횟수
numbers = new int[N];
isSelected = new boolean[7]; // 주사위 1~6 까지이므로
int mode = sc.nextInt(); // 주사위 던지는 모드
totalCnt = 0;
switch(mode) {
case 1: // 주사위 던지기 1: 중복순열
dice1(0);
break;
case 2: // 주사위 던지기 2: 순열
dice2(0);
case 3: // 주사위 던지기 3: 중복조합
dice3(0, 1); // 주사위 눈 1부터 시작하니까 시작점 1
break;
case 4:
dice4(0, 1); // 주사위 던지기 4: 조합
}
System.out.println("총 경우의 수: " + totalCnt);
}
// 증복순열
private static void dice1(int cnt) {
if(cnt == N) { // 기저파트
++totalCnt;
System.out.println(Arrays.toString(numbers));
return;
}
for(int i=1; i<=6; i++) { // 유도파트
numbers[cnt] = i;
dice1(cnt+1);
}
}
// 순열
private static void dice2(int cnt) {
if(cnt == N) { // 기저파트
++totalCnt;
System.out.println(Arrays.toString(numbers));
return;
}
for(int i=1; i<=6; i++) { // 유도파트
if(isSelected[i]) continue;
numbers[cnt] = i;
isSelected[i] = true;
dice2(cnt+1);
isSelected[i] = false;
}
}
// 중복조합
private static void dice3(int cnt, int start) {
// 기저파트
if(cnt == N) {
++totalCnt;
System.out.println(Arrays.toString(numbers));
return;
}
for(int i=start; i<= 6; i++) { // 유도파트
numbers[cnt] = i;
dice3(cnt+1, i); // 중복 조합이니까 i+1 아니고 i
}
}
// 조합
private static void dice4(int cnt, int start) {
// 기저파트
if(cnt == N) {
++totalCnt;
System.out.println(Arrays.toString(numbers));
return;
}
for(int i=start; i<= 6; i++) { // 유도파트
numbers[cnt] = i;
dice4(cnt+1, i+1); // 일반조합이니까 현재수 다음부터뽑음 i+1
}
}
}
|
package com.example.androidclient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Welcome extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
public void login(View view) {
Intent l = new Intent(this, Login.class);
startActivity(l);
}
public void help(View view) {
Intent h = new Intent(this, Help.class);
startActivity(h);
}
public void developer(View view) {
Intent d = new Intent(this, Developer.class);
startActivity(d);
}
}
|
package com.lessons.notes.note;
import android.os.Bundle;
import android.view.ContextMenu;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.lessons.notes.R;
import com.lessons.notes.note.domain.Note;
public class NotesFragment extends Fragment {
private NotesAdapter adapter;
private NoteViewModel viewModel;
private static final int MY_DEFAULT_DURATION = 1000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_notes, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(requireActivity()).get(NoteViewModel.class);
viewModel.getNotesLiveData().observe(getViewLifecycleOwner(), notes -> {
adapter.setData(notes);
});
viewModel.getSavedNote().observe(getViewLifecycleOwner(), note -> {
if (note != null) {
viewModel.updateNote(note);
}
});
if (savedInstanceState == null) {
viewModel.requestNotes();
}
initRecyclerView(view);
initTopMenu(view);
}
private void initRecyclerView(View view) {
adapter = new NotesAdapter(this);
adapter.setClickListener(new NotesAdapter.OnNoteClicked() {
@Override
public void onNoteClicked(Note note) {
viewModel.select(note);
}
@Override
public void onEditClicked(Note note) {
viewModel.select(note.setForEdit(true));
}
});
RecyclerView notesList = view.findViewById(R.id.list_layot);
RecyclerView.LayoutManager lm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
notesList.setLayoutManager(lm);
notesList.setAdapter(adapter);
DefaultItemAnimator animator = new DefaultItemAnimator();
animator.setAddDuration(MY_DEFAULT_DURATION);
animator.setRemoveDuration(MY_DEFAULT_DURATION);
animator.setChangeDuration(MY_DEFAULT_DURATION);
notesList.setItemAnimator(animator);
}
private void initTopMenu(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
Menu menu = toolbar.getMenu();
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
viewModel.filterByName(s);
return true;
}
@Override
public boolean onQueryTextChange(String s) {
viewModel.filterByName(s);
return true;
}
});
toolbar.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.action_sort_by_name) {
viewModel.sortByName();
return true;
}
if (item.getItemId() == R.id.action_sort_by_date) {
viewModel.sortByDate();
return true;
}
if (item.getItemId() == R.id.action_add) {
viewModel.select(new Note().setForEdit(true));
return true;
}
return false;
});
}
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = requireActivity().getMenuInflater();
inflater.inflate(R.menu.note_context_menu, menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_update:
viewModel.select(adapter.getNoteMenuPosition().setForEdit(true));
return true;
case R.id.action_delete:
viewModel.delete(adapter.getNoteMenuPosition().setForEdit(true));
return true;
}
return super.onContextItemSelected(item);
}
} |
/**
*
*/
package com.examples.androface;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.util.Log;
import android.view.View;
/**
* @author wdavid01
*
*/
public class FaceDetectionView extends View
{
private static final String tag = FaceDetectionView.class.getName();
private static final int NUM_FACES = 10;
private FaceDetector arrayFaces;
private final FaceDetector.Face getAllFaces[] = new FaceDetector.Face[NUM_FACES];
private FaceDetector.Face getFace = null;
private final PointF eyesMidPts[] = new PointF[NUM_FACES];
private final float eyesDistance[] = new float[NUM_FACES];
private Bitmap sourceImage;
private final Paint tmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint pOuterBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint pInnerBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);
private int picWidth, picHeight;
private float xRatio, yRatio;
private ImageLoader mImageLoader = null;
public FaceDetectionView(Context context, String imagePath)
{
super(context);
init();
mImageLoader = ImageLoader.getInstance(context);
sourceImage = mImageLoader.loadFromFile(imagePath);
detectFaces();
}
private void init()
{
Log.d(tag, "Init()...");
pInnerBullsEye.setStyle(Paint.Style.FILL);
pInnerBullsEye.setColor(Color.RED);
pOuterBullsEye.setStyle(Paint.Style.STROKE);
pOuterBullsEye.setColor(Color.RED);
tmpPaint.setStyle(Paint.Style.STROKE);
tmpPaint.setTextAlign(Paint.Align.CENTER);
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.RGB_565;
}
private void loadImage(String imagePath)
{
sourceImage = mImageLoader.loadFromFile(imagePath);
}
@Override
protected void onDraw(Canvas canvas)
{
Log.d(tag, "onDraw()...");
xRatio = getWidth() * 1.0f / picWidth;
yRatio = getHeight() * 1.0f / picHeight;
canvas.drawBitmap(sourceImage, null, new Rect(0, 0, getWidth(), getHeight()), tmpPaint);
for (int i = 0; i < eyesMidPts.length; i++)
{
if (eyesMidPts[i] != null)
{
pOuterBullsEye.setStrokeWidth(eyesDistance[i] / 6);
canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 2, pOuterBullsEye);
canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 6, pInnerBullsEye);
}
}
}
private void detectFaces()
{
Log.d(tag, "detectFaces()...");
picWidth = sourceImage.getWidth();
picHeight = sourceImage.getHeight();
arrayFaces = new FaceDetector(picWidth, picHeight, NUM_FACES);
arrayFaces.findFaces(sourceImage, getAllFaces);
for (int i = 0; i < getAllFaces.length; i++)
{
getFace = getAllFaces[i];
try
{
PointF eyesMP = new PointF();
getFace.getMidPoint(eyesMP);
eyesDistance[i] = getFace.eyesDistance();
eyesMidPts[i] = eyesMP;
Log.i("Face", i + " " + getFace.confidence() + " " + getFace.eyesDistance() + " " + "Pose: (" + getFace.pose(FaceDetector.Face.EULER_X) + "," + getFace.pose(FaceDetector.Face.EULER_Y) + "," + getFace.pose(FaceDetector.Face.EULER_Z) + ")" + "Eyes Midpoint: (" + eyesMidPts[i].x + "," + eyesMidPts[i].y + ")");
}
catch (Exception e)
{
Log.e("Face", i + " is null");
}
}
}
}
|
package com.maxmind.geoip2.model;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.maxmind.db.MaxMindDbConstructor;
import com.maxmind.db.MaxMindDbParameter;
import com.maxmind.db.Network;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Continent;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.MaxMind;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.RepresentedCountry;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.Traits;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a model for the data returned by the City Plus web
* service and the City database.
*
* @see <a href="https://dev.maxmind.com/geoip/docs/web-services?lang=en">GeoIP2 Web
* Services</a>
*/
public final class CityResponse extends AbstractCityResponse {
@MaxMindDbConstructor
public CityResponse(
@JsonProperty("city") @MaxMindDbParameter(name = "city") City city,
@JsonProperty("continent") @MaxMindDbParameter(name = "continent") Continent continent,
@JsonProperty("country") @MaxMindDbParameter(name = "country") Country country,
@JsonProperty("location") @MaxMindDbParameter(name = "location") Location location,
@JsonProperty("maxmind") @MaxMindDbParameter(name = "maxmind") MaxMind maxmind,
@JsonProperty("postal") @MaxMindDbParameter(name = "postal") Postal postal,
@JsonProperty("registered_country") @MaxMindDbParameter(name = "registered_country")
Country registeredCountry,
@JsonProperty("represented_country") @MaxMindDbParameter(name = "represented_country")
RepresentedCountry representedCountry,
@JsonProperty("subdivisions") @MaxMindDbParameter(name = "subdivisions")
ArrayList<Subdivision> subdivisions,
@JacksonInject("traits") @JsonProperty("traits") @MaxMindDbParameter(name = "traits")
Traits traits
) {
super(city, continent, country, location, maxmind, postal, registeredCountry,
representedCountry, subdivisions, traits);
}
public CityResponse(
CityResponse response,
String ipAddress,
Network network,
List<String> locales
) {
super(response, ipAddress, network, locales);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.clothing.webservices.demo.request;
/**
*
* @author Chanh Thanh
*/
public class LoginRequest {
private String idToken;
public String getIdToken() {
return idToken;
}
public void setIdToken(String idToken) {
this.idToken = idToken;
}
public LoginRequest(String idToken) {
this.idToken = idToken;
}
public LoginRequest() {
}
}
|
package aaa.assignment2.tests;
import aaa.*;
import aaa.assignment2.algorithms.*;
public class Test1
{
public static final int TEST_NUM_RUNS = 1000;
public static void main(String[] args)
{
for (float ALPHA: new float[] {0.1f, 0.2f, 0.3f, 0.4f, 0.5f})
{
for (float GAMMA: new float[] {0.1f, 0.3f, 0.5f, 0.7f, 0.9f})
{
System.out.println("\n\\alpha = " + ALPHA + ", \\gamma = " + GAMMA);
ModelFreeAlgorithm.performanceClear();
Thread[] t = new Thread[10];
for (int i = 0; i < 10; i++)
{
t[i] = new runAlgorithm(ALPHA, GAMMA);
t[i].start();
}
for (int i = 0; i < 10; i++)
{
try {
t[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ModelFreeAlgorithm.printPerformance();
}
}
}
}
class runAlgorithm extends Thread
{
private aaa.State env = new StateReduced(0, 0, 5, 5);
private final float ALPHA, GAMMA;
public runAlgorithm(float ALPHA, float GAMMA)
{
this.ALPHA = ALPHA;
this.GAMMA = GAMMA;
}
public void run()
{
new QLearning(env, this.ALPHA, this.GAMMA, 0.1f, 15, false, true);
}
}
|
package com.lagardien.plkviolation;
/**
* Ijaaz Lagardien
* 214167542
* Group 3A
* Dr B. Kabaso
* Date: 13 March 2016
*/
public class TestPLK {
public static void main(String[] args) {
// TODO Auto-generated method stub
PLKDemo demo = new PLKDemo();
Order order = new Order();
demo.process(order);
}
}
|
package com.redislabs.research;
import java.util.*;
/**
* Created by dvirsky on 07/02/16.
*/
public class Spec {
public enum IndexingType {
FullText,
Prefix,
Geo,
Numeric,
}
public static class Field {
public String name;
public IndexingType type;
public Field(String name, IndexingType type) {
this.name = name;
this.type = type;
}
public boolean matches(String fieldName) {
return this.name.equals(fieldName);
}
}
public static class PrefixField extends Field {
public boolean indexSuffixes;
public PrefixField(String name, boolean indexSuffixes) {
super(name, IndexingType.Prefix);
this.indexSuffixes = indexSuffixes;
}
}
public static PrefixField prefix(String name, boolean indexSuffixes) {
return new PrefixField(name, indexSuffixes);
}
public static class GeoField extends Field {
public int precision;
public GeoField(String name, int precision) {
super(name, IndexingType.Geo);
this.precision = precision;
}
}
public static Field geo(String name, int precision) {
return new GeoField(name, precision);
}
public static Field numeric(String name) {
return new Field(name, IndexingType.Numeric);
}
/**
* FullText field spec.
* It is unique in that the name represnets the index and not the field itself.
* You can pass it a list of fields to index, or a map of field=>weight if you want
* weighted indexing of the fields
*/
public static class FulltextField extends Field {
public Map<String,Double> fields;
public FulltextField(String name, Map<String, Double> weightedFields) {
super(name, IndexingType.FullText);
this.fields = weightedFields;
}
public FulltextField(String name, String ...fields) {
super(name, IndexingType.FullText);
this.fields = new HashMap<>();
for (String f : fields) {
this.fields.put(f, 1d);
}
}
public double getFieldWeight(String fieldName) {
Double w = this.fields.get(fieldName);
return w == null ? 0 : w;
}
/**
* A fullText index matches a field if it's either the same name or if the field list contains the field name
* @param fieldName
* @return
*/
@Override
public boolean matches(String fieldName) {
return super.matches(fieldName) || fields.containsKey(fieldName);
}
}
public static Field fulltext(String name, String ...fields) {
return new FulltextField(name, fields);
}
public static Field fulltext(String name, Map<String, Double> weightedFields) {
return new FulltextField(name, weightedFields);
}
public List<Field> fields;
public Spec(Field ...fields) {
this.fields = Arrays.asList(fields);
}
}
|
package nathan.banking;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public abstract class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = -343937814567666796L;
protected String username;
protected String password;
protected HashMap<String, String> personalInfo;
protected ArrayList<Account> connectedAccounts;
protected User()
{
}
public void addConnectedAccount(Account a)
{
this.connectedAccounts.add(a);
}
public String getUsername()
{
return username;
}
public boolean checkPassword(String pass)
{
return this.password.compareTo(pass) == 0;
}
public void setPassword(String oldPass, String newPass)
{
if((this.checkPassword(oldPass) && this.equals(DataIO.currentUser)) || DataIO.currentUser.isAdmin())
{
password = newPass;
}
else
{
System.out.println("Password change failed.");
if(!(this.checkPassword(oldPass)))
{
System.out.println("Password entered was incorrect.");
}
}
}
protected String getPersonalInfoBit(String key)
{
return this.personalInfo.get(key);
}
public abstract boolean canViewUserData();
public abstract boolean canSetUserData();
public abstract boolean canApproveAccounts();
public abstract boolean isAdmin();
public void listAccounts()
{
for(Account a : connectedAccounts)
{
System.out.print("\tAccount number " + a.getAccountNumber());
if(a.isJoint())
{
System.out.print(" joint with users:");
a.printConnectedUsers(true);
}
System.out.println();
}
}
public void printInfo()
{
System.out.println("User info for " + username);
for(Map.Entry<String, String> e : this.personalInfo.entrySet())
{
System.out.println("\t" + e.getKey() + ": " + e.getValue());
}
}
}
|
package com.fest.pecfestBackend.entity;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
import java.util.UUID;
@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Confirmation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long tokenId;
@Column(name="confirmation_token")
private String confirmationToken;
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false,name = "id")
private User user;
public Confirmation(User user) {
this.user = user;
createdDate = new Date();
confirmationToken = UUID.randomUUID().toString()+user.getId();
}
}
|
package za.ac.cput.chapter5assignment.abstractfactory;
/**
* Created by student on 2015/03/12.
*/
public class JustFruit implements FruitFactory {
private static JustFruit fruit = null;
private JustFruit(){
}
public static JustFruit getInstance(){
if(fruit == null){
fruit = new JustFruit();
}
return fruit;
}
public Fruit getName(String n){
if(n.equalsIgnoreCase("Apple")){
return new Apple();
}else{
return new Cherry();
}
}
@Override
public String fruitColor(String c) {
return "Green";
}
}
|
package ru.malichenko.market.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import ru.malichenko.market.entities.OrderEntity;
import java.util.List;
import java.util.stream.Collectors;
@Data
@NoArgsConstructor
public class OrderDto {
private List<OrderItemDto> items;
private int price;
private String address;
public OrderDto(OrderEntity o){
this.items = o.getItems().stream().map(OrderItemDto::new).collect(Collectors.toList());
this.price = o.getPrice();
this.address = o.getAddress();
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.rsocket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import io.netty.buffer.PooledByteBufAllocator;
import io.rsocket.Payload;
import io.rsocket.util.ByteBufPayload;
import io.rsocket.util.DefaultPayload;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBuffer;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link PayloadUtils}.
*
* @author Rossen Stoyanchev
* @since 5.2
*/
class PayloadUtilsTests {
private LeakAwareNettyDataBufferFactory nettyBufferFactory =
new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT);
@AfterEach
void tearDown() throws Exception {
this.nettyBufferFactory.checkForLeaks(Duration.ofSeconds(5));
}
@Test
void retainAndReleaseWithNettyFactory() {
Payload payload = ByteBufPayload.create("sample data");
DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, this.nettyBufferFactory);
try {
assertThat(buffer).isInstanceOf(NettyDataBuffer.class);
assertThat(((NettyDataBuffer) buffer).getNativeBuffer().refCnt()).isEqualTo(1);
assertThat(payload.refCnt()).isEqualTo(0);
}
finally {
DataBufferUtils.release(buffer);
}
}
@Test
void retainAndReleaseWithDefaultFactory() {
Payload payload = ByteBufPayload.create("sample data");
DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, DefaultDataBufferFactory.sharedInstance);
assertThat(buffer).isInstanceOf(DefaultDataBuffer.class);
assertThat(payload.refCnt()).isEqualTo(0);
}
@Test
void createWithNettyBuffers() {
NettyDataBuffer data = createNettyDataBuffer("sample data");
NettyDataBuffer metadata = createNettyDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata);
try {
assertThat(payload).isInstanceOf(ByteBufPayload.class);
assertThat(payload.data()).isSameAs(data.getNativeBuffer());
assertThat(payload.metadata()).isSameAs(metadata.getNativeBuffer());
}
finally {
payload.release();
}
}
@Test
void createWithDefaultBuffers() {
DataBuffer data = createDefaultDataBuffer("sample data");
DataBuffer metadata = createDefaultDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata);
assertThat(payload).isInstanceOf(DefaultPayload.class);
assertThat(payload.getDataUtf8()).isEqualTo(data.toString(UTF_8));
assertThat(payload.getMetadataUtf8()).isEqualTo(metadata.toString(UTF_8));
}
@Test
void createWithNettyAndDefaultBuffers() {
NettyDataBuffer data = createNettyDataBuffer("sample data");
DefaultDataBuffer metadata = createDefaultDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata);
try {
assertThat(payload).isInstanceOf(ByteBufPayload.class);
assertThat(payload.data()).isSameAs(data.getNativeBuffer());
assertThat(payload.getMetadataUtf8()).isEqualTo(metadata.toString(UTF_8));
}
finally {
payload.release();
}
}
@Test
void createWithDefaultAndNettyBuffers() {
DefaultDataBuffer data = createDefaultDataBuffer("sample data");
NettyDataBuffer metadata = createNettyDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata);
try {
assertThat(payload).isInstanceOf(ByteBufPayload.class);
assertThat(payload.getDataUtf8()).isEqualTo(data.toString(UTF_8));
assertThat(payload.metadata()).isSameAs(metadata.getNativeBuffer());
}
finally {
payload.release();
}
}
@Test
void createWithNettyBuffer() {
NettyDataBuffer data = createNettyDataBuffer("sample data");
Payload payload = PayloadUtils.createPayload(data);
try {
assertThat(payload).isInstanceOf(ByteBufPayload.class);
assertThat(payload.data()).isSameAs(data.getNativeBuffer());
}
finally {
payload.release();
}
}
@Test
void createWithDefaultBuffer() {
DataBuffer data = createDefaultDataBuffer("sample data");
Payload payload = PayloadUtils.createPayload(data);
assertThat(payload).isInstanceOf(DefaultPayload.class);
assertThat(payload.getDataUtf8()).isEqualTo(data.toString(UTF_8));
}
private NettyDataBuffer createNettyDataBuffer(String content) {
NettyDataBuffer buffer = this.nettyBufferFactory.allocateBuffer();
buffer.write(content, StandardCharsets.UTF_8);
return buffer;
}
private DefaultDataBuffer createDefaultDataBuffer(String content) {
DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256);
buffer.write(content, StandardCharsets.UTF_8);
return buffer;
}
}
|
package com.beike.wap.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;
import com.beike.dao.GenericDaoImpl;
import com.beike.wap.dao.MUserProfileWapDao;
import com.beike.wap.entity.MUserTemp;
/**
* <p>
* Title: 用户数据库基本操作
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: Sinobo
* </p>
*
* @date 2011-09-22
* @author kun.wang
* @version 1.0
*/
@Repository("mUserProfileWapDao")
public class MUserProfileWapDaoImpl extends GenericDaoImpl<MUserTemp, Long> implements MUserProfileWapDao{
private static Log log = LogFactory.getLog(MUserProfileWapDaoImpl.class);
@Override
public void deleteByMobile(String mobile) {
String sql = "delete from beiker_userprofile_wap where mobile = ?";
List<Object> list = new ArrayList<Object>();
list.add(mobile);
getSimpleJdbcTemplate().update(sql, list.toArray(new Object[] {}));
}
@Override
public int isMobileExist(String mobile) {
String sql = "select count(1) from beiker_userprofile_wap where mobile = ?";
List<Object> list = new ArrayList<Object>();
list.add(mobile);
return getSimpleJdbcTemplate().queryForInt(sql,
list.toArray(new Object[] {}));
}
@Override
public int findByIdAndCode(long id, String vcode) {
String sql = "select count(1) from beiker_userprofile_wap where id = ? and vcode = ?";
List<Object> list = new ArrayList<Object>();
list.add(id);
list.add(vcode);
return getSimpleJdbcTemplate().queryForInt(sql,
list.toArray(new Object[] {}));
}
@Override
public void addUserTemp(MUserTemp userTemp) {
String sql = "insert into beiker_userprofile_wap (mobile, vcode, regdate, password,email, customerkey) values (?,?,?,?,?,?)";
List<Object> list = new ArrayList<Object>();
list.add(userTemp.getMobile());
list.add(userTemp.getvCode());
list.add(new Date());
list.add(userTemp.getPassword());
list.add(userTemp.getEmail());
list.add(userTemp.getCustomerkey());
getSimpleJdbcTemplate().update(sql, list.toArray(new Object[] {}));
}
@Override
public void updateByMobile(MUserTemp userTemp) {
String sql = "update beiker_userprofile_wap set vcode = ?,password=?,customerkey=?,email=?, regdate = NOW() where mobile = ?";
List<Object> list = new ArrayList<Object>();
list.add(userTemp.getvCode());
list.add(userTemp.getPassword());
list.add(userTemp.getCustomerkey());
list.add(userTemp.getEmail());
list.add(userTemp.getMobile());
getSimpleJdbcTemplate().update(sql, list.toArray(new Object[] {}));
}
@Override
public void updatePassword(MUserTemp userTemp) {
String sql = "update beiker_userprofile_wap set password=?, customerkey=?,email=?, regdate = NOW() where mobile = ?";
List<Object> list = new ArrayList<Object>();
list.add(userTemp.getPassword());
list.add(userTemp.getCustomerkey());
list.add(userTemp.getEmail());
list.add(userTemp.getMobile());
getSimpleJdbcTemplate().update(sql, list.toArray(new Object[] {}));
}
@Override
public MUserTemp findByMobile(String mobile) {
String sql = "select * from beiker_userprofile_wap where mobile = ?";
List<Object> list = new ArrayList<Object>();
list.add(mobile);
List<MUserTemp> rsList = getSimpleJdbcTemplate().query(sql, new RowMapperImpl(),list.toArray(new Object[] {}));
if(rsList == null || rsList.size() == 0)
{
return null;
}
return rsList.get(0);
}
@Override
public MUserTemp findById(long id) {
String sql = "select * from beiker_userprofile_wap where id = ?";
List<Object> list = new ArrayList<Object>();
list.add(id);
List<MUserTemp> rsList = getSimpleJdbcTemplate().query(sql, new RowMapperImpl(),list.toArray(new Object[] {}));
if(rsList == null || rsList.size() == 0)
{
return null;
}
return rsList.get(0);
}
@Override
public void deleteById(Long id) {
String sql = "DELETE FROM beiker_userprofile_wap where id = ?";
try {
List<Object> list = new ArrayList<Object>();
list.add(id);
getSimpleJdbcTemplate().update(sql, id);
} catch (Exception e) {
e.printStackTrace();
log.info("delete beiker_userprofile_wap error \n id = " + id);
}
}
protected class RowMapperImpl implements ParameterizedRowMapper<MUserTemp> {
public MUserTemp mapRow(ResultSet rs, int rowNum) throws SQLException {
MUserTemp user = new MUserTemp();
user.setId(rs.getInt("id"));
user.setMobile(rs.getString("mobile"));
user.setRegDate(rs.getDate("regdate"));
user.setvCode(rs.getInt("vcode"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setCustomerkey(rs.getString("customerkey"));
return user;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.