text stringlengths 10 2.72M |
|---|
package StackCalculator.Exceptions;
public class VarNameHasAlreadyExist extends Exception {
public VarNameHasAlreadyExist(String name) {
super("Var name: " + name + " has already exist!");
}
}
|
package com.example.kimnamgil.testapplication;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import com.example.kimnamgil.testapplication.data.Person;
import com.example.kimnamgil.testapplication.widget.PersonView;
public class MainActivity extends AppCompatActivity {
ListView listView;
Drawable photoView;
ImageView photo;
PersonAdapter mAdapter;
@Override
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
super.onSupportActionModeStarted(mode);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
photo = (ImageView)findViewById(R.id.imageView);
listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
mAdapter = new PersonAdapter();
mAdapter.setAdapterLisner(new PersonAdapter.OnAdapterClickLisner()
{
@Override
public void onAdatper(Person person, PersonView view, PersonAdapter adapter)
{
photo.setImageDrawable(person.getPhoto());
photo.setVisibility(View.VISIBLE);
}
});
photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
photo.setVisibility(View.GONE);
}
});
listView.setAdapter(mAdapter);
initData();
}
private void initData()
{
Person person = new Person();
photoView = getResources().getDrawable(R.drawable.icon);
person.setEmail("tompx@namgil");
person.setName("Namgil");
person.setPhoto(photoView);
for(int i = 0; i < 20; i++)
{
mAdapter.add(person);
}
}
}
|
package batching.offline;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
* @author Diego Didona
* @email didona@gsd.inesc-id.pt
* @since 01/04/14
*/
public class BatchingPaoloAnalyticalOracle extends BatchingAnalyticalOracle {
private double num1;
private double num2;
private double num3;
private double num4;
private double num5;
private double num6;
private double net;
private double seqRate;
private double c;
private double bookKeepRate;
private double minRateToStartBatching;
private double maxThroughput;
private static double cutOff = 100000;
private static double DEF_NET = 200;
private static double DEF_SEQ_RATE = 5000;
private static double DEF_C = 2;
private static double DEF_BOOK_RATE = 1.0D / 26000D;
public static void cutOff100() {
cutOff = 100000;
}
public static void cutOff500() {
cutOff = 500000;
}
public static void overrideDEFS(double net, double seq, double c, double book) {
DEF_NET = net;
DEF_SEQ_RATE = seq;
DEF_C = c;
DEF_BOOK_RATE = book;
}
private static final int MAX_BATCHING_VALUE = 128;
private static final int MAX_RATE_VALUE = 20000;
public static void paperValues() {
overrideDEFS(200, 5000, 2, 1D / 26000D);
}
public static void optimalMAPEValues() {
if (cutOff == 500000)
overrideDEFS(2500, 8000, 3, 4.16e-5);
else {
overrideDEFS(2500, 6000, 4, 5.55e-5);
}
}
public static void optimalRMSEValues() {
if (cutOff == 500000) {
overrideDEFS(18000, 8500, 5, 5.88e-5);
} else {
overrideDEFS(500, 6000, 4, 5.55e-5);
}
}
public static void mediumMAPEValues() {
if (cutOff == 500000) {
//overrideDEFS(2000, 7000, 2, 1.42e-5);
overrideDEFS(0, 8000, 2, 1.78e-5);
} else {
overrideDEFS(2000, 6000, 2, 1.85e-5);
}
}
public static void mediumRMSEValues() {
if (cutOff == 500000) {
overrideDEFS(6000, 8500, 2, 3.92e-5);
} else {
overrideDEFS(1500, 6000, 2, 3.33e-5);
}
}
public BatchingPaoloAnalyticalOracle() {
net = DEF_NET;
seqRate = DEF_SEQ_RATE;
c = DEF_C;
bookKeepRate = DEF_BOOK_RATE;
precomputeNumQuantities();
}
@Override
protected double analyticalSelfDelivery(double lambda, double b) {
return getVal(lambda, (int) b);
}
private void precomputeNumQuantities() {
minRateToStartBatching = computeMinRateToBatch();
maxThroughput = computeMaxThroughput();
num1 = c * (-1.0D + bookKeepRate * seqRate);
num2 = bookKeepRate * c * seqRate;
num3 = seqRate - c * seqRate;
num4 = bookKeepRate * c;
num5 = Math.pow(seqRate, 2.0D);
num6 = 1.0D + -c;
}
/**
* Return the minimum arrival rate after which it is convenient to start batching messages
*
* @return
*/
private double computeMinRateToBatch() {
return (bookKeepRate * seqRate * seqRate) / 2.0D
+
0.5D * Math.sqrt(
(4.0D * seqRate * seqRate + bookKeepRate * bookKeepRate * c * Math.pow(seqRate, 4))
/
c
);
}
/**
* Return the max throughput according to the model
*
* @return
*/
private double computeMaxThroughput() {
return Math.max(seqRate, (-1.0D + c) / (bookKeepRate * c));
}
public int getOptimalBatchingValue(double rate) {
// it is checked whether it's above the 95% of the max_throughput. At max throughput the max batching factor in fact is infinite
if (rate > maxThroughput * .99D)
return MAX_BATCHING_VALUE;
if (rate < minRateToStartBatching)
return 1;
return Math.min(
(int) Math.ceil(
(seqRate + rate * num1)
/
(num3 + rate * num2)
+
Math.sqrt(
(c * Math.pow(seqRate + rate * num1, 2.0D))
/
(
(1.0D + rate * num4)
*
Math.pow((num6 + rate * num4), 2.0D)
*
num5
)
)
)
,
MAX_BATCHING_VALUE
);
/*
num1= c * (-1.0D + bookKeepRate * seqRate);
num2= bookKeepRate * c * seqRate;
num3=seqRate - c * seqRate;
num4=bookKeepRate *c;
num5=Math.pow(seqRate, 2.0D);
num6= 1.0D + -c ;
return Math.min(
(int) Math.ceil(
( seqRate + rate * c * (-1.0D + bookKeepRate * seqRate) )
/
( ( 1.0D + (-1.0D + rate*bookKeepRate) * c ) * seqRate )
+
Math.sqrt(
( c * Math.pow( seqRate + rate * c * (-1.0D + bookKeepRate*seqRate) , 2.0D ) )
/
(
(1.0D + rate * bookKeepRate *c )
*
Math.pow( ( 1.0D + ( -1.0D + rate * bookKeepRate ) * c) , 2.0D)
*
Math.pow(seqRate, 2.0D)
)
)
)
,
MAX_BATCHING_VALUE
);
*/
}
/**
* Returns the value of the desired using bilinear interpolation if the (rate,batch) coordinates fall into the known
* region. Otherwise it returns the value of the closer cell in the region, without attempting extrapolation.
*
* @param rate
* @param batch
*/
public double getVal(double rate, int batch) {
double ret;
if (rate <= 0)
ret = 0;
else if (batch < 1)
ret = 0;
else if (1.0D / (1.0D / seqRate + ((double) batch - 1.0D) / (c * rate) + (bookKeepRate) * ((double) batch - 1.0D)) - rate / (double) batch < 1.0D)
ret = cutOff;
else
ret = net + 1000000.0D / (1.0D / (1.0D / seqRate + ((double) batch - 1.0D) / (c * rate) + (bookKeepRate) * ((double) batch - 1.0D)) - rate / (double) batch);
if (ret > cutOff || ret < 0)
ret = cutOff;
return ret;
}
public void dumpGrid() {
try {
// Create file
FileWriter fstream = new FileWriter("analyticalDataGrid");
BufferedWriter out = new BufferedWriter(fstream);
for (int rate = 1; rate <= MAX_RATE_VALUE; rate += 1000) {
for (int batch = 1; batch < MAX_BATCHING_VALUE; batch += batch) {
//out.write(rate+" "+batch+" "+getVal(rate,batch)+"\n");
System.out.print(rate + " " + batch + " " + getVal(rate, batch) + "\n");
}
if (rate == 1)
rate = 0;
System.out.print("\n");
}
//Close the output stream
out.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//System.out.println("optimal["+msgRates[rate]+"]:"+getOptimalBatchingValue(rate));
}
public void dumpOptimal() {
for (int rate = 1000; rate <= 14000; rate += 1000)
System.out.println(rate + " " + getOptimalBatchingValue(rate));
//System.out.println(getOptimalBatchingValue(rate));
}
public void stressTest() {
long t = System.nanoTime();
for (int rate = 1; rate <= 14000; rate += 1)
getOptimalBatchingValue(rate);
t = System.nanoTime() - t;
System.out.println(t / 14000);
}
public static void main(String[] args) {
BatchingPaoloAnalyticalOracle.cutOff500();
BatchingPaoloAnalyticalOracle.mediumMAPEValues();
new BatchingPaoloAnalyticalOracle().dumpGrid();
}
}
|
package org.tempuri;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="branch_code" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="appid" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"branchCode",
"appid"
})
@XmlRootElement(name = "GetZoneAcct")
public class GetZoneAcct {
@XmlElement(name = "branch_code")
protected int branchCode;
protected int appid;
/**
* Gets the value of the branchCode property.
*
*/
public int getBranchCode() {
return branchCode;
}
/**
* Sets the value of the branchCode property.
*
*/
public void setBranchCode(int value) {
this.branchCode = value;
}
/**
* Gets the value of the appid property.
*
*/
public int getAppid() {
return appid;
}
/**
* Sets the value of the appid property.
*
*/
public void setAppid(int value) {
this.appid = value;
}
}
|
package controller.cliente;
import Excecoes.AnimalInexistenteException;
import controller.TelaPrincipalController;
import entity.Animal;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import entity.Cliente;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
public class TelaRemoverPetController implements Initializable {
private TelaPrincipalController telaPrincipalController;
private TelaClienteController telaClienteController;
@FXML
AnchorPane telaRemoverPet;
@FXML
Button removerBtn;
private Cliente cliente;
private AnchorPane parent;
@FXML
private Button sairBtn;
@FXML
private Button menuPrincipal;
@FXML
private Button carrinhoBtn;
@FXML
private Label nomePet;
@FXML
private ChoiceBox boxIdPet;
private int idAnimalSelecionado;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public void atualizar() {
List<Integer> ids = new ArrayList<>();
for (Animal animal : cliente.getPets().values()) {
ids.add(animal.getId());
}
ObservableList<Integer> opcoes = FXCollections.observableArrayList(ids);
boxIdPet.setItems(opcoes);
boxIdPet.setOnAction((e) -> {
try {
idAnimalSelecionado = (int) boxIdPet.getSelectionModel().getSelectedItem();
nomePet.setText(cliente.getPets().get(idAnimalSelecionado).getNome());
} catch (Exception ex) {
idAnimalSelecionado = -1;
}
});
}
public void setTelaPrincipalController(TelaPrincipalController telaPrincipalController) {
this.telaPrincipalController = telaPrincipalController;
}
@FXML
public void irRemoverPet() {
try {
if (idAnimalSelecionado > -1) {
cliente.removerAnimal(idAnimalSelecionado);
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmação");
alert.setHeaderText(null);
alert.setContentText("Animal Removido");
alert.showAndWait();
atualizar();
}
} catch (AnimalInexistenteException ex) {
Logger.getLogger(TelaRemoverPetController.class.getName()).log(Level.SEVERE, null, ex);
}
}//fim do metodo
@FXML
public void irCarrinho(ActionEvent event) {
try {
AnchorPane telaCarrinho = FXMLLoader.load(TelaPrincipalController.class.getResource("/view/TelaCarrinho.fxml"));
telaRemoverPet.getChildren().clear();
telaRemoverPet.getChildren().add(telaCarrinho);
} catch (IOException ex) {
}//fim do catch
}//fim do metodo
@FXML
private void irMenu(ActionEvent event) {
if (telaClienteController != null) {
telaClienteController.irTelaInicialCliente();
}
}//fim do metodo
public void setTelaClienteController(TelaClienteController telaClienteController) {
this.telaClienteController = telaClienteController;
}
@FXML
public void sair(ActionEvent event) {
telaPrincipalController.retornar();
}//dim do metodo
public void setParent(AnchorPane a) {
this.parent = a;
}
}
|
/*
* Test 84:
*
* Data la disponibilita' delle procedure di deallocazione delle variabili
* locali, testeremo ora il Nesting di variabili locali.
*/
class Kanu {}
public class corinto
{
void proc()
{
int i=1;
{
float i=1;
int k=10;
{
Kanu k; /*
* Variabile locale duplicata, k del blocco precedente
* e' a livello 5 cosi' come questa.
*/
int m;
}
{
float m=1.1; /*
* Ok. m del blocco precedente e' ormai scartata
* dalla symbol-table.
*/
for (m=1; m!=0; m--); /*
* Ok. il for usa m dichiarata in
* questo blocco.
*/
for (int m=1; m==0; m++); /*
* errore!!! m duplicata.
*/
}
}
}
}
|
package com.jd.myadapterlib.common;
import android.support.annotation.LayoutRes;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import com.jd.myadapterlib.R;
import com.jd.myadapterlib.dinterface.DOnItemClickListener;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* Auther: Jarvis Dong
* Time: on 2016/12/23 0023
* Name:
* OverView: page 的切换,pagerAdapter
* Usage:
*/
public class CommonPagerAdapter extends PagerAdapter {
public CommonPagerAdapter() {
}
private int mAutoPlayInterval = 2000;
private boolean mAutoPlayAble = false;
private List<View> mViews;
private List<View> mHackyViews;
private List<? extends Object> mObject;
PlayRunnable mPlayRunnable;
public void setmAutoPlayInterval(int mAutoPlayInterval) {
this.mAutoPlayInterval = mAutoPlayInterval;
}
public void setmAutoPlayAble(boolean mAutoPlayAble) {
this.mAutoPlayAble = mAutoPlayAble;
}
public void startAutoPlay(ViewPager mViewpager) {
stopAutoPlay(mViewpager);
if (mAutoPlayAble && mViewpager != null) {
mViewpager.postDelayed(mPlayRunnable, mAutoPlayInterval);
}
}
public void stopAutoPlay(ViewPager mViewpager) {
if (mAutoPlayAble && mViewpager != null) {
mViewpager.removeCallbacks(mPlayRunnable);
}
}
private void switchToNextPage(ViewPager mViewPager) {
if (mViewPager != null) {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
}
}
/**
* 设置每一页的控件、数据模型
*
* @param mViews
* @param mObject
* @param mItemListener
*/
public void setmViews(ViewPager mViewpager, List<View> mViews, List<? extends Object> mObject, OnItemFillListener mItemListener) {
if (mAutoPlayAble && mViews != null && mViews.size() < 3 && mHackyViews == null) {
mAutoPlayAble = false;
}
this.mViews = mViews;
this.mObject = mObject;
this.mItemListener = mItemListener;
if (mViews != null) {
if (mAutoPlayAble) {
int zeroItem = Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2) % mViews.size();
mViewpager.setCurrentItem(zeroItem);
} else if (mViewpager != null) {
mViewpager.setCurrentItem(0);
}
}
notifyDataSetChanged();
}
/**
* Attention :must be canAutoPlay;
*/
public void setScroll(ViewPager mViewpager, boolean isScroll) {
if (mPlayRunnable == null)
mPlayRunnable = new PlayRunnable(mViewpager);
if (mAutoPlayAble) {
if (isScroll) {
startAutoPlay(mViewpager);
} else {
stopAutoPlay(mViewpager);
}
}
}
/**
* 设置布局资源id、数据模型
*
* @param mViewpager
* @param layoutResId
* @param models
*/
public void setmViews(ViewPager mViewpager, @LayoutRes int layoutResId, List<? extends Object> models, OnItemFillListener mItemListener) {
mViews = new ArrayList<>();
if (models != null) {
for (int i = 0; i < models.size(); i++) {
mViews.add(View.inflate(mViewpager.getContext(), layoutResId, null));
}
}
if (mAutoPlayAble && mViews.size() < 3) {
mHackyViews = new ArrayList<>(mViews);
mHackyViews.add(View.inflate(mViewpager.getContext(), layoutResId, null));
if (mHackyViews.size() == 2) {
mHackyViews.add(View.inflate(mViewpager.getContext(), layoutResId, null));
}
}
setmViews(mViewpager, mViews, models, mItemListener);
}
/**
* 设置数据模型和文案,布局资源默认为ImageView
*
* @param models 每一页的数据模型集合
*/
public void setmViews(ViewPager mViewpager, List<? extends Object> models, OnItemFillListener mItemListener) {
setmViews(mViewpager, R.layout.common_banner_item, models, mItemListener);
}
@Override
public int getCount() {
return mViews == null ? 0 : (mAutoPlayAble ? Integer.MAX_VALUE : mViews.size());
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
final int finalPosition = position % mViews.size();
View view = (View) mViews.get(finalPosition);
if (container.equals(view.getParent())) {
container.removeView(view);
}
if (mListener != null) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClick(v, finalPosition, mObject == null ? null : mObject.get(finalPosition));
}
});
}
if (mItemListener != null) {
mItemListener.fillBannerItem(view, mObject == null ? null : mObject.get(finalPosition), finalPosition);
}
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (!mAutoPlayAble) {
container.removeView((View) mViews.get(position));
} else {
int finalPosition = position % mViews.size();
container.removeView((View) mViews.get(finalPosition));
}
}
private DOnItemClickListener mListener;
public void setDOnItemClickListener(DOnItemClickListener mListener) {
this.mListener = mListener;
}
public static <T extends View> T generateView(int id, View view) {
return (T) view.findViewById(id);
}
private OnItemFillListener mItemListener;
public interface OnItemFillListener {
void fillBannerItem(View view, Object model, int position);
}
public class PlayRunnable implements Runnable {
private final WeakReference<View> weakReference;
public PlayRunnable(ViewPager viewPager) {
weakReference = new WeakReference<View>(viewPager);
}
@Override
public void run() {
ViewPager mViewPager = (ViewPager) weakReference.get();
if (mViewPager != null) {
switchToNextPage(mViewPager);
startAutoPlay(mViewPager);//需要handler去滑动;
}
}
}
}
|
package com.tdr.registrationv3.ui.activity.car;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.google.gson.Gson;
import com.tdr.registrationv3.R;
import com.tdr.registrationv3.adapter.FragmentPageAdapter;
import com.tdr.registrationv3.bean.InfoBean;
import com.tdr.registrationv3.bean.RegisterPutBean;
import com.tdr.registrationv3.constants.BaseConstants;
import com.tdr.registrationv3.rx.RxBus;
import com.tdr.registrationv3.ui.activity.base.NoLoadingBaseActivity;
import com.tdr.registrationv3.ui.fragment.register.ChangeRegisterCarFragment;
import com.tdr.registrationv3.ui.fragment.register.ChangeRegisterPeopleFragment;
import com.tdr.registrationv3.utils.PhotoUtils;
import com.tdr.registrationv3.view.NoScrollViewPager;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class ChangeRegisterMainActivity extends NoLoadingBaseActivity {
@BindView(R.id.register_vp)
NoScrollViewPager registerVp;
public int vehicleType = 1;
public RegisterPutBean registerPutBean;
public InfoBean infoBean;
private Intent resultData;
@Override
protected void initTitle() {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
registerPutBean = new RegisterPutBean();
String dataJson = bundle.getString(BaseConstants.data);
infoBean = new Gson().fromJson(dataJson, InfoBean.class);
registerPutBean.setVehicleType(infoBean.getElectriccars().getVehicleType());
}
}
@Override
protected void initData(Bundle savedInstanceState) {
vehicleType = getIntent().getExtras().getInt("car_type");
List<Fragment> mFragmentList = new ArrayList<>();
mFragmentList.add(new ChangeRegisterCarFragment());
mFragmentList.add(new ChangeRegisterPeopleFragment());
registerVp.setNoScroll(true);
registerVp.setAdapter(new FragmentPageAdapter(getSupportFragmentManager(), mFragmentList));
setVpCurrentItem(0);
}
public void setVpCurrentItem(int page) {
registerVp.setCurrentItem(page);
}
@Override
protected int getLayoutId() {
return R.layout.activity_register_main;
}
@Override
protected void submitRequestData() {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
resultData= data;
switch (requestCode) {
case PhotoUtils.CAMERA_REQESTCODE:
RxBus.getDefault().post(BaseConstants.BUX_SEND_CODE, PhotoUtils.CAMERA_REQESTCODE);
break;
case PhotoUtils.ALBUM_REQESTCODE:
RxBus.getDefault().post(BaseConstants.BUX_SEND_CODE,PhotoUtils.ALBUM_REQESTCODE);
break;
}
}
}
}
|
package com.richdapice.flowfinder.models;
import com.google.auto.value.AutoValue;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
@AutoValue
public abstract class DefaultTimeZone {
public abstract String zoneOffSet();
public abstract String zoneAbbreviation();
public static JsonAdapter<DefaultTimeZone> jsonAdapter(Moshi moshi){
return new AutoValue_DefaultTimeZone.MoshiJsonAdapter(moshi);
}
}
|
package main.java;
import main.java.Request.HTTPRequestType;
import main.java.connection.HTTPConnection;
/**
* A simple class to test the application
*/
public class Main {
public static void main(String[] args) {
// HTTPConnection connection = new HTTPConnection.HTTPConnectionBuilder().withHTTPHeaders(true).withPath("/").build();
// HTTPConnection connection2 = new HTTPConnection.HTTPConnectionBuilder().withHTTPHeaders(true).withPath("/root")
// .build();
// HTTPConnection connection3 = new HTTPConnection.HTTPConnectionBuilder().withHTTPHeaders(true)
// .withPath("/getRequest").withRequesttype(HTTPRequestType.GET).build();
HTTPConnection connection4 = new HTTPConnection.HTTPConnectionBuilder().withHTTPHeaders(true)
.withPath("/getWithETAG").withRequesttype(HTTPRequestType.GET).withETAG("Sample ETAG").build();
System.out.println(connection4);
}
}
|
/**
*
*/
package controller.input;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import Graphs.*;
/**
* @author Aloy
*
*/
public class File_input {
/**
*
*/
public File_input(String n) {
// TODO Auto-generated constructor stub
String name = n; // this is the name of the file which will contain all the directed edge values
Write_to_file(n);
}
private void Write_to_file(String file) {
try {
FileOutputStream out= new FileOutputStream();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package nachos.vm;
import nachos.machine.*;
import nachos.threads.*;
import nachos.userprog.*;
import nachos.vm.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
/**
* A kernel that can support multiple demand-paging user processes.
*/
public class VMKernel extends UserKernel {
/**
* Allocate a new VM kernel.
*/
public VMKernel() {
super();
}
/**
* Initialize this kernel.
*/
public void initialize(String[] args) {
super.initialize(args);
pagesAvailableMutex = new Lock();
swapLock = new Lock();
swapPages = new LinkedList<>();
swapFile = ThreadedKernel.fileSystem.open("swapfile", true);
spnTotal = 0;
pinLock = new Lock();
numPagesPinned = 0;
managerLock = new Lock();
pinCV = new Condition(pinLock);
// initialize manager
manager = new pageManager[Machine.processor().getNumPhysPages()];
for(int i = 0; i < Machine.processor().getNumPhysPages(); i++){
manager[i] = new pageManager(null, null, false);
}
}
/**
* Test this kernel.
*/
public void selfTest() {
super.selfTest();
}
/**
* Start running user programs.
*/
public void run() {
super.run();
}
/**
* Terminate this kernel. Never returns.
*/
public void terminate() {
super.terminate();
}
// dummy variables to make javac smarter
private static VMProcess dummy1 = null;
private static final char dbgVM = 'v';
// protected static Lock pagesAvailableMutex;
//
// protected static LinkedList<Integer> pagesAvailable = new LinkedList<>();
//
// protected static int pidCounter;
//
// protected static Lock pidCounterMutex;
//
// protected static int runningProcessCounter;
//
// protected static Lock runningProcessCounterMutex;
// static ArrayList<TranslationEntry> victims;
// static int victim;
static OpenFile swapFile;
static int spnTotal;
static LinkedList<Integer> swapPages;
static Lock swapLock;
/**
* Page manager class that keeps the translation entry,
* owner process and pin status for all physical pages in memory.
* Inspired by piazza post
*/
static class pageManager {
private TranslationEntry translationEntry;
private VMProcess process;
private boolean isPinned;
public pageManager(TranslationEntry entry, VMProcess process, boolean pin) {
translationEntry = entry;
process = process;
isPinned = pin;
}
public TranslationEntry getEntry() {
return this.translationEntry;
}
public void setEntry(TranslationEntry entry) {
this.translationEntry = entry;
}
public VMProcess getProcess() {
return this.process;
}
public void setProcess(VMProcess process) {
this.process = process;
}
public boolean getPinStatus() {
return this.isPinned;
}
public void setPinStatus(boolean pin) {
this.isPinned = pin;
}
}
static pageManager[] manager;
static Condition pinCV;
static Lock pinLock;
static int numPagesPinned;
static Lock managerLock;
}
|
package com.mercadolibre.bootcampmelifrescos.dtos.response;
import com.mercadolibre.bootcampmelifrescos.model.Batch;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BatchWithDueDateResponse {
private Long batchNumber;
private Long productId;
private String productTypeId;
private LocalDate dueDate;
private int quantity;
public BatchWithDueDateResponse(Batch batch) {
this.batchNumber = batch.getId();
this.productId = batch.getProduct().getId();
this.productTypeId = batch.getProduct().getCategory().getCode();
this.dueDate = batch.getDueDate();
this.quantity = batch.getCurrentQuantity();
}
}
|
/*
* Copyright 2002-2020 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.web.servlet.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.View;
/**
* A {@link org.springframework.web.servlet.ViewResolver} implementation that uses
* bean definitions in a {@link ResourceBundle}, specified by the bundle basename.
*
* <p>The bundle is typically defined in a properties file, located in the classpath.
* The default bundle basename is "views".
*
* <p>This {@code ViewResolver} supports localized view definitions, using the
* default support of {@link java.util.PropertyResourceBundle}. For example, the
* basename "views" will be resolved as class path resources "views_de_AT.properties",
* "views_de.properties", "views.properties" - for a given Locale "de_AT".
*
* <p>Note: This {@code ViewResolver} implements the {@link Ordered} interface
* in order to allow for flexible participation in {@code ViewResolver} chaining.
* For example, some special views could be defined via this {@code ViewResolver}
* (giving it 0 as "order" value), while all remaining views could be resolved by
* a {@link UrlBasedViewResolver}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see java.util.ResourceBundle#getBundle
* @see java.util.PropertyResourceBundle
* @see UrlBasedViewResolver
* @see BeanNameViewResolver
* @deprecated as of 5.3, in favor of Spring's common view resolver variants
* and/or custom resolver implementations
*/
@Deprecated
public class ResourceBundleViewResolver extends AbstractCachingViewResolver
implements Ordered, InitializingBean, DisposableBean {
/** The default basename if no other basename is supplied. */
public static final String DEFAULT_BASENAME = "views";
private String[] basenames = new String[] {DEFAULT_BASENAME};
private ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader();
@Nullable
private String defaultParentView;
@Nullable
private Locale[] localesToInitialize;
private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered
/* Locale -> BeanFactory */
private final Map<Locale, BeanFactory> localeCache = new HashMap<>();
/* List of ResourceBundle -> BeanFactory */
private final Map<List<ResourceBundle>, ConfigurableApplicationContext> bundleCache = new HashMap<>();
/**
* Set a single basename, following {@link java.util.ResourceBundle} conventions.
* The default is "views".
* <p>{@code ResourceBundle} supports different locale suffixes. For example,
* a base name of "views" might map to {@code ResourceBundle} files
* "views", "views_en_au" and "views_de".
* <p>Note that ResourceBundle names are effectively classpath locations: As a
* consequence, the JDK's standard ResourceBundle treats dots as package separators.
* This means that "test.theme" is effectively equivalent to "test/theme",
* just like it is for programmatic {@code java.util.ResourceBundle} usage.
* @see #setBasenames
* @see ResourceBundle#getBundle(String)
* @see ResourceBundle#getBundle(String, Locale)
*/
public void setBasename(String basename) {
setBasenames(basename);
}
/**
* Set an array of basenames, each following {@link java.util.ResourceBundle}
* conventions. The default is a single basename "views".
* <p>{@code ResourceBundle} supports different locale suffixes. For example,
* a base name of "views" might map to {@code ResourceBundle} files
* "views", "views_en_au" and "views_de".
* <p>The associated resource bundles will be checked sequentially when resolving
* a message code. Note that message definitions in a <i>previous</i> resource
* bundle will override ones in a later bundle, due to the sequential lookup.
* <p>Note that ResourceBundle names are effectively classpath locations: As a
* consequence, the JDK's standard ResourceBundle treats dots as package separators.
* This means that "test.theme" is effectively equivalent to "test/theme",
* just like it is for programmatic {@code java.util.ResourceBundle} usage.
* @see #setBasename
* @see ResourceBundle#getBundle(String)
* @see ResourceBundle#getBundle(String, Locale)
*/
public void setBasenames(String... basenames) {
this.basenames = basenames;
}
/**
* Set the {@link ClassLoader} to load resource bundles with.
* Default is the thread context {@code ClassLoader}.
*/
public void setBundleClassLoader(ClassLoader classLoader) {
this.bundleClassLoader = classLoader;
}
/**
* Return the {@link ClassLoader} to load resource bundles with.
* <p>Default is the specified bundle {@code ClassLoader},
* usually the thread context {@code ClassLoader}.
*/
protected ClassLoader getBundleClassLoader() {
return this.bundleClassLoader;
}
/**
* Set the default parent for views defined in the {@code ResourceBundle}.
* <p>This avoids repeated "yyy1.(parent)=xxx", "yyy2.(parent)=xxx" definitions
* in the bundle, especially if all defined views share the same parent.
* <p>The parent will typically define the view class and common attributes.
* Concrete views might simply consist of a URL definition then:
* a la "yyy1.url=/my.jsp", "yyy2.url=/your.jsp".
* <p>View definitions that define their own parent or carry their own
* class can still override this. Strictly speaking, the rule that a
* default parent setting does not apply to a bean definition that
* carries a class is there for backwards compatibility reasons.
* It still matches the typical use case.
*/
public void setDefaultParentView(String defaultParentView) {
this.defaultParentView = defaultParentView;
}
/**
* Specify Locales to initialize eagerly, rather than lazily when actually accessed.
* <p>Allows for pre-initialization of common Locales, eagerly checking
* the view configuration for those Locales.
*/
public void setLocalesToInitialize(Locale... localesToInitialize) {
this.localesToInitialize = localesToInitialize;
}
/**
* Specify the order value for this ViewResolver bean.
* <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered.
* @see org.springframework.core.Ordered#getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
/**
* Eagerly initialize Locales if necessary.
* @see #setLocalesToInitialize
*/
@Override
public void afterPropertiesSet() throws BeansException {
if (this.localesToInitialize != null) {
for (Locale locale : this.localesToInitialize) {
initFactory(locale);
}
}
}
@Override
protected View loadView(String viewName, Locale locale) throws Exception {
BeanFactory factory = initFactory(locale);
try {
return factory.getBean(viewName, View.class);
}
catch (NoSuchBeanDefinitionException ex) {
// Allow for ViewResolver chaining...
return null;
}
}
/**
* Initialize the View {@link BeanFactory} from the {@code ResourceBundle},
* for the given {@link Locale locale}.
* <p>Synchronized because of access by parallel threads.
* @param locale the target {@code Locale}
* @return the View factory for the given Locale
* @throws BeansException in case of initialization errors
*/
protected synchronized BeanFactory initFactory(Locale locale) throws BeansException {
// Try to find cached factory for Locale:
// Have we already encountered that Locale before?
if (isCache()) {
BeanFactory cachedFactory = this.localeCache.get(locale);
if (cachedFactory != null) {
return cachedFactory;
}
}
// Build list of ResourceBundle references for Locale.
List<ResourceBundle> bundles = new ArrayList<>(this.basenames.length);
for (String basename : this.basenames) {
bundles.add(getBundle(basename, locale));
}
// Try to find cached factory for ResourceBundle list:
// even if Locale was different, same bundles might have been found.
if (isCache()) {
BeanFactory cachedFactory = this.bundleCache.get(bundles);
if (cachedFactory != null) {
this.localeCache.put(locale, cachedFactory);
return cachedFactory;
}
}
// Create child ApplicationContext for views.
GenericWebApplicationContext factory = new GenericWebApplicationContext();
factory.setParent(getApplicationContext());
factory.setServletContext(getServletContext());
// Load bean definitions from resource bundle.
org.springframework.beans.factory.support.PropertiesBeanDefinitionReader reader =
new org.springframework.beans.factory.support.PropertiesBeanDefinitionReader(factory);
reader.setDefaultParentBean(this.defaultParentView);
for (ResourceBundle bundle : bundles) {
reader.registerBeanDefinitions(bundle);
}
factory.refresh();
// Cache factory for both Locale and ResourceBundle list.
if (isCache()) {
this.localeCache.put(locale, factory);
this.bundleCache.put(bundles, factory);
}
return factory;
}
/**
* Obtain the resource bundle for the given basename and {@link Locale}.
* @param basename the basename to look for
* @param locale the {@code Locale} to look for
* @return the corresponding {@code ResourceBundle}
* @throws MissingResourceException if no matching bundle could be found
* @see ResourceBundle#getBundle(String, Locale, ClassLoader)
*/
protected ResourceBundle getBundle(String basename, Locale locale) throws MissingResourceException {
return ResourceBundle.getBundle(basename, locale, getBundleClassLoader());
}
/**
* Close the bundle View factories on context shutdown.
*/
@Override
public void destroy() throws BeansException {
for (ConfigurableApplicationContext factory : this.bundleCache.values()) {
factory.close();
}
this.localeCache.clear();
this.bundleCache.clear();
}
}
|
package com.mpls.v2.repository;
import com.mpls.v2.model.Callback;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CallbackRepository extends JpaRepository<Callback, Long> {
List<Callback> findAllByName(String name);
List<Callback> findAllByEmail(String email);
}
|
package kr.co.flyingturtle.repository.vo;
public class PageResult {
private Page page; //page, listSize
private int pageNo; //현재페이지
private int count; //총 게시물 수
private int beginPage; //현재페이지 기준 시작 페이지 번호
private int endPage; //현재페이지 기준 끝 페이지 번호
private boolean prev; //이전버튼 활성화 여부
private boolean next; //다음버튼 활성화 여부
public PageResult(Page page) {
this.page = page;
}
public PageResult(int pageNo, int count) {
this.pageNo = pageNo;
this.count = count;
//메서드 호출
setPageInfo();
}
/*
* public String makeSearch(int page) { UriComponents uriComponents =
* UriComponentsBuilder.newInstance() .queryParam("page", page)
* .queryParam("listSize",cri.getListSize()) .queryParam("keyword",
* ((Search)cri).getKeyword()) .build(); return uriComponents.toUriString();
*
* }
*/
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public void setCount(int count) {
this.count = count;
}
public void setBeginPage(int beginPage) {
this.beginPage = beginPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public void setPrev(boolean prev) {
this.prev = prev;
}
public void setNext(boolean next) {
this.next = next;
}
public void setPageInfo() {
//실제 마지막 페이지
int lastPage = (count % 10)==0 ? count /10 : count / 10 +1;
//한번에 보여줄 페이지 개수
int tabSize = 10;
//pageGroup - 요청 페이지 번호가 포함된 페이지 블럭 번호( 1Tab ->1~10, 2Tab ->11~20 )
int pageGroup = (pageNo -1)/tabSize +1;
beginPage = (pageGroup -1) * tabSize +1;
//실제 글이 존재하는 페이지 번호 수(lastPage = 7page)보다 페이지탭수(1~10page)가 크면 마지막페이지(endPage)번호는 실제 존재하는 페이지번호 수 (7page)가 된다.
endPage = (pageGroup * tabSize > lastPage)? lastPage : pageGroup * tabSize;
//이전버튼 활성화할껀지?
prev = beginPage != 1;
next = endPage != lastPage;
}
public int getPageNo() {
return pageNo;
}
public int getCount() {
return count;
}
public int getBeginPage() {
return beginPage;
}
public int getEndPage() {
return endPage;
}
public boolean isPrev() {
return prev;
}
public boolean isNext() {
return next;
}
}
|
package com.training.resources;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebService(name = "Flight", targetNamespace = "http://ifaces.training.com/")
@XmlSeeAlso({
ObjectFactory.class
})
public interface Flight {
/**
*
* @param src
* @param dest
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "seatAvailable", targetNamespace = "http://ifaces.training.com/", className = "com.training.resources.SeatAvailable")
@ResponseWrapper(localName = "seatAvailableResponse", targetNamespace = "http://ifaces.training.com/", className = "com.training.resources.SeatAvailableResponse")
@Action(input = "http://ifaces.training.com/Flight/seatAvailableRequest", output = "http://ifaces.training.com/Flight/seatAvailableResponse")
public String seatAvailable(
@WebParam(name = "src", targetNamespace = "")
String src,
@WebParam(name = "dest", targetNamespace = "")
String dest);
}
|
package com.library.qa.util;
public class TestUtil {
public static long PAGE_LOAD_TIME = 30;
public static long IMPLICIT_TIME = 20;
}
|
package util;
import color.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import org.h2.tools.Server;
/**
* Clase para gestionar la conexión a base de datos desde Java JDBC por medio
* del patrón singleton, también se incluyen métodos útiles para trabajar con la
* base de datos.
*
* @author Sebastián López
* @version abril/2021
* @see
* <a href=http://www.juntadeandalucia.es/servicios/madeja/contenido/recurso/202/>Marco
* de Desarrollo de la Junta de Andalucía</a>
* @see
* <a href=https://itquetzali.com/2019/09/01/patron-de-diseno-singleton-implementacion-en-java/>itquetzali.com:
* Singleton</a>
* @see
* <a href=http://www.programandoapasitos.com/2016/07/java-y-mysql-patron-singleton.html>Patrón
* Singleton acceso a base de datos en Java</a>
*/
public class BD {
/**
* Ruta al directorio que contiene los ficheros script de SQL.
*/
public static final String RUTA_SCRIPTSQL = "./src/scriptSQL/";
/**
* Ruta al directorio que contiene los ficheros de base de datos.
*/
public static final String RUTA_BD = "./bd/";
/**
* Nombre de la base de datos.
*/
public static final String BASE_DE_DATOS = "agenda";
/**
* Usuario de la base de datos.
*/
public static final String USER = "java";
/**
* Password del usuario de base de datos.
*/
public static final String PASSWORD = "java";
/**
* Cadena de conexión JDBC.
*/
public static final String URL = "jdbc:h2:" + RUTA_BD + BASE_DE_DATOS + ";AUTO_SERVER=TRUE";
/**
* Objeto Connection Singleton.
*/
private static Connection conexionBD = null;
/**
* Objeto Servidor Web para consola
*/
private static Server servidorWebH2 = null;
/**
* Método privado para que no se puedan instanciar objetos de la clase desde
* fuera.
*/
private BD() {
try {
BD.conexionBD = DriverManager.getConnection(URL, USER, PASSWORD);
try {
servidorWebH2 = Server.createWebServer(); //Crea el servidor web para consola
servidorWebH2.start(); //Arranca el servidor web pata consola
} catch (SQLException e) {
System.out.println(Color.error("ERROR: no se pudo crear el servidor web para la consola."));
}
} catch (SQLException e) {
System.out.println(Color.error("ERROR: no es posible conectar con la base de datos."));
}
}
/**
* Devuelve la conexión a la base de datos según el patrón Singleton.
*
* @return el objeto Singleton Connection
*/
public static Connection getConexion() {
if (BD.conexionBD == null) {
new BD();
}
return BD.conexionBD;
}
/**
* Cierra la conexión con la base de datos.
*/
public static void closeConexion() {
if (BD.conexionBD != null) {
try {
if (servidorWebH2 != null) { //Parar el servidor web si está funcionando
servidorWebH2.stop();
}
BD.conexionBD.close(); //Cierra la conexión con la base de datos
} catch (SQLException e) {
System.out.println(Color.error("ERROR: no es posible cerrar la conexión con la base de datos."));
}
}
}
/**
* Lanza la consola de la base de datos H2 en una ventana de navegador.
*/
public static String openWebConsola() {
String mensaje = "";
if (servidorWebH2 == null) {
mensaje = Color.error("ERROR: El servidor web no está funcionando.");
} else {
try {
servidorWebH2.openBrowser("http://127.0.0.1:8082");
} catch (Exception e) {
mensaje = Color.error("ERROR: no se pudo abrir la consola en el navegador web.");
}
}
return mensaje;
}
/**
* Devuelve un String con el contenido de un fichero de script SQL. El
* fichero debe estar en la ruta
*
* @param ficheroScriptSQL Nombre del fichero script SQL
* @return el contenido del fichero script como un String
*/
private static String cargaFicheroScriptSQL(String ficheroScriptSQL) {
String linea = "";
StringBuilder scriptSQL = new StringBuilder();
System.out.print(Color.dialogo("Leyendo fichero de script SQL " + ficheroScriptSQL + "... "));
File f = new File(BD.RUTA_SCRIPTSQL + ficheroScriptSQL);
try ( FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr)) {
while ((linea = br.readLine()) != null) {
scriptSQL.append(linea);
}
System.out.println(Color.dialogo("OK"));
} catch (FileNotFoundException e) {
System.out.println(Color.error("ERROR al abrir el fichero script SQL."));
} catch (IOException ex) {
System.out.println(Color.error("ERROR leyendo el fichero de script sQL."));
}
return scriptSQL.toString();
}
/**
* Ejecuta un script SQL contenido en el fichero que se indica como
* parámetro. El fichero debe estar en la ruta {@value #RUTA_SCRIPTSQL}
*
* @param ficheroScriptSQL Nombre del fichero script SQL
* @return true si el script se ejecutó correctamente, false en otro caso
*/
public static boolean execScriptSQL(String ficheroScriptSQL) {
boolean resultado = false;
String scriptSQL = "";
scriptSQL = cargaFicheroScriptSQL(ficheroScriptSQL);
if (scriptSQL.length() > 0) {
System.out.print(Color.dialogo("Ejecutando el fichero de script SQL " + ficheroScriptSQL + "... "));
try ( Statement st = BD.getConexion().createStatement()) {
st.execute(scriptSQL);
resultado = true;
System.out.println(Color.dialogo("OK"));
} catch (SQLException ex) {
resultado = false;
System.out.println(Color.error("ERROR ejecutando script SQL."));
}
}
return resultado;
}
}
|
package models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Objects;
public class Avaliacao implements Serializable{
private Aluno aluno;
private Professor orientador;
private Professor avaliador;
private String titulo;
private String parecer;
private boolean avaliacao;
private String conceito;
public Avaliacao(PropostaTC proposta,Professor avaliador, boolean avaliacao) {
this.aluno = proposta.getAutor();
this.avaliador = avaliador;
this.titulo = proposta.getTitulo();
this.avaliacao = avaliacao;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Professor getAvaliador() {
return avaliador;
}
public void setAvaliador(Professor avaliador) {
this.avaliador = avaliador;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getParecer() {
return parecer;
}
public void setParecer(String parecer) {
this.parecer = parecer;
}
public boolean isAvaliacao() {
return avaliacao;
}
public void setAvaliacao(boolean avaliacao) {
this.avaliacao = avaliacao;
}
public String getConceito() {
return conceito;
}
public void setConceito(String conceito) {
this.conceito = conceito;
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.aluno);
hash = 83 * hash + Objects.hashCode(this.avaliador);
hash = 83 * hash + Objects.hashCode(this.titulo);
hash = 83 * hash + Objects.hashCode(this.parecer);
hash = 83 * hash + (this.avaliacao ? 1 : 0);
hash = 83 * hash + Objects.hashCode(this.conceito);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Avaliacao other = (Avaliacao) obj;
if (this.avaliacao != other.avaliacao) {
return false;
}
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.parecer, other.parecer)) {
return false;
}
if (!Objects.equals(this.conceito, other.conceito)) {
return false;
}
if (!Objects.equals(this.aluno, other.aluno)) {
return false;
}
if (!Objects.equals(this.avaliador, other.avaliador)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Avaliacao{" + "aluno=" + aluno + ", avaliador=" + avaliador +
", titulo=" + titulo +
", parecer=" + parecer + ", avaliacao=" + avaliacao +
", conceito=" + conceito + '}';
}
}
|
/*
* @(#) SmailInfoService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.smailinfo.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.service.impl.BaseService;
import com.esum.imsutil.util.ExcelCreater;
import com.esum.wp.ims.smailinfo.SmailInfo;
import com.esum.wp.ims.smailinfo.dao.ISmailInfoDAO;
import com.esum.wp.ims.smailinfo.service.ISmailInfoService;
import com.esum.wp.ims.tld.XtrusLangTag;
/**
*
* @author
* @version $Revision: 1.1 $ $Date: 2008/07/31 01:49:44 $
*/
public class SmailInfoService extends BaseService implements ISmailInfoService {
/**
* Default constructor. Can be used in place of getInstance()
*/
public SmailInfoService () {}
public Object insert(Object object) {
try {
ISmailInfoDAO iSmailInfoDAO = (ISmailInfoDAO)iBaseDAO;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SmailInfo diObj = (SmailInfo)object;
SmailInfo dsObj = new SmailInfo();
SmailInfo dsObjMain = new SmailInfo();
String useInbound = diObj.getUseInbound();
String useOutbound = diObj.getUseOutbound();
String inboundPartnerId = "";
String outboundPartnerId = "";
inboundPartnerId = diObj.getInterfaceId()+"_IN";
dsObj.setInboundPartnerId(inboundPartnerId);
boolean inFlag = false;
if(useInbound.equals("Y") || !useInbound.equals("")){
if(diObj.getInPartnerMailArr().length == 1 &&diObj.getInPartnerMailArr()[0].equals("") && diObj.getInPartnerMailArr()[0].equals(""))
inFlag = false;
else
inFlag = true;
if(inFlag == true){
dsObj.setInterfaceId(diObj.getInterfaceId());
for(int i = 0; i < diObj.getInPartnerMailArr().length; i++){
dsObj.setInPartnerMail(diObj.getInPartnerMailArr()[i]);
dsObj.setInParsingRule(diObj.getInParsingRuleArr()[i]);
dsObj.setRegDate(sdf.format(new Date()));
dsObj.setModDate(sdf.format(new Date()));
if(dsObj.getInPartnerMail() != null){
Object resultObjIn = iSmailInfoDAO.insertInPartnerInfo(dsObj);
}
}
}
}
boolean outFlag = false;
if(diObj.getOutPartnerMailArr() != null){
if(diObj.getOutPartnerMailArr().length == 1 &&diObj.getOutPartnerMailArr()[0].equals("") && diObj.getOutPartnerMailArr()[0].equals(""))
outFlag = false;
else
outFlag = true;
}else{
outFlag = false;
}
dsObj = new SmailInfo();
outboundPartnerId = diObj.getInterfaceId()+"_OUT";
dsObj.setOutboundPartnerId(outboundPartnerId);
if(useOutbound.equals("Y") || !useOutbound.equals("")){
if(outFlag == true){
dsObj.setInterfaceId(diObj.getInterfaceId());
for(int i = 0; i < diObj.getOutPartnerMailArr().length; i++){
dsObj.setOutPartnerTpId(diObj.getOutPartnerTpIdArr()[i]);
dsObj.setOutPartnerMail(diObj.getOutPartnerMailArr()[i]);
dsObj.setOutContentTypes(diObj.getOutContentTypesArr()[i]);
dsObj.setRegDate(sdf.format(new Date()));
dsObj.setModDate(sdf.format(new Date()));
if(dsObj.getOutPartnerMail() != null){
Object resultObjOut = iSmailInfoDAO.insertOutPartnerInfo(dsObj);
}
}
}
}
dsObjMain.setInterfaceId(diObj.getInterfaceId());
dsObjMain.setUseInbound(diObj.getUseInbound());
if (diObj.getSvrInfoId()==null||diObj.getSvrInfoId().equals(""))
dsObjMain.setSvrInfoId(" ");
else
dsObjMain.setSvrInfoId(diObj.getSvrInfoId());
dsObjMain.setInboundPartnerId(inboundPartnerId);
dsObjMain.setUseOutbound(diObj.getUseOutbound());
dsObjMain.setOutboundSenderMail(diObj.getOutSmailPartnerId());
dsObjMain.setOutboundPartnerId(outboundPartnerId);
dsObjMain.setRegDate(diObj.getRegDate());
dsObjMain.setModDate(diObj.getModDate());
Object resultObj = iBaseDAO.insert(dsObjMain);
return resultObj;
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
ae.printException("");
return ae;
}
}
public Object update(Object object){
try{
String inboundPartnerId = "";
String outboundPartnerId = "";
ISmailInfoDAO iSmailInfoDAO = (ISmailInfoDAO)iBaseDAO;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Integer result = null;
SmailInfo diObj = (SmailInfo)object;
SmailInfo dsObj = new SmailInfo();
SmailInfo dsObjMain = new SmailInfo();
String useInbound = diObj.getUseInbound();
String useOutbound = diObj.getUseOutbound();
dsObjMain.setInterfaceId(diObj.getInterfaceId());
dsObjMain.setUseInbound(diObj.getUseInbound());
inboundPartnerId = diObj.getInterfaceId()+"_IN";
dsObjMain.setInboundPartnerId(inboundPartnerId);
if(useInbound.equals("Y") || (!useInbound.equals("") && !useInbound.equals("N"))){
dsObjMain.setSvrInfoId(diObj.getSvrInfoId());
} else {
dsObjMain.setInboundPartnerId("");
dsObjMain.setSvrInfoId(" ");
}
dsObjMain.setUseOutbound(diObj.getUseOutbound());
outboundPartnerId = diObj.getInterfaceId()+"_OUT";
dsObjMain.setOutboundPartnerId(outboundPartnerId);
if(useOutbound.equals("Y") || (!useOutbound.equals("") && !useOutbound.equals("N"))){
dsObjMain.setOutboundSenderMail(diObj.getOutSmailPartnerId());
} else {
dsObjMain.setOutboundSenderMail("");
dsObjMain.setOutboundPartnerId("");
}
dsObjMain.setModDate(diObj.getModDate());
Object resultObj = iBaseDAO.update(dsObjMain);
boolean inFlag = false;
if(diObj.getInPartnerMailArr().length == 2 &&diObj.getInPartnerMailArr()[0].equals("") && diObj.getInPartnerMailArr()[0].equals(""))
inFlag = false;
else
inFlag = true;
dsObj.setInboundPartnerId(inboundPartnerId);
dsObj.setInSmailPartnerId(diObj.getInSmailPartnerId());
dsObj.setInPartnerMail("");
int deleteResult = iSmailInfoDAO.deleteInPartnerInfo(dsObj);
Object inInsertResult = null;
if(useInbound.equals("Y") || (!useInbound.equals("") && !useInbound.equals("N"))){
if(inFlag == true){
dsObj.setInSmailPartnerId(diObj.getInSmailPartnerId());
for(int i = 0; i < diObj.getInPartnerMailArr().length; i++){
dsObj.setInPartnerMail(diObj.getInPartnerMailArr()[i]);
dsObj.setInParsingRule(diObj.getInParsingRuleArr()[i]);
dsObj.setRegDate(sdf.format(new Date()));
dsObj.setModDate(sdf.format(new Date()));
if(dsObj.getInPartnerMail() != null){
inInsertResult = iSmailInfoDAO.insertInPartnerInfo(dsObj);
}
}
}
}
boolean outFlag = false;
if(diObj.getOutPartnerMailArr() != null){
if(diObj.getOutPartnerMailArr().length == 2 &&diObj.getOutPartnerMailArr()[0].equals("") && diObj.getOutPartnerMailArr()[0].equals(""))
outFlag = false;
else
outFlag = true;
}else{
outFlag = false;
}
dsObj.setOutSmailPartnerId(diObj.getOutSmailPartnerId());
dsObj.setOutboundPartnerId(outboundPartnerId);
dsObj.setOutPartnerMail("");
int outDeleteResult = iSmailInfoDAO.deleteOutPartnerInfo(dsObj);
Object outInsertResult = null;
if(useOutbound.equals("Y") || (!useOutbound.equals("") && !useOutbound.equals("N"))){
if(outFlag == true){
dsObj.setOutSmailPartnerId(diObj.getOutSmailPartnerId());
for(int i = 0; i < diObj.getOutPartnerMailArr().length; i++){
dsObj.setOutPartnerTpId(diObj.getOutPartnerTpIdArr()[i]);
dsObj.setOutPartnerMail(diObj.getOutPartnerMailArr()[i]);
dsObj.setOutContentTypes(diObj.getOutContentTypesArr()[i]);
dsObj.setRegDate(sdf.format(new Date()));
dsObj.setModDate(sdf.format(new Date()));
if(dsObj.getOutPartnerMail()!=null){
outInsertResult = iSmailInfoDAO.insertOutPartnerInfo(dsObj);
}
}
}
}
//result = new Integer(ISmailInfoDAO.update(diObj));
return result;
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
ae.printException("");
return ae;
}
}
public Object delete(Object object) {
try {
ISmailInfoDAO iSmailInfoDAO = (ISmailInfoDAO)iBaseDAO;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SmailInfo diObj = (SmailInfo)object;
SmailInfo dsObj = new SmailInfo();
SmailInfo dsObjMain = new SmailInfo();
String useInbound = diObj.getUseInbound();
String useOutbound = diObj.getUseOutbound();
String inboundPartnerId = "";
String outboundPartnerId = "";
inboundPartnerId = diObj.getInterfaceId()+"_IN";
dsObj.setInboundPartnerId(inboundPartnerId);
outboundPartnerId = diObj.getInterfaceId()+"_OUT";
dsObj.setOutboundPartnerId(outboundPartnerId);
Object resultObjIn = iSmailInfoDAO.deleteInPartnerInfo(dsObj);
Object resultObjOut = iSmailInfoDAO.deleteOutPartnerInfo(dsObj);
dsObjMain.setInterfaceId(diObj.getInterfaceId());
Object resultObj = iBaseDAO.delete(dsObjMain);
return resultObj;
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
ae.printException("");
return ae;
}
}
public Object selectPageList(Object object) {
try {
ISmailInfoDAO iMailInfoDAO = (ISmailInfoDAO)iBaseDAO;
return iMailInfoDAO.selectPageList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object smailInfoDetail(Object object) {
try {
ISmailInfoDAO iMailInfoDAO = (ISmailInfoDAO)iBaseDAO;
return iMailInfoDAO.smailInfoDetail(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object smailInPartnerInfoList(Object object) {
try {
ISmailInfoDAO iMailInfoDAO = (ISmailInfoDAO)iBaseDAO;
return iMailInfoDAO.selectInPartnerList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object smailOutPartnerInfoList(Object object) {
try {
ISmailInfoDAO iMailInfoDAO = (ISmailInfoDAO)iBaseDAO;
return iMailInfoDAO.selectOutPartnerList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object updatePassword(Object object) {
try {
ISmailInfoDAO iMailInfoDAO = (ISmailInfoDAO)iBaseDAO;
return new Integer(iMailInfoDAO.updatePassword(object));
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
@Override
public void saveSmailInfoExcel(Object object, HttpServletRequest request,
HttpServletResponse response) throws Exception{
SmailInfo info = (SmailInfo) object;
ISmailInfoDAO iSmailInfoDAO = (ISmailInfoDAO)iBaseDAO;
Map smailInfoMap = iSmailInfoDAO.saveSmailInfoExcel(object);
Map inPartnerInfoMap = iSmailInfoDAO.saveSmailInPartnerInfoExcel(object);
Map outPartnerInfoMap = iSmailInfoDAO.saveSmailOutPartnerInfoExcel(object);
ExcelCreater excel = new ExcelCreater();
excel.createSheet((String) smailInfoMap.get("table"), (String[]) smailInfoMap.get("header"), (int[]) smailInfoMap.get("size"), (List) smailInfoMap.get("data"));
excel.createSheet((String) inPartnerInfoMap.get("table"), (String[]) inPartnerInfoMap.get("header"), (int[]) inPartnerInfoMap.get("size"), (List) inPartnerInfoMap.get("data"));
excel.createSheet((String) outPartnerInfoMap.get("table"), (String[]) outPartnerInfoMap.get("header"), (int[]) outPartnerInfoMap.get("size"), (List) outPartnerInfoMap.get("data"));
excel.download(info.getRootPath(), XtrusLangTag.getMessage("mail.info"), request, response);
}
}
|
package model;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
/**
* Department entity. @author MyEclipse Persistence Tools
*/
public class Department implements java.io.Serializable {
// Fields
private Integer id;
private User user;
private String name;
private Timestamp createTime;
private Timestamp modifyTime;
private Short sort;
private Set users = new HashSet(0);
// Constructors
/** default constructor */
public Department() {
}
/** minimal constructor */
public Department(String name, Timestamp createTime) {
this.name = name;
this.createTime = createTime;
}
/** full constructor */
public Department(User user, String name, Timestamp createTime,
Timestamp modifyTime, Short sort, Set users) {
this.user = user;
this.name = name;
this.createTime = createTime;
this.modifyTime = modifyTime;
this.sort = sort;
this.users = users;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public Timestamp getModifyTime() {
return this.modifyTime;
}
public void setModifyTime(Timestamp modifyTime) {
this.modifyTime = modifyTime;
}
public Short getSort() {
return this.sort;
}
public void setSort(Short sort) {
this.sort = sort;
}
public Set getUsers() {
return this.users;
}
public void setUsers(Set users) {
this.users = users;
}
} |
package edu.student.android.scarnesdice;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import static android.R.attr.mode;
import static android.R.string.no;
public class MainActivity extends AppCompatActivity {
private final static String TAG = "ScarnesDiceApp";
private int user_overall_score = 0;
private int user_turn_score = 0;
private int computer_overall_score = 0;
private int computer_turn_score = 0;
private Button roll,reset,hold,inc,dec;
private ImageView diceImage1,diceImage2;
private TextView status,counter;
private ArrayList<String> diceImages;
private boolean isTwoDice,isFastMode;
private Random random = new Random();
private int i=1;
final Handler timerHandler = new Handler();
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_scarnes, menu);
MenuItem item = menu.findItem(R.id.two_dice);
item.setChecked(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.two_dice) {
item.setChecked(!item.isChecked());
if(item.isChecked()) {
Log.v(TAG,"Two Dice Mode On");
isTwoDice = true;
diceImage2.setVisibility(View.VISIBLE);
user_overall_score=0;
user_turn_score=0;
computer_overall_score=0;
computer_turn_score=0;
hold.setVisibility(View.VISIBLE);
roll.setVisibility(View.VISIBLE);
status.setText("Your score: "+user_overall_score+"\ncomputer score: "+computer_overall_score+"\nyour turn score: "+user_turn_score);
}else{
Log.v(TAG,"Two Dice Mode OFF");
isTwoDice = false;
diceImage2.setVisibility(View.GONE);
user_overall_score=0;
user_turn_score=0;
computer_overall_score=0;
computer_turn_score=0;
hold.setVisibility(View.VISIBLE);
roll.setVisibility(View.VISIBLE);
status.setText("Your score: "+user_overall_score+"\ncomputer score: "+computer_overall_score+"\nyour turn score: "+user_turn_score);
}
}
else if(id == R.id.face_dice) {
item.setChecked(!item.isChecked());
if (item.isChecked()) {
Log.v(TAG, "Fast Mode On");
isFastMode = true;
diceImage2.setVisibility(View.GONE);
user_overall_score = 0;
user_turn_score = 0;
computer_overall_score = 0;
computer_turn_score = 0;
inc.setVisibility(View.VISIBLE);
dec.setVisibility(View.VISIBLE);
counter.setVisibility(View.VISIBLE);
hold.setVisibility(View.GONE);
roll.setVisibility(View.VISIBLE);
counter.setText(String.valueOf(i));
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
}
else{
Log.v(TAG, "Fast Mode Off");
isFastMode = false;
diceImage2.setVisibility(View.GONE);
user_overall_score = 0;
user_turn_score = 0;
computer_overall_score = 0;
computer_turn_score = 0;
inc.setVisibility(View.GONE);
dec.setVisibility(View.GONE);
counter.setVisibility(View.GONE);
hold.setVisibility(View.VISIBLE);
roll.setVisibility(View.VISIBLE);
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isFastMode= false;
isTwoDice = false;
roll = (Button) findViewById(R.id.roll);
reset = (Button) findViewById(R.id.reset);
hold = (Button) findViewById(R.id.hold);
inc = (Button) findViewById(R.id.button);
dec = (Button) findViewById(R.id.button2);
counter = (TextView) findViewById(R.id.textView2);
diceImage1 = (ImageView) findViewById(R.id.dice_img1);
diceImage2 = (ImageView) findViewById(R.id.dice_img2);
status = (TextView) findViewById(R.id.textView);
inc.setVisibility(View.GONE);
dec.setVisibility(View.GONE);
counter.setVisibility(View.GONE);
inc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(TAG,"Increment");
if(i>=1&& i<=10) {
i = i + 1;
counter.setText(String.valueOf(i));
}
}
});
dec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(TAG,"Decrement");
if(i>1) {
i = i - 1;
counter.setText(String.valueOf(i));
}
}
});
roll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isFastMode)
rollDice("user",1);
else{
rollDice("user",i);
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG,"Reset Clicked");
user_overall_score=0;
user_turn_score=0;
computer_overall_score=0;
computer_turn_score=0;
hold.setVisibility(View.VISIBLE);
roll.setVisibility(View.VISIBLE);
status.setText("Your score: "+user_overall_score+"\ncomputer score: "+computer_overall_score+"\nyour turn score: "+user_turn_score);
}
});
hold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG,"Hold Clicked");
user_overall_score = user_overall_score+user_turn_score;
user_turn_score=0;
status.setText("Your score: "+user_overall_score+"\ncomputer score: "+computer_overall_score+"\nyour turn score: "+user_turn_score);
computerTurn();
}
});
}
private void rollDice(String turnOf,int noOfRolls) {
if(!isFastMode) {
//<editor-fold desc="When two dice and one dice">
Log.e(TAG, "rollDice Method");
int[] a = new int[6];
int m = random.nextInt(6) + 1;
int n = random.nextInt(6) + 1;
for (int i = 1; i <= 6; i++) {
String url = "drawable/" + "dice" + (i);
a[i - 1] = getResources().getIdentifier(url, "drawable", getPackageName());
}
diceImage1.setImageResource(a[n - 1]);
if (isTwoDice) {
Log.e(TAG, "isTwoDice");
int[] b = new int[6];
for (int j = 1; j <= 6; j++) {
String url = "drawable/" + "dice" + (j);
b[j - 1] = getResources().getIdentifier(url, "drawable", getPackageName());
}
diceImage2.setImageResource(b[m - 1]);
}
if (isWinner()) {
hold.setVisibility(View.GONE);
roll.setVisibility(View.GONE);
} else {
if (!isTwoDice) {
Log.v(TAG, "One Dice Mode");
if (turnOf.equals("user")) {
Log.v(TAG, "Users Turn");
if (n != 1) {
Log.v(TAG, "User scored other than 1");
user_turn_score = user_turn_score + n;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
} else {
Log.v(TAG, "User scored 1");
user_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
computerTurn();
}
} else {
Log.v(TAG, "Computers Turn");
if (n != 1) {
Log.v(TAG, "Computers scored other than 1");
computer_turn_score = computer_turn_score + n;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
computerTurn();
} else {
Log.v(TAG, "Computers scored 1");
computer_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nComputer rolled a 1 ");
computerTurn();
}
}
} else {
Log.v(TAG, "Two Dice Mode");
if (turnOf.equals("user")) {
Log.v(TAG, "Users Turn");
if (n == m) {
Log.v(TAG, "Both the dice have same value");
user_turn_score = user_turn_score + n + m;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
} else if (n != 1 && m != 1) {
Log.v(TAG, "User scored a " + n + " " + m + ".");
user_turn_score = user_turn_score + n + m;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
} else if (n == 1 || m == 1) {
Log.v(TAG, "User scored a " + n + " " + m + ".");
user_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
System.out.println("User rolled a one");
computerTurn();
} else if (n == 1 && m == 1) {
Log.v(TAG, "User scored a " + n + " " + m + ".");
user_turn_score = 0;
user_overall_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
System.out.println("User rolled two ones");
computerTurn();
}
} else {
Log.v(TAG, "Computers Turn");
if (n == m) {
Log.v(TAG, "Both the dice have same value");
computer_turn_score = computer_turn_score + n + m;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
computerTurn();
} else if (n != 1 && m != 1) {
Log.v(TAG, "Computer scored a " + n + " " + m + ".");
computer_turn_score = computer_turn_score + n + m;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
computerTurn();
} else if (n == 1 || m == 1) {
Log.v(TAG, "Computer scored a " + n + " " + m + ".");
computer_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nComputer rolled a 1 ");
System.out.println("Computer rolled a one");
computerTurn();
} else if (n == 1 && m == 1) {
Log.v(TAG, "Computer scored a " + n + " " + m + ".");
computer_turn_score = 0;
computer_overall_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nComputer rolled a 1 ");
System.out.println("Computer rolled two ones");
}
/* if (n != 1) {
computer_turn_score = computer_turn_score + n;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
computerTurn();
} else {
computer_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nComputer rolled a 1 ");
System.out.println("computer rolled a one");
computerTurn();
}*/
}
}
}
//</editor-fold>
}else{
isFastModeRollDice(turnOf,noOfRolls);
}
}
private void isFastModeRollDice(String turnOf, int noOfRolls) {
Log.v(TAG, "isFastModeRollDice - No of Rolls"+ noOfRolls);
boolean s= false;
Log.v(TAG, turnOf+" turn - fast mode");
int[] a = new int[noOfRolls];
int sum = 0;
for (int i = 0; i < noOfRolls; i++) {
a[i] = random.nextInt(6) + 1;
Log.v(TAG, turnOf+" Rolled a "+a[i]);
if (a[i] == 1) {
Log.v(TAG, turnOf+" Rolled a 1");
s = true;
break;
}else{
sum+=a[i];
}
}
if(turnOf.equals("user")){
if (s) {
Log.v(TAG, turnOf+" rolled a 1 - fast mode");
user_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
computerTurn();
}else{
Log.v(TAG, turnOf+" rolled no 1 in the no of rolls Total Sum "+sum+" - fast mode");
user_turn_score = user_turn_score + sum;
user_overall_score = user_overall_score+user_turn_score;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\nyour turn score: " + user_turn_score);
computerTurn();
}
}else{
if (s) {
Log.v(TAG, turnOf+" rolled a 1 - fast mode");
computer_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
}else{
Log.v(TAG, turnOf+" rolled no 1 in the no of rolls - fast mode");
computer_turn_score = computer_turn_score + sum;
status.setText("Your score: " + user_overall_score + "\ncomputer score: " + computer_overall_score + "\ncomputer turn score: " + computer_turn_score);
}
}
}
private boolean isWinner(){
if(computer_overall_score >=100 || user_overall_score >=100){
if(user_overall_score>=100){
Log.v(TAG,"User scored a 100");
status.setText("You have won the game");
return true;
}else{
Log.v(TAG,"Computer scored a 100");
status.setText("You lost the game! Computer won this one.");
return true;
}
}
return false;
}
private void computerTurn() {
Log.e(TAG, "computerTurn method");
roll.setVisibility(View.GONE);
hold.setVisibility(View.GONE);
System.out.println("Computer Score: " + computer_turn_score);
if (!isFastMode) {
if (computer_turn_score < 20) {
Log.v(TAG, "Computer Turn Score is less than 20");
timerHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!isFastMode)
rollDice("computer", 1);
else {
rollDice("computer", 5);
}
}
}, 1000);
} else {
Log.v(TAG, "Computer Turn Score is more than 20");
computer_overall_score = computer_overall_score + computer_turn_score;
computer_turn_score = 0;
status.setText("Your score: " + user_overall_score + "\n computer score: " + computer_overall_score + "\nComputer holds ");
if (isWinner()) {
Log.v(TAG, "Computer Scored a Hundred");
roll.setVisibility(View.GONE);
hold.setVisibility(View.GONE);
} else {
Log.v(TAG, "Computer Holds and Overall Score not greater than 100");
roll.setVisibility(View.VISIBLE);
hold.setVisibility(View.VISIBLE);
}
}
}
}
}
|
package com.beike.dao.background.guest;
import java.util.List;
import com.beike.dao.GenericDao;
import com.beike.entity.background.guest.GuestBranch;
import com.beike.form.background.guest.GuestBranchForm;
/**
*
* Title : GuestBranchDao
* <p/>
* Description : 客户分店信息访问数据接口
* <p/>
* CopyRight : CopyRight (c) 2011
* </P>
* Company : Sinobo
* </P>
* JDK Version Used : JDK 5.0 +
* <p/>
* Modification History :
* <p/>
* <pre>NO. Date Modified By Why & What is modified</pre>
* <pre>1 2011-06-03 lvjx Created<pre>
* <p/>
*
* @author lvjx
* @version 1.0.0.2011-06-03
*/
public interface GuestBranchDao extends GenericDao<GuestBranch,Long> {
/**
* Description : 新增客户分店信息
* @param guestBranchForm
* @return
* @throws Exception
*/
public String addGuestBranch(GuestBranchForm guestBranchForm) throws Exception;
/**
* Description : 按条件查询客户分店信息
* @param guestBranchForm
* @param startRow
* @param pageSize
* @return
* @throws Exception
*/
public List<GuestBranch> queryGuestBranchConditions(GuestBranchForm guestBranchForm,int startRow,int pageSize) throws Exception;
/**
* Description : 按条件查询客户信息总条数
* @param guestBranchForm
* @return
* @throws Exception
*/
public int queryGuestBranchCountConditions(GuestBranchForm guestBranchForm) throws Exception;
/**
* Description : 根据客户分店id查询分店信息
* @param branchId
* @return
* @throws Exception
*/
public GuestBranch queryGuestBranchById(String branchId) throws Exception;
/**
* Description : 修改客户分店信息
* @param guestBranchForm
* @return
* @throws Exception
*/
public String editGuestBranch(GuestBranchForm guestBranchForm) throws Exception;
/**
* Description : 根据客户id查询客户分店信息
* @param guestBranchForm
* @return
* @throws Exception
*/
public List<GuestBranch> queryBranchInfo(GuestBranchForm guestBranchForm) throws Exception;
/**
* Description : 验证分店名称是否重复
* @param guestBranchForm
* @return
* @throws Exception
*/
public boolean validatorBranchName(GuestBranchForm guestBranchForm) throws Exception;
}
|
/*
Input
{([]){}()}
Output
true
https://www.codingame.com/ide/puzzle/brackets-extreme-edition
*/
import java.util.Scanner;
import java.util.Stack;
public class BracketsExtreme {
public static boolean isOpening(char x) {
boolean flag = false;
switch(x) {
case '{' :
flag = true;
break;
case '(' :
flag = true;
break;
case '[' :
flag = true;
break;
}
return flag;
}
public static boolean isClosing(char x) {
boolean flag = false;
switch(x) {
case '}' :
flag = true;
break;
case ')' :
flag = true;
break;
case ']' :
flag = true;
break;
}
return flag;
}
public static char openingPair(char x) {
char a ='~';
switch(x) {
case '}' :
a = '{';
break;
case ')' :
a = '(';
break;
case ']' :
a = '[';
break;
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack <Character> st = new Stack <Character> ();
boolean flag = true;
char a[] = sc.nextLine().toCharArray();
for(int i = 0; i < a.length; i++) {
if (isOpening(a[i])) {
st.push(a[i]);
}
else if (isClosing(a[i])) {
if (st.empty() == true) {
flag = false;
break;
}
if (st.peek() == openingPair(a[i])) {
st.pop();
}
else {
flag = false;
break;
}
}
}
if(!st.empty()) {
flag = false;
}
System.out.println(flag);
}
}
|
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.0
*/
package com.lenovohit.hwe.ssm.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lenovohit.hwe.base.model.AuditableModel;
/**
* SSM_MATERIAL_IN
*
* @author zyus
* @version 1.0.0 2017-12-14
*/
@Entity
@Table(name = "SSM_MATERIAL_IN")
public class MaterialIn extends AuditableModel implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = -5857230990968868745L;
/** inPutAccount */
private Integer inPutAccount;
/** inPutTime */
private Date inPutTime;
/** materialId */
private String materialId;
/** A - 初始
0 - 正常
1 - 已屏蔽 */
private String status;
/**
* 获取inPutAccount
*
* @return inPutAccount
*/
@Column(name = "IN_PUT_ACCOUNT", nullable = true, length = 10)
public Integer getInPutAccount() {
return this.inPutAccount;
}
/**
* 设置inPutAccount
*
* @param inPutAccount
*/
public void setInPutAccount(Integer inPutAccount) {
this.inPutAccount = inPutAccount;
}
/**
* 获取inPutTime
*
* @return inPutTime
*/
@Column(name = "IN_PUT_TIME", nullable = true)
public Date getInPutTime() {
return this.inPutTime;
}
/**
* 设置inPutTime
*
* @param inPutTime
*/
public void setInPutTime(Date inPutTime) {
this.inPutTime = inPutTime;
}
/**
* 获取materialId
*
* @return materialId
*/
@Column(name = "MATERIAL_ID", nullable = true, length = 32)
public String getMaterialId() {
return this.materialId;
}
/**
* 设置materialId
*
* @param materialId
*/
public void setMaterialId(String materialId) {
this.materialId = materialId;
}
/**
* 获取A - 初始
0 - 正常
1 - 已屏蔽
*
* @return A - 初始
0 - 正常
1 - 已屏蔽
*/
@Column(name = "STATUS", nullable = true, length = 1)
public String getStatus() {
return this.status;
}
/**
* 设置A - 初始
0 - 正常
1 - 已屏蔽
*
* @param status
* A - 初始
0 - 正常
1 - 已屏蔽
*/
public void setStatus(String status) {
this.status = status;
}
} |
package com.me.learn.date;
public class Readme {
/*
LocalDate, LocalTime and LocalDateTime
Duration and Period for difference. First one is small and second larger..
Sometimes, we need to perform advance date time manipulation such as adjusting date to first day
of next month or adjusting date to next working day or adjusting date to next public holiday then
we can use TemporalAdjusters to meet our needs. Java 8 comes bundled with many predefined temporal
adjusters for common scenarios. These temporal adjusters are available as static factory methods
inside the TemporalAdjusters class.
*/
}
|
package ucf.assignments;
/*
* UCF COP3330 Summer 2021 Assignment 4 Solution
* Copyright 2021 Christian Klingbiel
*/
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Boolean.compare;
public class ToDoListController {
public List<ToDoItem> list = new ArrayList<>();
List<ToDoItem> savedList = new ArrayList<>();
@FXML
public TextField textOutput;
@FXML
public TextField textDesc;
@FXML
public TextField textDate;
@FXML
public TextField textComplete;
@FXML
public ListView<String> listDisplay;
@FXML
public void addItemButtonClicked() { addItem(); }
@FXML
public void removeItemButtonClicked() { removeItem(); }
@FXML
public void editDescriptionButtonClicked() {
editDescription();
}
@FXML
public void editDueDateButtonClicked() {
editDueDate();
}
@FXML
public void markItemCompleteButtonClicked() {
markItemComplete();
}
@FXML
public void displayAllItemsButtonClicked() {
displayAllItems();
}
@FXML
public void displayIncompleteButtonClicked() { displayIncomplete(); }
@FXML
public void displayCompletionsButtonClicked() {
displayCompletions();
}
@FXML
public void saveItemsButtonClicked() { saveItems(); }
@FXML
public void loadListButtonClicked() {
loadList();
}
@FXML
public void clearListButtonClicked(){clearList();}
public void addItem(){
ToDoItem t = new ToDoItem();
//get items from TextField
getDate(t);
getDesc(t);
getComplete(t);
//validate credentials and add item to ToDoList
if(validateComplete() && validateDate() && validateDesc()){
list.add(t);
setTextOutput("Added item successfully.");
}
else setTextOutput("Make sure everything is correct.");
//display list
displayList(list);
//clear texts
clearText(textDesc);
clearText(textDate);
clearText(textComplete);
}
public void removeItem(){
//make a tempList and new item
List <ToDoItem> temp = new ArrayList<>();
ToDoItem t = new ToDoItem();
//get item from TextField and assign to t
getDesc(t);
getComplete(t);
getDate(t);
//for loop that runs through list to see if it finds a matching description
// - if it does not add to temp list
for(int i = 0;i < list.size();i++){
if(!list.get(i).desc.equalsIgnoreCase(t.desc)){
temp.add(list.get(i));
}
}
//set list equals to temp
list = temp;
//display list
displayList(list);
setTextOutput("Displaying new list.");
//clear texts
clearText(textDesc);
clearText(textDate);
clearText(textComplete);
}
public void clearList(){
//for loop that flushes out list
for (int i = 0;i < list.size();i++){
list.remove(i);
i--;
}
setTextOutput("Successfully cleared list.");
displayList(list);
}
public void editDescription(){
ToDoItem t = new ToDoItem();
//receive items from user
getDesc(t);
getDate(t);
getComplete(t);
//if the list has the task, add new description
if (validateDesc() && validateDate() && validateComplete()){
for (int i = 0;i < list.size();i++){
if (list.get(i).date.equalsIgnoreCase(t.date) && list.get(i).complete == t.complete){
list.get(i).desc = t.desc;
setTextOutput("Successfully changed desc.");
break;
}
else setTextOutput("Task wasn't found.");
}
}
else setTextOutput("Make sure date and status are correct.");
displayList(list);
//clear text
clearText(textDesc);
clearText(textDate);
clearText(textComplete);
}
public void editDueDate(){
ToDoItem t = new ToDoItem();
//get name and date
getDesc(t);
getDate(t);
getComplete(t);
//if the list has the task, add its due date
if (validateDesc() && validateDate() && validateComplete()){
for (int i = 0;i < list.size();i++){
if (list.get(i).desc.equalsIgnoreCase(t.desc) && list.get(i).complete == t.complete){
list.get(i).date = t.date;
setTextOutput("Successfully changed date.");
break;
}
else setTextOutput("Task wasn't found.");
}
}
else setTextOutput("Make sure desc. and status are correct.");
displayList(list);
//clear texts
clearText(textDesc);
clearText(textDate);
clearText(textComplete);
}
public void markItemComplete(){
ToDoItem t = new ToDoItem();
//receive the name of the ToDoList the user would like to edit from textDisplay
getDesc(t);
getDate(t);
getComplete(t);
if (validateComplete() && validateDesc() && validateDate()){
for (int i = 0;i < list.size();i++) {
if (t.desc.equalsIgnoreCase(list.get(i).desc) && t.date.equalsIgnoreCase(list.get(i).date)) {
list.get(i).complete = t.complete;
setTextOutput("Successfully changed status.");
}
else setTextOutput("Task wasn't found.");
}
}
else setTextOutput("Make sure date and desc. are correct.");
displayList(list);
//clear texts
clearText(textComplete);
clearText(textDate);
clearText(textDesc);
}
public void displayAllItems(){
//call displayList
displayList(list);
setTextOutput("Displaying all items.");
}
public void displayIncomplete(){
//make new list
List <ToDoItem> listIncomplete = new ArrayList<>();
//if item status is incomplete, add all items to new list
for (int i = 0;i < list.size();i++){
if (compare(list.get(i).complete,false) == 0){
listIncomplete.add(list.get(i));
}
}
//display new list
displayList(listIncomplete);
setTextOutput("Displaying incomplete items.");
}
public void displayCompletions(){
//make new list
List <ToDoItem> listComplete = new ArrayList<>();
//if item status is incomplete, add all items to new list
for (int i = 0;i < list.size();i++){
if (compare(list.get(i).complete,true) == 0){
listComplete.add(list.get(i));
}
}
//display new list
displayList(listComplete);
setTextOutput("Displaying complete items.");
}
public void saveItems(){
//saves items into another list
savedList = list;
setTextOutput("List saved successfully.");
}
public void loadList(){
//loads saved list
list.addAll(savedList);
displayList(list);
setTextOutput("Loaded list");
}
public String getText(TextField t){
//return the text from a TextField
return t.getText();
}
public void setTextOutput(String text){
//sets the text of textOutput to the parameter
textOutput.setText(text);
}
public void clearText(TextField t){
//sets the text of the TextField in the parameter blank
t.setText("");
}
public void getDesc(ToDoItem t){
//gets data from textDesc and sets it to t
t.desc = getText(textDesc);
}
public void getDate(ToDoItem t) {
//gets data from textDate and sets it to t
t.date = getText(textDate);
}
public void getComplete(ToDoItem t){
//gets data from textComplete and determines whether the boolean is true or false
if (getText(textComplete).equalsIgnoreCase("Complete"))
t.complete = true;
else if (getText(textComplete).equalsIgnoreCase("Incomplete"))
t.complete = false;
else t.complete = false;
}
public boolean validateDesc(){
//assures that the description is less than 256 characters
return getText(textDesc).length() > 0 && getText(textDesc).length() < 256;
}
public boolean validateDate(){
//create a string array that splits textDate by -'s
String [] stringArray = getText(textDate).split("-");
//create integer array and parseInt each element
ArrayList<Integer> intArray = new ArrayList<>();
for (int i = 0;i < stringArray.length; i++){
intArray.add(Integer.parseInt(stringArray[i]));
}
//assure that the date is valid by Gregorian standards
if (intArray.size() == 3){
return intArray.get(0) < 10000 && intArray.get(1) < 13 && intArray.get(2) < 32;
}
else return false;
}
public boolean validateComplete(){
//returns true if textComplete is "complete"
return getText(textComplete).equalsIgnoreCase("Complete") ||
getText(textComplete).equalsIgnoreCase("Incomplete");
}
public String listToString(int i){
String c = "Complete";
String inc = "Incomplete";
//determines the output of a toDoItem on a list by its status
if (list.get(i).complete){
return String.format("%s%32s%32s",list.get(i).desc,list.get(i).date,c);
}
else return String.format("%s%32s%32s",list.get(i).desc,list.get(i).date,inc);
}
public void displayList(List<ToDoItem> list){
//create observableList
ObservableList<String> observableList = FXCollections.observableArrayList();
//add each element in list to observableList
for(int i = 0;i < list.size();i++){
observableList.add(listToString(i));
}
//displays the list on listDisplay
listDisplay.setItems(observableList);
}
}
|
package io.mosip.tf.t5.cryptograph.service.impl;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.jaiimageio.jpeg2000.impl.J2KImageReader;
import io.mosip.kernel.core.cbeffutil.spi.CbeffUtil;
import io.mosip.kernel.core.exception.ExceptionUtils;
import io.mosip.kernel.core.logger.spi.Logger;
import io.mosip.kernel.core.pdfgenerator.exception.PDFGeneratorException;
import io.mosip.kernel.core.util.CryptoUtil;
import io.mosip.kernel.pdfgenerator.itext.constant.PDFGeneratorExceptionCodeConstant;
import io.mosip.tf.t5.cryptograph.constant.IdType;
import io.mosip.tf.t5.cryptograph.constant.LoggerFileConstant;
import io.mosip.tf.t5.cryptograph.constant.ServiceConstant;
import io.mosip.tf.t5.cryptograph.dto.DecryptRequestDto;
import io.mosip.tf.t5.cryptograph.dto.DecryptResponseDto;
import io.mosip.tf.t5.cryptograph.dto.JsonValue;
import io.mosip.tf.t5.cryptograph.exception.ApisResourceAccessException;
import io.mosip.tf.t5.cryptograph.exception.IdentityNotFoundException;
import io.mosip.tf.t5.cryptograph.exception.ParsingException;
import io.mosip.tf.t5.cryptograph.exception.PlatformErrorMessages;
import io.mosip.tf.t5.cryptograph.logger.CryptographLogger;
import io.mosip.tf.t5.cryptograph.logger.LogDescription;
import io.mosip.tf.t5.cryptograph.service.IDDecoderService;
import io.mosip.tf.t5.cryptograph.service.RestClientService;
import io.mosip.tf.t5.cryptograph.util.IDEncodeCaller;
import io.mosip.tf.t5.cryptograph.util.JsonUtil;
import io.mosip.tf.t5.cryptograph.util.Utilities;
import io.mosip.tf.t5.http.RequestWrapper;
import io.mosip.tf.t5.http.ResponseWrapper;
@Service
public class IDDecoderServiceImpl implements IDDecoderService {
@Autowired
private IDEncodeCaller enrollDataUpload;
/** The Constant VALUE. */
private static final String VALUE = "value";
/** The primary lang. */
@Value("${mosip.primary-language}")
private String primaryLang;
/** The secondary lang. */
@Value("${mosip.secondary-language}")
private String secondaryLang;
private static Logger printLogger = CryptographLogger.getLogger(IDDecoderServiceImpl.class);
/** The utilities. */
@Autowired
private Utilities utilities;
/** The rest client service. */
@Autowired
private RestClientService<Object> restClientService;
@Autowired
private CbeffUtil cbeffutil;
@Override
public void extractData(String credential, String credentialType, String encryptionPin, String requestId,
String sign, String cardType, boolean isPasswordProtected) {
printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.CRYPTOGRAPHID.toString(), "",
"IDDecoderServiceImpl::getDocuments()::entry");
String credentialSubject;
new HashMap<>();
String uin = null;
LogDescription description = new LogDescription();
String individualBio = null;
Map<String, Object> demoAttributes = new LinkedHashMap<>();
Map<String, byte[]> bioAttributes = new LinkedHashMap<>();
try {
credentialSubject = getCrdentialSubject(credential);
org.json.JSONObject credentialSubjectJson = new org.json.JSONObject(credentialSubject);
org.json.JSONObject decryptedJson = decryptAttribute(credentialSubjectJson, encryptionPin, credential);
individualBio = decryptedJson.getString("biometrics");
String individualBiometric = new String(individualBio);
uin = decryptedJson.getString("UIN");
boolean isBiometricsExtracted = extractBiometrics(individualBiometric, bioAttributes);
if (!isBiometricsExtracted) {
printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.CRYPTOGRAPHID.toString(),
uin, PlatformErrorMessages.PRT_PRT_APPLICANT_PHOTO_NOT_SET.name());
}
setDemographicsData(decryptedJson.toString(), demoAttributes);
demoAttributes.put(IdType.UIN.toString(), uin);
enrollDataUpload.uploadData(demoAttributes, bioAttributes);
} catch (Exception ex) {
ex.printStackTrace();
description.setMessage(PlatformErrorMessages.PRT_PRT_PDF_GENERATION_FAILED.getMessage());
description.setCode(PlatformErrorMessages.PRT_PRT_PDF_GENERATION_FAILED.getCode());
printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.CRYPTOGRAPHID.toString(),
"UIN", description + ex.getMessage() + ExceptionUtils.getStackTrace(ex));
throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(),
ex.getMessage() + ExceptionUtils.getStackTrace(ex));
}
printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.CRYPTOGRAPHID.toString(), "",
"IDDecoderServiceImpl::getDocuments()::exit");
}
/**
* Sets the applicant photo.
*
* @param response the response
* @param attributes the attributes
* @return true, if successful
* @throws Exception the exception
*/
private boolean extractBiometrics(String individualBio, Map<String, byte[]> attributes) throws Exception {
String value = individualBio;
if (value != null) {
Map<String, String> bdbBasedOnFace = cbeffutil.getBDBBasedOnType(CryptoUtil.decodeBase64(value), "Face",
null);
for (Entry<String, String> iterable_element : bdbBasedOnFace.entrySet()) {
attributes.put("face_image", convertToJPG(iterable_element.getValue(), true));
}
Map<String, String> bdbBasedOnFinger = cbeffutil.getBDBBasedOnType(CryptoUtil.decodeBase64(value), "Finger",
null);
for (Entry<String, String> iterable_element : bdbBasedOnFinger.entrySet()) {
String[] str = iterable_element.getKey().split("_");
if (str[1].equalsIgnoreCase("Right Thumb")) {
attributes.put("finger_image_r1", convertToJPG(iterable_element.getValue(), false));
}
if (str[1].equalsIgnoreCase("Right IndexFinger")) {
attributes.put("finger_image_r2", convertToJPG(iterable_element.getValue(), false));
}
// if (str[1].equalsIgnoreCase("Right MiddleFinger")) {
// attributes.put("finger_image_r3", convertToJPG(iterable_element.getValue()));
// }
// if (str[1].equalsIgnoreCase("Right RingFinger")) {
// attributes.put("finger_image_r4", convertToJPG(iterable_element.getValue()));
// }
// if (str[1].equalsIgnoreCase("Right LittleFinger")) {
// attributes.put("finger_image_r5", convertToJPG(iterable_element.getValue()));
// }
if (str[1].equalsIgnoreCase("Left Thumb")) {
attributes.put("finger_image_l1", convertToJPG(iterable_element.getValue(), false));
}
if (str[1].equalsIgnoreCase("Left IndexFinger")) {
attributes.put("finger_image_l2", convertToJPG(iterable_element.getValue(), false));
}
// if (str[1].equalsIgnoreCase("Left MiddleFinger")) {
// attributes.put("finger_image_l3", convertToJPG(iterable_element.getValue()));
// }
// if (str[1].equalsIgnoreCase("Left RingFinger")) {
// attributes.put("finger_image_l4", convertToJPG(iterable_element.getValue()));
// }
// if (str[1].equalsIgnoreCase("Left LittleFinger")) {
// attributes.put("finger_image_l5", convertToJPG(iterable_element.getValue()));
// }
}
}
if (attributes.size() > 0) {
return true;
}
return false;
}
/**
* Gets the artifacts.
*
* @param idJsonString the id json string
* @param attribute the attribute
* @return the artifacts
* @throws IOException Signals that an I/O exception has occurred.
* @throws ParseException
*/
@SuppressWarnings("unchecked")
private void setDemographicsData(String jsonString, Map<String, Object> attribute)
throws IOException, ParseException {
try {
JSONObject demographicIdentity = JsonUtil.objectMapperReadValue(jsonString, JSONObject.class);
if (demographicIdentity == null)
throw new IdentityNotFoundException(PlatformErrorMessages.PRT_PIS_IDENTITY_NOT_FOUND.getMessage());
String mapperJsonString = Utilities.getJson(utilities.getConfigServerFileStorageURL(),
utilities.getGetRegProcessorIdentityJson());
JSONObject mapperJson = JsonUtil.objectMapperReadValue(mapperJsonString, JSONObject.class);
JSONObject mapperIdentity = JsonUtil.getJSONObject(mapperJson,
utilities.getGetRegProcessorDemographicIdentity());
List<String> mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet());
for (String key : mapperJsonKeys) {
LinkedHashMap<String, String> jsonObject = JsonUtil.getJSONValue(mapperIdentity, key);
Object obj = null;
String values = jsonObject.get(VALUE);
for (String value : values.split(",")) {
Object object = demographicIdentity.get(value);
if (object != null) {
try {
obj = new JSONParser().parse(object.toString());
} catch (Exception e) {
obj = object;
}
if (obj instanceof JSONArray) {
JsonValue[] jsonValues = JsonUtil.mapJsonNodeToJavaObject(JsonValue.class, (JSONArray) obj);
for (JsonValue jsonValue : jsonValues) {
if (jsonValue.getLanguage().equals(primaryLang))
attribute.put(value + "_" + primaryLang, jsonValue.getValue());
if (jsonValue.getLanguage().equals(secondaryLang))
attribute.put(value + "_" + secondaryLang, jsonValue.getValue());
}
} else if (object instanceof JSONObject) {
JSONObject json = (JSONObject) object;
attribute.put(value, (String) json.get(VALUE));
} else {
attribute.put(value, String.valueOf(object));
}
}
}
}
} catch (JsonParseException | JsonMappingException e) {
printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.CRYPTOGRAPHID.toString(),
null, "Error while parsing Json file" + ExceptionUtils.getStackTrace(e));
throw new ParsingException(PlatformErrorMessages.PRT_RGS_JSON_PARSING_EXCEPTION.getMessage(), e);
}
}
private String getCrdentialSubject(String crdential) {
org.json.JSONObject jsonObject = new org.json.JSONObject(crdential);
String credentialSubject = jsonObject.get("credentialSubject").toString();
return credentialSubject;
}
public org.json.JSONObject decryptAttribute(org.json.JSONObject data, String encryptionPin, String credential) {
org.json.JSONObject jsonObj = new org.json.JSONObject(credential);
RequestWrapper<DecryptRequestDto> request = new RequestWrapper<>();
ResponseWrapper<DecryptResponseDto> response = new ResponseWrapper<DecryptResponseDto>();
LocalDateTime now = LocalDateTime.now(ZoneId.of("UTC"));
request.setRequesttime(now);
org.json.JSONArray jsonArray = (org.json.JSONArray) jsonObj.get("protectedAttributes");
if (!jsonArray.isEmpty()) {
for (Object str : jsonArray) {
try {
DecryptRequestDto decryptRequestDto = new DecryptRequestDto();
DecryptResponseDto decryptResponseDto = new DecryptResponseDto();
decryptRequestDto.setUserPin(encryptionPin);
decryptRequestDto.setData(data.getString(str.toString()));
request.setRequest(decryptRequestDto);
response = (ResponseWrapper) restClientService.postApi(ServiceConstant.DECRYPTPINBASSED, "", "",
request, ResponseWrapper.class);
decryptResponseDto = JsonUtil.readValue(JsonUtil.writeValueAsString(response.getResponse()),
DecryptResponseDto.class);
data.put((String) str, decryptResponseDto.getData());
} catch (ApisResourceAccessException e) {
printLogger.error(LoggerFileConstant.SESSIONID.toString(),
LoggerFileConstant.CRYPTOGRAPHID.toString(), null,
"Error while parsing Json file" + ExceptionUtils.getStackTrace(e));
throw new ParsingException(PlatformErrorMessages.PRT_RGS_JSON_PARSING_EXCEPTION.getMessage(), e);
} catch (IOException e) {
printLogger.error(LoggerFileConstant.SESSIONID.toString(),
LoggerFileConstant.CRYPTOGRAPHID.toString(), null,
"Error while parsing Json file" + ExceptionUtils.getStackTrace(e));
throw new ParsingException(PlatformErrorMessages.PRT_RGS_JSON_PARSING_EXCEPTION.getMessage(), e);
}
}
}
return data;
}
/**
*
* @param isoTemplate
* @return
*/
private byte[] convertToJPG(String isoTemplate, boolean isUpscaleRequired) {
byte[] inputFileBytes = CryptoUtil.decodeBase64(isoTemplate);
int index;
for (index = 0; index < inputFileBytes.length; index++) {
if ((char) inputFileBytes[index] == 'j' && (char) inputFileBytes[index + 1] == 'P') {
break;
}
}
try {
return convertToJPG(Arrays.copyOfRange(inputFileBytes, index - 4, inputFileBytes.length), "image",
isUpscaleRequired);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
*
* @param jp2Data
* @param fileName
* @return
* @throws IOException
*/
private byte[] convertToJPG(byte[] jp2Data, String fileName, boolean isUpscaleRequired) throws IOException {
ByteArrayOutputStream beforeUpScale = new ByteArrayOutputStream();
ByteArrayOutputStream afterUpScale = new ByteArrayOutputStream();
J2KImageReader j2kImageReader = new J2KImageReader(null);
j2kImageReader.setInput(ImageIO.createImageInputStream(new ByteArrayInputStream(jp2Data)));
ImageReadParam imageReadParam = j2kImageReader.getDefaultReadParam();
BufferedImage image = j2kImageReader.read(0, imageReadParam);
ImageIO.write(image, "PNG", beforeUpScale);
if (!isUpscaleRequired) {
return beforeUpScale.toByteArray();
}
int height = image.getHeight();
int width = image.getWidth();
BufferedImage outputImage = createResizedCopy(image, 2 * width, 2 * height, true);
ImageIO.write(outputImage, "PNG", afterUpScale);
byte[] jpgImg = afterUpScale.toByteArray();
return jpgImg;
}
/**
*
* @param originalImage
* @param scaledWidth
* @param scaledHeight
* @param preserveAlpha
* @return
*/
private BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight,
boolean preserveAlpha) {
System.out.println("resizing...");
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
}
|
package com.gaoshin.stock.plugin;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.gaoshin.sorma.SORMA;
import com.gaoshin.sorma.browser.JsonUtil;
import com.gaoshin.stock.BroadcastAction;
import com.gaoshin.stock.model.ConfigurationServiceImpl;
import com.gaoshin.stock.model.GroupItem;
import com.gaoshin.stock.model.StockContentProvider;
public class PluginWebView extends WebView {
private static final String TAG = PluginWebView.class.getSimpleName();
private float scale = 0;
private SORMA sorma;
private ConfigurationServiceImpl confService;
private boolean firstLoad = true;
private Plugin plugin;
private Integer symbol;
private Handler handler;
private PageStartedListener pageStartedListener;
private PageFinishedListener pageFinishedListener;
private ScaleChangedListener scaleChangedListener;
private Runnable postActionRunnable;
private boolean newPage = false;
private PluginParamList paramList;
public PluginWebView(Context context) {
super(context);
handler = new Handler();
setId(Math.abs(this.hashCode()));
sorma = SORMA.getInstance(context, StockContentProvider.class);
confService = new ConfigurationServiceImpl(sorma);
setupView();
}
private void setupView() {
setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
getSettings().setJavaScriptEnabled(true);
getSettings().setAllowFileAccess(true);
WebViewJavascriptInterface javascriptInterface = new WebViewJavascriptInterface();
addJavascriptInterface(javascriptInterface, "android");
WebChromeClient chromeClient = new WebChromeClient();
setWebChromeClient(chromeClient);
setWebViewClient(new GenericWebViewClient());
getSettings().setBuiltInZoomControls(true);
getSettings().setUseWideViewPort(true);
setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
setScrollbarFadingEnabled(true);
requestFocus(View.FOCUS_DOWN);
}
@Override
public boolean zoomIn() {
boolean ret = super.zoomIn();
float newScale = getScale();
if(scaleChangedListener != null) {
scaleChangedListener.onScaleChange(newScale);
}
scale = newScale;
return ret;
}
@Override
public boolean zoomOut() {
boolean ret = super.zoomOut();
float newScale = getScale();
if(scaleChangedListener != null) {
scaleChangedListener.onScaleChange(newScale);
}
scale = newScale;
return ret;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean b = super.onTouchEvent(ev);
float newScale = getScale();
if(scaleChangedListener != null) {
scaleChangedListener.onScaleChange(newScale);
}
scale = newScale;
return b;
}
public void setSymbol(Integer groupItemId) {
load(groupItemId, new HashMap<String, String>());
}
private void load(Integer groupItemId, Map<String, String> params) {
if(plugin == null) {
return;
}
this.symbol = groupItemId;
GroupItem groupItem = sorma.get(GroupItem.class, "id=" + groupItemId, null);
Map<String, String> finalParams = new HashMap<String, String>();
for(PluginParameter pp : paramList.getItems()) {
finalParams.put(pp.getName(), pp.getDefValue());
}
finalParams.putAll(params);
String url = plugin.getUrl();
url = url.replaceAll("__SYM__", groupItem.getSym());
for(PluginParameter pp : paramList.getItems()) {
String finalValue = finalParams.get(pp.getName());
if(finalValue == null) {
finalValue = "";
}
if(url.indexOf("__" + pp.getName() + "__") != -1) {
url = url.replaceAll("__" + pp.getName() + "__", finalValue);
}
else {
if(url.indexOf("?") == -1) {
url = url + "?" + pp.getName() + "=" + URLEncoder.encode(finalValue);
}
else {
if(url.endsWith("&")) {
url = url + pp.getName() + "=" + URLEncoder.encode(finalValue);
}
else {
url = url + "&" + pp.getName() + "=" + URLEncoder.encode(finalValue);
}
}
}
}
loadUrl(url);
}
public class GenericWebViewClient extends WebViewClient {
public GenericWebViewClient() {
postActionRunnable = new Runnable() {
@Override
public void run() {
newPage = false;
String postAction = PluginWebView.this.plugin.getPostAction();
if(postAction != null && postAction.trim().length() > 0) {
StringBuilder sb = new StringBuilder();
sb.append("javascript:").append(JavascriptLibrary.getInstance().getAllFunctions()).append(PluginWebView.this.plugin.getPostAction());
String url = sb.toString();
loadUrl(url);
if(pageFinishedListener != null) {
pageFinishedListener.onPageFinished();
}
}
else {
if(pageFinishedListener != null) {
pageFinishedListener.onPageFinished();
}
}
}
};
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
newPage = true;
if(scale != 0) {
view.setInitialScale((int) (scale * 100));
}
super.onPageStarted(view, url, favicon);
if(pageStartedListener != null) {
pageStartedListener.onPageStarted();
}
}
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
super.onScaleChanged(view, oldScale, newScale);
scale = newScale;
if(scaleChangedListener != null) {
scaleChangedListener.onScaleChange(newScale);
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(getContext(), "Error loading " + symbol + ". " + description, Toast.LENGTH_SHORT).show();
if(pageFinishedListener != null) {
pageFinishedListener.onPageFinished();
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(pageFinishedListener != null) {
pageFinishedListener.onPageFinished();
}
/* if(firstLoad) {
Toast.makeText(getContext(), "Double tap for zooming", Toast.LENGTH_LONG).show();
firstLoad = false;
}
if(newPage) {
newPage = false;
handler.removeCallbacks(postActionRunnable);
handler.post(postActionRunnable);
}*/
}
}
public Integer getSymbol() {
return symbol;
}
public class WebViewJavascriptInterface {
public void exit() {
}
public String getPlugins() {
List<Plugin> list = sorma.select(Plugin.class, null, null);
PluginList pl = new PluginList();
pl.setList(list);
return JsonUtil.toJsonString(pl);
}
public boolean deletePlugin(String pluginId) {
try {
sorma.delete(Plugin.class, "id="+pluginId, null);
Intent intent = new Intent(BroadcastAction.PluginDeleted.name());
intent.putExtra("data", Integer.parseInt(pluginId));
getContext().sendBroadcast(intent);
return true;
}
catch (Exception e) {
return false;
}
}
public boolean addPlugin(String json) {
try {
Plugin plugin = JsonUtil.toJavaObject(json, Plugin.class);
sorma.insert(plugin);
Intent intent = new Intent(BroadcastAction.PluginAdded.name());
intent.putExtra("data", plugin.getId());
getContext().sendBroadcast(intent);
return true;
}
catch (Exception e) {
return false;
}
}
public void onDomReady() {
Log.d(TAG, "dom ready");
newPage = false;
handler.removeCallbacks(postActionRunnable);
handler.post(postActionRunnable);
}
}
private class PluginList {
private List<Plugin> list = new ArrayList<Plugin>();
public List<Plugin> getList() {
return list;
}
public void setList(List<Plugin> list) {
this.list = list;
}
}
public PageStartedListener getPageStartedListener() {
return pageStartedListener;
}
public void setPageStartedListener(PageStartedListener pageStartedListener) {
this.pageStartedListener = pageStartedListener;
}
public PageFinishedListener getPageFinishedListener() {
return pageFinishedListener;
}
public void setPageFinishedListener(PageFinishedListener pageFinishedListener) {
this.pageFinishedListener = pageFinishedListener;
}
public void setPlugin(Plugin plugin2) {
this.plugin = plugin2;
if(plugin.getParamsJson() != null) {
paramList = JsonUtil.toJavaObject(plugin.getParamsJson(), PluginParamList.class);
}
else {
paramList = new PluginParamList();
}
}
public Plugin getPlugin() {
return plugin;
}
public ScaleChangedListener getScaleChangedListener() {
return scaleChangedListener;
}
public void setScaleChangedListener(ScaleChangedListener scaleChangedListener) {
this.scaleChangedListener = scaleChangedListener;
}
public void setScale(float newScale) {
scale = newScale;
}
public void refresh() {
plugin = sorma.get(Plugin.class, "id=" + plugin.getId(), null);
setPlugin(plugin);
setSymbol(getSymbol());
}
}
|
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import servlet.*;
public class Main {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new ApiServlet()), "/api/*");
context.addServlet(new ServletHolder(new MoneyTransactionServlet()), "/transaction");
context.addServlet(new ServletHolder(new RegistrationServlet()), "/registration");
context.addServlet(new ServletHolder(new ResultServlet()), "/result");
context.addServlet(new ServletHolder(new UtilityServlet()), "/renew");
context.addServlet(new ServletHolder(new AllUsers()), "/users");
Server server = new Server(8080);
server.setHandler(context);
server.start();
server.join();
}
}
|
package com.c4wrd.loadtester.testservice;
import com.c4wrd.loadtester.request.RequestDetail;
import java.io.IOException;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
public abstract class RequestExecutorBase implements Callable<List<RequestDetail>> {
protected int threadCount, interval;
RequestExecutorBase() {}
RequestExecutorBase(int interval) {
this.interval = interval;
}
RequestExecutorBase(int threadCount, int interval) {
this.threadCount = threadCount;
this.interval = interval;
}
List<RequestDetail> getResults(Queue<Future<RequestDetail>> requestQueue) throws IOException {
return requestQueue.parallelStream()
.map(
(item) -> {
try {
return item.isDone() ? item.get() : null;
} catch (InterruptedException | ExecutionException e) {
return null;
}
})
.filter(item -> item != null)
.collect(Collectors.toList());
}
}
|
package com.example.bootcamp.controller;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.bootcamp.commons.ResponseMessage;
import com.example.bootcamp.commons.ResponseStatus;
import com.example.bootcamp.model.EmailPhoneModel;
import com.example.bootcamp.model.ResetPasswordModel;
import com.example.bootcamp.service.UserPasswordTokenService;
import com.example.bootcamp.utils.Constant;
import com.example.bootcamp.utils.JsonUtils;
@RestController
@RequestMapping("/user")
public class UserPasswordTokenController {
private static final Logger logger = LoggerFactory.getLogger(UserPasswordTokenController.class);
@Autowired
UserPasswordTokenService userPasswordTokenService;
@RequestMapping(value="/forgot-password",produces="application/json",method = {RequestMethod.POST})
public ResponseEntity<String> sendPasswordResetLink( @Valid @RequestBody EmailPhoneModel emailorPhoneModel){
String response =null;
try {
response = userPasswordTokenService.sendPasswordResetLink(emailorPhoneModel.getEmailorPhone());
return new ResponseEntity<String>(response,HttpStatus.OK);
} catch (DataIntegrityViolationException e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.DATABASE_EXCEPTION,
ResponseMessage.DATA_VALIDATION_ERROR,
null),HttpStatus.OK);
} catch (Exception e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.INTERNAL_ERROR,
ResponseMessage.INTERNAL_ERROR,
null),HttpStatus.OK);
}
}
@RequestMapping(value="/verify-password-link",produces="application/json",method = {RequestMethod.GET})
public ResponseEntity<String> verifyPasswordResetLink(HttpServletRequest req){
String response =null;
try {
String resetLink = req.getHeader(Constant.RESET_LINK_HEADER);
if(null == resetLink)
response = JsonUtils.getResponseJson(ResponseStatus.FAILED,
ResponseMessage.EMAIL_OR_RESET_LINK_INVALID,
null);
else
response = userPasswordTokenService.verifyPasswordResetLink(resetLink);
return new ResponseEntity<String>(response,HttpStatus.OK);
} catch (DataIntegrityViolationException e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.DATABASE_EXCEPTION,
ResponseMessage.DATA_VALIDATION_ERROR,
null),HttpStatus.OK);
} catch (Exception e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.INTERNAL_ERROR,
ResponseMessage.INTERNAL_ERROR,
null),HttpStatus.OK);
}
}
@RequestMapping(value="/update-password",produces="application/json",method = {RequestMethod.POST})
public ResponseEntity<String> updatePassword(@Valid @RequestBody ResetPasswordModel resetPasswordModel , HttpServletRequest req){
String response =null;
try {
String resetLink = req.getHeader(Constant.RESET_LINK_HEADER);
if(null == resetLink)
response = JsonUtils.getResponseJson(ResponseStatus.FAILED,
ResponseMessage.EMAIL_OR_RESET_LINK_INVALID,
null);
else
response = userPasswordTokenService.updatePassword(resetPasswordModel,resetLink);
return new ResponseEntity<String>(response,HttpStatus.OK);
} catch (DataIntegrityViolationException e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.DATABASE_EXCEPTION,
ResponseMessage.DATA_VALIDATION_ERROR,
null),HttpStatus.OK);
} catch (Exception e) {
logger.error(e.toString());
return new ResponseEntity<String>(JsonUtils.getResponseJson(ResponseStatus.INTERNAL_ERROR,
ResponseMessage.INTERNAL_ERROR,
null),HttpStatus.OK);
}
}
}
|
package com.myvodafone.android.model.service;
import com.myvodafone.android.utils.StaticTools;
public class Asset_msisdn {
public StringBuffer last_change_tariff_date = null;
public StringBuffer switch_on_date = null;
public StringBuffer agreement_date = null;
public StringBuffer sim_only_eligible = null;
public StringBuffer retention_eligible = null;
public StringBuffer number = null;
public StringBuffer name = null;
public Asset_tariff_plan tariff_plan = null;
public Asset_msisdn(String last_change_tariff_date, String switch_on_date, String agreement_date, String sim_only_eligible,
String retention_eligible, String number, String name, Asset_tariff_plan tariff_plan) {
this.last_change_tariff_date = new StringBuffer(last_change_tariff_date);
this.switch_on_date = new StringBuffer(switch_on_date);
this.agreement_date = new StringBuffer(agreement_date);
this.sim_only_eligible = new StringBuffer(sim_only_eligible);
this.retention_eligible = new StringBuffer(retention_eligible);
this.number = new StringBuffer(number);
this.name = new StringBuffer(name);
this.tariff_plan = tariff_plan;
}
public Asset_msisdn() {
this.last_change_tariff_date = new StringBuffer();
this.switch_on_date = new StringBuffer();
this.agreement_date = new StringBuffer();
this.sim_only_eligible = new StringBuffer();
this.retention_eligible = new StringBuffer();
this.number = new StringBuffer();
this.name = new StringBuffer();
this.tariff_plan = new Asset_tariff_plan();
}
public String getLast_change_tariff_date() {
return last_change_tariff_date.toString();
}
public void setLast_change_tariff_date(String last_change_tariff_date) {
this.last_change_tariff_date.append(last_change_tariff_date.trim());
}
public String getSwitch_on_date() {
return switch_on_date.toString();
}
public void setSwitch_on_date(String switch_on_date) {
this.switch_on_date.append(switch_on_date.trim());
}
public String getAgreement_date() {
return agreement_date.toString();
}
public void setAgreement_date(String agreement_date) {
this.agreement_date.append(agreement_date.trim());
}
public String getSim_only_eligible() {
return sim_only_eligible.toString();
}
public void setSim_only_eligible(String sim_only_eligible) {
this.sim_only_eligible.append(sim_only_eligible.trim());
}
public String getRetention_eligible() {
return retention_eligible.toString();
}
public void setRetention_eligible(String retention_eligible) {
this.retention_eligible.append(retention_eligible.trim());
}
public String getNumber() {
return number.toString();
}
public void setNumber(String number) {
this.number.append(number.trim());
}
public String getName() {
return name.toString();
}
public void setName(String name) {
this.name.append(name.trim());
}
public Asset_tariff_plan getTariff_plan() {
return tariff_plan;
}
public void setTariff_plan(Asset_tariff_plan tariff_plan) {
this.tariff_plan = tariff_plan;
}
// PRINT
public void print() {
StaticTools.Log("ITEM BANNER:: ", "" + last_change_tariff_date);
StaticTools.Log("ITEM BANNER:: ", "" + switch_on_date);
StaticTools.Log("ITEM BANNER:: ", "" + agreement_date);
StaticTools.Log("ITEM BANNER:: ", "" + sim_only_eligible);
StaticTools.Log("ITEM BANNER:: ", "" + retention_eligible);
StaticTools.Log("ITEM BANNER:: ", "" + number);
StaticTools.Log("ITEM BANNER:: ", "" + name);
StaticTools.Log("ITEM BANNER:: ", "Start_tariff");
tariff_plan.print();
StaticTools.Log("ITEM BANNER:: ", "End_tariff");
}
} |
package partieConsole;
public class Module {
private int idModule;
private String libeleModole;
public Module(int idModule, String libeleModole) {
super();
this.idModule = idModule;
this.libeleModole = libeleModole;
}
public Module() {
// TODO Auto-generated constructor stub
}
public int getIdModule() {
return idModule;
}
public void setIdModule(int idModule) {
this.idModule = idModule;
}
public String getLibeleModole() {
return libeleModole;
}
public void setLibeleModole(String libeleModole) {
this.libeleModole = libeleModole;
}
@Override
public String toString() {
return "" + idModule;
}
}
|
package com.tweetqueue.core.services.user;
import com.tweetqueue.core.model.user.User;
import com.tweetqueue.core.model.user.UserFactory;
import com.tweetqueue.core.model.user.UserRepository;
public class CreateUserService {
private final UserRepository userRepository;
private final UserFactory userFactory;
private final UserResponseFactory userResponseFactory;
public CreateUserService(
UserRepository userRepository,
UserFactory userFactory,
UserResponseFactory userResponseFactory) {
this.userRepository = userRepository;
this.userFactory = userFactory;
this.userResponseFactory = userResponseFactory;
}
public UserResponse createUser(CreateUserRequest createUserRequest) {
User user = userRepository.save(userFactory.getUser(createUserRequest.getUsername()));
return userResponseFactory.getUserResponse(user);
}
}
|
/**
* DB操作之ORM功能注解
*/
package xyz.noark.core.annotation.orm; |
package com.ardoise.model;
/**
*
* <b> Cette énumération regroupe les formes possibles du pinceau </b>
*
* @author Oltenos
* @version 1
*/
public enum Forme {
CARRE("Carré", "images/carre.png"), ROND("Rond", "images/rond.png");
/**
* nom de la forme
*/
String nom;
/**
* adresse de l'icone représentant le forme dans la barre d'outils
*/
String adresseIcon;
/**
* Constructeur
*
* @param nom
* nom de la forme
* @param adresseIcon
* adresse de l'icone représentant le forme dans la barre d'outils
*/
Forme(String nom, String adresseIcon) {
this.nom = nom;
this.adresseIcon = adresseIcon;
}
/**
* retourne le nom de la forme
*
* @return nom de la forme
*/
public String toString() {
return nom;
}
/**
* retourne l'adresse de l'icone représentant le forme dans la barre d'outils
*
* @return adresse de l'icone représentant le forme dans la barre d'outils
*/
public String getAdresseIcon() {
return adresseIcon;
}
}
|
package controller;
import handler.HandlerJDO;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
public class ModificarLibroController implements Initializable {
HandlerJDO jdo = new HandlerJDO();
@FXML
ComponenteModificarController componenteModificarController;
@FXML
ComponenteBuscarController componenteBuscarController;
@FXML
Button modificarLibro;
/**
* Método para el botón pulsar que buscará el libro a través del ID y
* establecerá los datos en lso TextField
*
* @param event
*/
@FXML
public void buscar(ActionEvent event) {
componenteModificarController.buscarLibro(componenteBuscarController.getFieldId());
if (componenteModificarController.getTxtId().equals("")) {
componenteModificarController.deshabilitarCampos();
modificarLibro.setDisable(true);
} else {
componenteModificarController.habilitarCampos();
modificarLibro.setDisable(false);
}
}
/**
* Método para modificar un libro, cogerá los vfalores introducidos y se los
* pasará al HandlerJDO para que modifique el libro a través del método
* modificarLibro()
*
* @param event
*/
@FXML
public void modificarLibro(ActionEvent event) {
//Cojo todos los daotos
int id = Integer.parseInt(componenteModificarController.getTxtId());
String nombre = componenteModificarController.getTxtNombre();
String autor = componenteModificarController.getTxtAutor();
String comentarios = componenteModificarController.getTxtComentarios();
boolean leido = (componenteModificarController.getSiRadio()) ? true : false;
String genero = componenteModificarController.getTxtGenero();
String puntuacion = componenteModificarController.getTxtPuntuacion();
//Ahora realizo la modificación
jdo.modificarLibro(id, nombre, autor, genero, comentarios, leido, puntuacion);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
componenteModificarController.deshabilitarCampos();
modificarLibro.setDisable(true);
}
}
|
package com.cloudinte.modules.xingzhengguanli.dao;
import java.util.List;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.cloudinte.modules.xingzhengguanli.entity.EducationProjectPerformance;
/**
* 项目支出绩效目标申报DAO接口
* @author dcl
* @version 2019-12-16
*/
@MyBatisDao
public interface EducationProjectPerformanceDao extends CrudDao<EducationProjectPerformance> {
long findCount(EducationProjectPerformance educationProjectPerformance);
void batchInsert(List<EducationProjectPerformance> educationProjectPerformance);
void batchUpdate(List<EducationProjectPerformance> educationProjectPerformance);
void batchInsertUpdate(List<EducationProjectPerformance> educationProjectPerformance);
void disable(EducationProjectPerformance educationProjectPerformance);
void deleteByIds(EducationProjectPerformance educationProjectPerformance);
} |
package com.citibank.ods.entity.bg.valueobject;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
*
* @see package com.citibank.ods.entity.bg.valueobject;
* @version 1.0
* @author michele.monteiro,18/06/2007
*/
public class BaseTbgPointAcctInvstEntityVO extends BaseEntityVO
{
//Número da filial
private String m_acctBrchNbr = "";
//Número da entidade
private String m_acctBusNbr = "";
//Número da conta corrente
private String m_curAcctNbr = "";
//Número da filial
private String m_invstAcctBrchNbr = "";
//Número da entidade
private String m_invstAcctBusNbr = "";
//Conta Investimento
private String m_invstCurAcctNbr = "";
//Código de origem do movimento
private String m_custMovOrigCode = "";
/**
* @return Returns curAcctNbr.
*/
public String getCurAcctNbr()
{
return m_curAcctNbr;
}
/**
* @param curAcctNbr_ Field curAcctNbr to be setted.
*/
public void setCurAcctNbr( String curAcctNbr_ )
{
m_curAcctNbr = curAcctNbr_;
}
/**
* @return Returns acctBrchNbr.
*/
public String getAcctBrchNbr()
{
return m_acctBrchNbr;
}
/**
* @param acctBrchNbr_ Field acctBrchNbr to be setted.
*/
public void setAcctBrchNbr( String acctBrchNbr_ )
{
m_acctBrchNbr = acctBrchNbr_;
}
/**
* @return Returns acctBusNbr.
*/
public String getAcctBusNbr()
{
return m_acctBusNbr;
}
/**
* @param acctBusNbr_ Field acctBusNbr to be setted.
*/
public void setAcctBusNbr( String acctBusNbr_ )
{
m_acctBusNbr = acctBusNbr_;
}
/**
* @return Returns custOrigCode.
*/
public String getMovCustOrigCode()
{
return m_custMovOrigCode;
}
/**
* @param custOrigCode_ Field custOrigCode to be setted.
*/
public void setCustMovOrigCode( String custOrigCode_ )
{
m_custMovOrigCode = custOrigCode_;
}
/**
* @return Returns invstAcctBrchNbr.
*/
public String getInvstAcctBrchNbr()
{
return m_invstAcctBrchNbr;
}
/**
* @param invstAcctBrchNbr_ Field invstAcctBrchNbr to be setted.
*/
public void setInvstAcctBrchNbr( String invstAcctBrchNbr_ )
{
m_invstAcctBrchNbr = invstAcctBrchNbr_;
}
/**
* @return Returns invstAcctBusNbr.
*/
public String getInvstAcctBusNbr()
{
return m_invstAcctBusNbr;
}
/**
* @param invstAcctBusNbr_ Field invstAcctBusNbr to be setted.
*/
public void setInvstAcctBusNbr( String invstAcctBusNbr_ )
{
m_invstAcctBusNbr = invstAcctBusNbr_;
}
/**
* @return Returns invstCurAcctNbr.
*/
public String getInvstCurAcctNbr()
{
return m_invstCurAcctNbr;
}
/**
* @param invstCurAcctNbr_ Field invstCurAcctNbr to be setted.
*/
public void setInvstCurAcctNbr( String invstCurAcctNbr_ )
{
m_invstCurAcctNbr = invstCurAcctNbr_;
}
} |
/*
*
* This code finds the longest pallindromic subsequence in this string
* Time complexity - O(n*n)
* Space complexity - O(n*n)
* Youtube link - https://youtu.be/_nCsPn7_OgI
* Reference: https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/LongestPalindromicSubsequence.java
* if the given sequence is BBABCBCAB, then the output should be 7 as BABCBAB is the longest palindromic subseuqnce in it.
* BBBBB and BBCBB are also palindromic subsequences of the given sequence, but not the longest ones.
*/
public class LongestPallindromicSubsequence {
// function to count longest pallindromic subsequence using Dynamic Programming
public int countLongestPalSubseq(char[] str) {
int T[][] = new int[str.length][str.length];
for(int i = 0; i < str.length; i++) {
T[i][i] = 1;
}
int n = str.length;
for(int l = 2; l <= n; l++) {
for(int i = 0; i < n - l + 1; i++) {
int j = i + l - 1;
// if(l == 2 && str[i] == str[j]) {
// T[i][j] = 2;
// } else
if(str[i] == str[j]) {
T[i][j] = T[i + 1][j - 1] + 2;
} else {
T[i][j] = Math.max(T[i + 1][j], T[i][j - 1]);
}
}
}
return T[0][str.length - 1]; // remember this [str.length - 1] .. it is not [str.length]
}
//function to calculate longest pallindromic subsequence using recursion
public int countLongestSubSequence(char[] str, int start, int len) {
// Base Case 1: If there is only 1 character
if(start == len) {
return 1;
}
// Base Case 2: If there are only 2 characters and both are same
if (str[start] == str[len] && start + 1 == len) {
return 2;
}
if(str[start] == str[len]) {
return 2 + countLongestSubSequence(str, start + 1, len - 1);
} else {
return Math.max(countLongestSubSequence(str, start + 1, len), countLongestSubSequence(str, start, len - 1));
}
}
//main method
public static void main(String args[]) {
LongestPallindromicSubsequence lps = new LongestPallindromicSubsequence();
String str1 = "BBABCBCAB";
int longestSubseqCount = lps.countLongestPalSubseq(str1.toCharArray());
int n = str1.length() - 1; // remmber this -1
int longestSubseqCountRecur = lps.countLongestSubSequence(str1.toCharArray(), 0, n);
System.out.println(longestSubseqCountRecur);
System.out.println(longestSubseqCount);
}
} |
public class Test{
//final usage:
// mTempMatrix can't changed,not the context of mTempMatrix[..]
private static final float[] mTempMatrix = new float[16];
public static void main(String[] args){
Student st1 = new Student();
Student st2 = new Student();
//age=24 amount=100
st1.age+=2;
st2.age+=3;
st2.amount+=100;
System.out.println("st1.age "+st1.age);
System.out.println("st2.age "+st2.age);
System.out.println("st2.amount "+st2.amount);
System.out.println("amount "+Student.amount);
final float[] temp = mTempMatrix;
temp[1] = 3.0f;
temp[1] = 5.0f;
System.out.println("mTempMatrix[1]: "+mTempMatrix[1]);
}
}
//st1.age 26
//st2.age 27
//st2.amount 200
//amount 200
|
package com.mycompany.ghhrkapp1.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mycompany.ghhrkapp1.dto.JobsDTO;
import com.mycompany.ghhrkapp1.entity.Jobs;
import com.mycompany.ghhrkapp1.service.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/job")
@Api(value="hr", description="Jobs data")
public class JobsController
{
@Autowired
JobService jobService;
@ApiOperation(value = "List of Jobs", response = Iterable.class)
@RequestMapping(value = "/list", method= RequestMethod.GET, produces = "application/json")
public Iterable<Jobs> list(Model model)
{
Iterable<Jobs> ret = jobService.listAll();
return ret;
}
@ApiOperation(value = "List a page of Jobs", response = Iterable.class)
@RequestMapping(value = "/list/{page}", method= RequestMethod.GET, produces = "application/json")
public Page<Jobs> list(@PathVariable Integer page, Model model)
{
Page<Jobs> ret = jobService.listAllPaged(page - 1);
return ret;
}
@ApiOperation(value = "Add a job")
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity save(@RequestBody JobsDTO jobDTO)
{
jobService.save(jobDTO);
return new ResponseEntity("Job saved successfully", HttpStatus.CREATED);
}
}
|
package com.ahuo.personapp.base;
import android.support.v4.app.Fragment;
/**
* Created on 17-5-10
*
* @author liuhuijie
*/
public class BaseFragment extends Fragment{
}
|
package engine.managers.objects.scrollers;
import com.badlogic.gdx.math.Rectangle;
import engine.interfaces.InformationProvider;
import engine.managers.objects.EntitiesManager;
import engine.utils.EntityFactory;
import entities.Fruit;
import entities.EntityType;
public class FruitsManager extends EntitiesManager<Fruit> {
private InformationProvider provider;
public FruitsManager(float interval, float Scroll_Speed,
InformationProvider provider) {
super(interval, Scroll_Speed);
this.provider = provider;
}
@Override
public void update(float delta) {
if (entities.size != 0) {
for (Fruit fruit : entities) {
fruit.update(delta);
if(fruit.isNotVisible()) {
removeValue(fruit);
EntityFactory.getInstance().getPools().free(fruit);
provider.getGameListener().notifyStrikesDecreasment();
}
}
}
if (timer.hasTimeElapsed()) {
addObject();
timer.reset();
}
timer.update(delta);
}
public int isCollidedWithMonkeyFruits(Rectangle bodyMonkey) {
for (Fruit entity : entities) {
if (bodyMonkey.overlaps(entity.getBody())) {
removeValue(entity);
EntityFactory.getInstance().getPools().free(entity);
return entity.getPoints();
}
}
return 0;
}
public void addObject() {
Fruit fruit = (Fruit) EntityFactory.getInstance().createEntity(EntityType.FRUIT);
entities.add(fruit);
}
}
|
package com.cpro.rxjavaretrofit.views.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cpro.rxjavaretrofit.R;
import com.cpro.rxjavaretrofit.constant.InterfaceUrl;
import com.cpro.rxjavaretrofit.entity.JsonReturnCommonEntity;
import com.cpro.rxjavaretrofit.entity.JsonReturnCommonSubmitEntity;
import com.cpro.rxjavaretrofit.entity.RoleTaskSupervisionDetailEntity;
import com.cpro.rxjavaretrofit.entity.TaskConfirmFormEntity;
import com.cpro.rxjavaretrofit.entity.TaskDetailFormEntity;
import com.cpro.rxjavaretrofit.listener.OnRecyclerItemClickListener;
import com.cpro.rxjavaretrofit.utils.JSONUtils;
import com.cpro.rxjavaretrofit.views.adapter.RoleTaskSupervisionDetailAnnexesAdapter;
import com.cpro.rxjavaretrofit.views.adapter.RoleTaskSupervisionDetailImagesAdapter;
import com.cpro.rxjavaretrofit.views.adapter.RoleTaskSupervisionDetailJoinMemberAdapter;
import com.cpro.rxjavaretrofit.views.adapter.RoleTaskSupervisionDetailReportImagesAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import java.io.File;
import java.lang.reflect.Type;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by lx on 2016/6/20.
*/
public class RoleTaskSupervisionDetailsActivity extends AppCompatActivity {
@BindView(R.id.role_task_supervision_detail_toolbar)
Toolbar roleTaskSupervisionDetailToolbar;
@BindView(R.id.pb_role_task_sp_download_file)
ProgressBar pbRoleTaskSpDownloadFile;
@BindView(R.id.tv_role_task_supervision_detail_title)
TextView tvRoleTaskSupervisionDetailTitle;
@BindView(R.id.tv_role_task_supervision_detail_sender)
TextView tvRoleTaskSupervisionDetailSender;
@BindView(R.id.tv_role_task_supervision_detail_time)
TextView tvRoleTaskSupervisionDetailTime;
@BindView(R.id.tv_role_task_supervision_detail_content)
TextView tvRoleTaskSupervisionDetailContent;
@BindView(R.id.rv_role_task_supervision_detail_join_member)
RecyclerView rvRoleTaskSupervisionDetailJoinMember;
@BindView(R.id.rv_role_task_supervision_detail_photo)
RecyclerView rvRoleTaskSupervisionDetailPhoto;
@BindView(R.id.rv_role_task_supervision_detail_annex)
RecyclerView rvRoleTaskSupervisionDetailAnnex;
@BindView(R.id.tv_role_task_supervision_detail_report_content)
TextView tvRoleTaskSupervisionDetailReportContent;
@BindView(R.id.rv_role_task_supervision_detail_report)
RecyclerView rvRoleTaskSupervisionDetailReport;
@BindView(R.id.btn_role_task_supervision_detail_submit)
Button btnRoleTaskSupervisionDetailSubmit;
RoleTaskSupervisionDetailEntity roleTaskSupervisionDetailEntity;
RoleTaskSupervisionDetailImagesAdapter roleTaskSupervisionDetailImagesAdapter;
RoleTaskSupervisionDetailReportImagesAdapter roleTaskSupervisionDetailReportImagesAdapter;
RoleTaskSupervisionDetailAnnexesAdapter roleTaskSupervisionDetailAnnexesAdapter;
RoleTaskSupervisionDetailJoinMemberAdapter roleTaskSupervisionDetailJoinMemberAdapter;
private MaterialDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_role_task_supervision_detail);
ButterKnife.bind(this);
roleTaskSupervisionDetailToolbar.setTitle("任务详情");
setSupportActionBar(roleTaskSupervisionDetailToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayoutManager linearLayoutManagerImages = new LinearLayoutManager(this);
linearLayoutManagerImages.setOrientation(LinearLayoutManager.HORIZONTAL);
rvRoleTaskSupervisionDetailPhoto.setLayoutManager(linearLayoutManagerImages);
LinearLayoutManager linearLayoutManagerReportImages = new LinearLayoutManager(this);
linearLayoutManagerReportImages.setOrientation(LinearLayoutManager.HORIZONTAL);
rvRoleTaskSupervisionDetailReport.setLayoutManager(linearLayoutManagerReportImages);
LinearLayoutManager linearLayoutManagerFiles = new LinearLayoutManager(this);
linearLayoutManagerFiles.setOrientation(LinearLayoutManager.HORIZONTAL);
rvRoleTaskSupervisionDetailAnnex.setLayoutManager(linearLayoutManagerFiles);
GridLayoutManager gridLayoutManagerJoinMember = new GridLayoutManager(this, 3);
rvRoleTaskSupervisionDetailJoinMember.setLayoutManager(gridLayoutManagerJoinMember);
roleTaskSupervisionDetailAnnexesAdapter = new RoleTaskSupervisionDetailAnnexesAdapter();
rvRoleTaskSupervisionDetailAnnex.setAdapter(roleTaskSupervisionDetailAnnexesAdapter);
roleTaskSupervisionDetailImagesAdapter = new RoleTaskSupervisionDetailImagesAdapter();
rvRoleTaskSupervisionDetailPhoto.setAdapter(roleTaskSupervisionDetailImagesAdapter);
roleTaskSupervisionDetailJoinMemberAdapter = new RoleTaskSupervisionDetailJoinMemberAdapter();
rvRoleTaskSupervisionDetailJoinMember.setAdapter(roleTaskSupervisionDetailJoinMemberAdapter);
roleTaskSupervisionDetailReportImagesAdapter = new RoleTaskSupervisionDetailReportImagesAdapter();
rvRoleTaskSupervisionDetailReport.setAdapter(roleTaskSupervisionDetailReportImagesAdapter);
rvRoleTaskSupervisionDetailPhoto.addOnItemTouchListener(new OnRecyclerItemClickListener(rvRoleTaskSupervisionDetailPhoto) {
@Override
public void onItemClick(RecyclerView.ViewHolder viewHolder) {
RoleTaskSupervisionDetailImagesAdapter.RoleTaskSupervisionDetailImagesViewHolder roleTaskSupervisionDetailImagesViewHolder = (RoleTaskSupervisionDetailImagesAdapter.RoleTaskSupervisionDetailImagesViewHolder) viewHolder;
Intent intent = new Intent();
intent.putExtra("image_url", roleTaskSupervisionDetailImagesViewHolder.image_url);
intent.setClass(RoleTaskSupervisionDetailsActivity.this, CommonDetailBigImgActivity.class);
startActivity(intent);
}
@Override
public void onItemLongClick(RecyclerView.ViewHolder viewHolder) {
}
});
rvRoleTaskSupervisionDetailAnnex.addOnItemTouchListener(new OnRecyclerItemClickListener(rvRoleTaskSupervisionDetailAnnex) {
@Override
public void onItemClick(final RecyclerView.ViewHolder viewHolder) {
final RoleTaskSupervisionDetailAnnexesAdapter.RoleTaskSupervisionDetailAnnexesViewHoleder roleTaskSupervisionDetailAnnexesViewHoleder = (RoleTaskSupervisionDetailAnnexesAdapter.RoleTaskSupervisionDetailAnnexesViewHoleder) viewHolder;
OkHttpUtils
.get()
.url(roleTaskSupervisionDetailAnnexesViewHoleder.file_url)
.build()
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath() + InterfaceUrl.FILE_DOWNLOAD_PATH, roleTaskSupervisionDetailAnnexesViewHoleder.file_url.substring(roleTaskSupervisionDetailAnnexesViewHoleder.file_url.lastIndexOf("/") + 1, roleTaskSupervisionDetailAnnexesViewHoleder.file_url.length())) {
@Override
public void onBefore(Request request, int id) {
super.onBefore(request, id);
pbRoleTaskSpDownloadFile.setVisibility(View.VISIBLE);
roleTaskSupervisionDetailAnnexesViewHoleder.tv_common_detail_download_label.setText(R.string.downloading_file);
}
@Override
public void inProgress(float progress, long total, int id) {
super.inProgress(progress, total, id);
pbRoleTaskSpDownloadFile.setProgress((int) (100 * progress));
}
@Override
public void onError(Call call, Exception e, int id) {
Snackbar.make(btnRoleTaskSupervisionDetailSubmit, getResources().getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show();
}
@Override
public void onResponse(File response, int id) {
pbRoleTaskSpDownloadFile.setVisibility(View.GONE);
Snackbar.make(viewHolder.itemView, R.string.download_complete, Snackbar.LENGTH_LONG)
.setAction("打开", new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + InterfaceUrl.FILE_DOWNLOAD_PATH + roleTaskSupervisionDetailAnnexesViewHoleder.file_url.substring(roleTaskSupervisionDetailAnnexesViewHoleder.file_url.lastIndexOf("/") + 1, roleTaskSupervisionDetailAnnexesViewHoleder.file_url.length())), "*/*");
startActivity(intent);
}
}).show();
roleTaskSupervisionDetailAnnexesViewHoleder.tv_common_detail_download_label.setText(R.string.download_file_complete);
roleTaskSupervisionDetailAnnexesViewHoleder.tv_common_detail_download_label.setTextColor(getResources().getColor(R.color.md_amber_200));
}
@Override
public void onAfter(int id) {
super.onAfter(id);
}
});
}
@Override
public void onItemLongClick(RecyclerView.ViewHolder viewHolder) {
}
});
rvRoleTaskSupervisionDetailReport.addOnItemTouchListener(new OnRecyclerItemClickListener(rvRoleTaskSupervisionDetailReport) {
@Override
public void onItemClick(RecyclerView.ViewHolder viewHolder) {
RoleTaskSupervisionDetailReportImagesAdapter.RoleTaskSupervisionDetailReportImagesViewHolder roleTaskSupervisionDetailReportImagesViewHolder = (RoleTaskSupervisionDetailReportImagesAdapter.RoleTaskSupervisionDetailReportImagesViewHolder) viewHolder;
Intent intent = new Intent();
intent.putExtra("image_url", roleTaskSupervisionDetailReportImagesViewHolder.image_url);
intent.setClass(RoleTaskSupervisionDetailsActivity.this, CommonDetailBigImgActivity.class);
startActivity(intent);
}
@Override
public void onItemLongClick(RecyclerView.ViewHolder viewHolder) {
}
});
getData();
}
@OnClick(R.id.btn_role_task_supervision_detail_submit)
void roleTaskSubmitOnclick() {
TaskConfirmFormEntity taskConfirmFormEntity = new TaskConfirmFormEntity();
taskConfirmFormEntity.setTaskMemberId(getIntent().getIntExtra("taskMemberId", 0));
taskConfirmFormEntity.setTaskId(getIntent().getIntExtra("taskId", 0));
taskConfirmFormEntity.setTaskType("1");
taskConfirmFormEntity.setOrgId(getIntent().getLongExtra("orgId", 0));
OkHttpUtils
.postString()
.url(InterfaceUrl.CONFIRM_TASK)
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.content(new Gson().toJson(taskConfirmFormEntity))
.build()
.execute(new StringCallback() {
@Override
public void onBefore(Request request, int id) {
super.onBefore(request, id);
progressDialog = new MaterialDialog.Builder(RoleTaskSupervisionDetailsActivity.this)
.title(R.string.submiting_data)
.content(R.string.please_wait)
.progress(true, 0)
.cancelable(false)
.show();
}
@Override
public void onError(Call call, Exception e, int id) {
Log.e("HH", "HH");
}
@Override
public void onResponse(String response, int id) {
JsonReturnCommonSubmitEntity jsonReturnCommonSubmitEntity;
jsonReturnCommonSubmitEntity = JSONUtils.getJsonReturnCommonSubmitEntity(response);
if ("00".equals(jsonReturnCommonSubmitEntity.getResultCd())) {
Snackbar.make(btnRoleTaskSupervisionDetailSubmit, "确认任务成功!", Snackbar.LENGTH_LONG).show();
finish();
} else {
Snackbar.make(btnRoleTaskSupervisionDetailSubmit, jsonReturnCommonSubmitEntity.getResultMsg(), Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onAfter(int id) {
super.onAfter(id);
progressDialog.dismiss();
}
});
}
private void getData() {
TaskDetailFormEntity taskDetailFormEntity = new TaskDetailFormEntity();
taskDetailFormEntity.setTaskId(getIntent().getIntExtra("taskId", 0));
taskDetailFormEntity.setIsMine("2");
taskDetailFormEntity.setTaskMemberId(getIntent().getIntExtra("taskMemberId", 0));
OkHttpUtils
.postString()
.url(InterfaceUrl.GET_ROLE_TASK_DETAIL)
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.content(new Gson().toJson(taskDetailFormEntity))
.build()
.execute(new RoleTaskSupervisionCallback() {
@Override
public void onBefore(Request request, int id) {
super.onBefore(request, id);
progressDialog = new MaterialDialog.Builder(RoleTaskSupervisionDetailsActivity.this)
.title(R.string.trying_to_load)
.content(R.string.please_wait)
.progress(true, 0)
.cancelable(false)
.show();
}
@Override
public void onError(Call call, Exception e, int id) {
Log.e("HH", "HH");
}
@Override
public void onResponse(RoleTaskSupervisionDetailEntity response, int id) {
if (null != response) {
tvRoleTaskSupervisionDetailTitle.setText(response.getRoleTaskBody().getTaskName());
tvRoleTaskSupervisionDetailSender.setText(response.getRoleTaskBody().getSender());
tvRoleTaskSupervisionDetailTime.setText(response.getRoleTaskBody().getTaskStartTime() + "~" + response.getRoleTaskBody().getTaskEndTime());
tvRoleTaskSupervisionDetailContent.setText(response.getRoleTaskBody().getTaskContent());
tvRoleTaskSupervisionDetailReportContent.setText(response.getRoleTaskBody().getTaskResult());
roleTaskSupervisionDetailImagesAdapter.setList(response.getTaskImageList());
roleTaskSupervisionDetailAnnexesAdapter.setList(response.getTaskFileList());
roleTaskSupervisionDetailReportImagesAdapter.setList(response.getTaskResultImageList());
roleTaskSupervisionDetailJoinMemberAdapter.setList(response.getTaskMemberList());
} else {
}
}
@Override
public void onAfter(int id) {
super.onAfter(id);
progressDialog.dismiss();
}
});
}
private abstract class RoleTaskSupervisionCallback extends Callback<RoleTaskSupervisionDetailEntity> {
@Override
public RoleTaskSupervisionDetailEntity parseNetworkResponse(Response response, int id) throws Exception {
JsonReturnCommonEntity jsonReturnCommonEntity;
jsonReturnCommonEntity = JSONUtils.getJsonReturnCommonEntity(response.body().string());
if ("00".equals(jsonReturnCommonEntity.getResultCd())) {
Gson gson = new Gson();
Type type = new TypeToken<RoleTaskSupervisionDetailEntity>() {
}
.getType();
roleTaskSupervisionDetailEntity = gson.fromJson(jsonReturnCommonEntity.getData(), type);
return roleTaskSupervisionDetailEntity;
} else {
return null;
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
|
package com.silrait.bookssearch;
import android.util.Log;
import com.silrait.bookssearch.domain.Book;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class QueryUtils {
public static final String LOG_TAG = QueryUtils.class.getName();
private QueryUtils() {
}
public static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
public static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
public static List<Book> extractBooks(String jsonResponse) {
ArrayList<Book> books = new ArrayList<>();
try {
JSONObject root = new JSONObject(jsonResponse);
JSONArray items = root.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject JSONVolumeInfo = items.getJSONObject(i).getJSONObject("volumeInfo");
books.add(new Book(
items.getJSONObject(i).getString("id"),
JSONVolumeInfo.getString("title"),
JSONVolumeInfo.getJSONArray("authors").getString(0),
JSONVolumeInfo.getJSONObject("imageLinks").getString("thumbnail"),
JSONVolumeInfo.getString("infoLink"),
(JSONVolumeInfo.has("averageRating"))?
Double.parseDouble(JSONVolumeInfo.getString("averageRating")) : 0.0
));
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the book JSON results", e);
}
return books;
}
public static List<Book> queryBooks(String APIurl){
List<Book> list = null;
URL url = QueryUtils.createUrl(APIurl);
try {
list = QueryUtils.extractBooks(QueryUtils.makeHttpRequest(url));
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making HTTP request for the book JSON results.", e);
}
return list;
}
} |
package controller;
import model.*;
import view.*;
/**
* Created by E.E on 10.01.2017.
*/
public class einloggenController implements iControllerInterface
{
private iModelInterface m_model;
private Einloggen einloggFenster;
/**
* Erstellt einen einlogenController.
*/
public einloggenController (iModelInterface model)
{
//einloggFenster = einloggFenster;
m_model = model;
}
/**
* Prüft User und übergibt dem Model.
*/
public void setBenutzer (String user)
{
boolean error = false;
if ( !error )
{
m_model.setUser(user);
}
}
}
|
package org.CarRental.repository;
import org.CarRental.model.AppUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserAppRepository extends JpaRepository<AppUser, Long> {
} |
/**
* @Title: SkuVo.java
* @Package com.cza.service.goods.vo
* @Description: TODO(用一句话描述该文件做什么)
* @author mufeng
* @date 2017年3月1日上午11:28:47
* @version V1.0
*/
package com.cza.service.vo;
import java.math.BigDecimal;
import java.util.List;
/**
* @ClassName: SkuVo
* @Description: TODO(这里用一句话描述这个类的作用)
* @author mufeng
* @date 2017年3月1日上午11:28:47
*
*/
public class SkuVo {
private Long sid;
private BigDecimal price;
private String barcode;
private List<SkuAttrVo>attrs;
private String goodsName;
private String skuPic;
private Long number;//库存
private Long gid;
private Long stock;
/**
* @return gid
*/
public Long getGid() {
return gid;
}
/**
* @param gid the gid to set
*/
public void setGid(Long gid) {
this.gid = gid;
}
/**
* @return skuPic
*/
public String getSkuPic() {
return skuPic;
}
/**
* @param skuPic the skuPic to set
*/
public void setSkuPic(String skuPic) {
this.skuPic = skuPic;
}
/**
* @return stock
*/
public Long getStock() {
return stock;
}
/**
* @param stock the stock to set
*/
public void setStock(Long stock) {
this.stock = stock;
}
/**
* @return goodsName
*/
public String getGoodsName() {
return goodsName;
}
/**
* @param goodsName the goodsName to set
*/
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
/**
* @return sid
*/
public Long getSid() {
return sid;
}
/**
* @param sid the sid to set
*/
public void setSid(Long sid) {
this.sid = sid;
}
/**
* @return price
*/
public BigDecimal getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
/**
* @return barcode
*/
public String getBarcode() {
return barcode;
}
/**
* @param barcode the barcode to set
*/
public void setBarcode(String barcode) {
this.barcode = barcode;
}
/**
* @return attrs
*/
public List<SkuAttrVo> getAttrs() {
return attrs;
}
/**
* @param attrs the attrs to set
*/
public void setAttrs(List<SkuAttrVo> attrs) {
this.attrs = attrs;
}
/**
* @return number
*/
public Long getNumber() {
return number;
}
/**
* @param number the number to set
*/
public void setNumber(Long number) {
this.number = number;
}
/* (非 Javadoc)
*
*
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "SkuVo [sid=" + sid + ", price=" + price + ", barcode=" + barcode + ", attrs=" + attrs + ", goodsName="
+ goodsName + ", skuPic=" + skuPic + ", number=" + number + ", stock=" + stock + "]";
}
}
|
/*
* 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 Servlet;
import DAO.PortfolioDAO;
import Modelo.PortfolioModelo;
import Modelo.ProdutoModelo;
import java.io.IOException;
import java.io.PrintWriter;
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 azm
*/
@WebServlet(name = "ProdutoServlet", urlPatterns = "/ServLet/ProdutoServlet")
public class ProdutoServlet extends HttpServlet
{
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException
{
response.setContentType ("text/html;charset=UTF-8");
// try (PrintWriter out = response.getWriter ())
//// {
// String operacao = request.getParameter ("operacao");
// String redirecionar = request.getParameter ("redirecionar");
//
// if (operacao.equalsIgnoreCase ("cadastrar"))
// {
// String nomeDoProduto = request.getParameter ("txtNomeProduto");
// String imagem = request.getParameter ("txtImagem");
// Double preco = Double.parseDouble (request.getParameter ("txtPreco"));
// String dataCadastro = request.getParameter ("txtData_cadastro");
// int quantidade = Integer.parseInt (request.getParameter ("txtQuantidade"));
// int fornecedor_pk = Integer.parseInt (request.getParameter ("comboFornecdor"));
// String categoria1 = request.getParameter ("comboNivel_1");
// String categoria2 = request.getParameter ("comboNivel_2");
// String categoria3 = request.getParameter ("comboNivel_3");
//
// ProdutoModelo produtoModelo = new ProdutoModelo ();
// PortfolioModelo portfolioModelo = new PortfolioModelo ();
// PortfolioDAO portfolioDAO = new PortfolioDAO ();
//// PortfolioModelo portfolioModelo1 = portfolioDAO.retornarNivel (categoria1);
// produtoModelo.setDesignacao (nomeDoProduto);
// produtoModelo.setPreco (preco);
// produtoModelo.setImagem (imagem);
// produtoModelo.setData_registro (dataCadastro);
// produtoModelo.setQuantidade (quantidade);
// produtoModelo.setFornecedor_fk (fornecedor_pk);
// portfolioModelo.setDesignacao (categoria1);
//
// }
// else if (operacao.equalsIgnoreCase ("eliminar"))
// {
//
// }
// else if (operacao.equalsIgnoreCase ("alterar"))
// {
//
// }
// }
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
processRequest (request, response);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger (ProdutoServlet.class.getName ()).log (Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
processRequest (request, response);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger (ProdutoServlet.class.getName ()).log (Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo ()
{
return "Short description";
}// </editor-fold>
}
|
package com.coreconcepts;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//Jdk 5, Enhanced ForLoop, VarArgs, enum
public class VarArgsDemo {
static int sum(int a,int b,int ... vargs)
{
int s=a+b;
for(int i=0;i<vargs.length;i++)
s=s+vargs[i];
return s;
}
public static void main(String... args) {
System.out.println(sum(10,20,30,40,50,70,80,90));
// String to be scanned to find the pattern.
}
}
|
package vista;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
public class PConfiguracion extends JPanel{
private static final long serialVersionUID = 1L;
private PanelPrincipal pp;
private JTextField precio1,precio2,precio3,precio4;
private JComboBox<String> temporada;
private JSlider velocidad;
private JSpinner nroHab1,nroHab2,nroHab3,nroHab4,tiempoSim;
private JSpinner demanda1,demanda2,demanda3,demanda4;
public PConfiguracion(PanelPrincipal vpp){
pp=vpp;
confi_ini();
crearCont();
confi_fin();
}
private void confi_ini() {
//setLayout(new GridLayout(20,2,5,15));
setLayout(null);
this.setBackground(new Color(0,0,0));
cambiar_tam();
}
private void cambiar_tam(){
int posX=(int)(pp.getWidth()*1.0*4/5);
int posY=100;
int tamX=(int)(pp.getWidth()*(1.0/5)-10);
int tamY=(int)(pp.getHeight()*(1.0*7/8));
setBounds(posX,posY,tamX,tamY);
}
private void crearCont() {
JLabel lab;
lab=new JLabel("Etiquetas");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,102,102));
lab.setBounds(15,15,150,15);
add(lab);
lab=new JLabel("Cambios");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,102,102));
lab.setBounds(170,15,250,15);
add(lab);
lab=new JLabel("Precio Simple");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,50,150,15);
add(lab);
precio1=new JTextField();
precio1.setText("25");
precio1.setFont(new Font("Lucida Calligraphy", 1, 14));
precio1.setForeground(new Color(153,204,0));
precio1.setBounds(190,50,40,18);
add(precio1);
lab=new JLabel("Precio Estandar");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,75,150,15);
add(lab);
precio2=new JTextField();
precio2.setText("50");
precio2.setFont(new Font("Lucida Calligraphy", 1, 14));
precio2.setForeground(new Color(153,204,0));
precio2.setBounds(190,75,40,18);
add(precio2);
lab=new JLabel("Precio Matrimonial");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,100,180,15);
add(lab);
precio3=new JTextField();
precio3.setText("75");
precio3.setFont(new Font("Lucida Calligraphy", 1, 14));
precio3.setForeground(new Color(153,204,0));
precio3.setBounds(190,100,40,18);
add(precio3);
lab=new JLabel("Precio Ejecutiva");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,125,150,15);
add(lab);
precio4=new JTextField();
precio4.setText("100");
precio4.setFont(new Font("Lucida Calligraphy", 1, 14));
precio4.setForeground(new Color(153,204,0));
precio4.setBounds(190,125,40,18);
add(precio4);
lab=new JLabel("Demanda 1");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,150,150,15);
add(lab);
demanda1=new JSpinner();
demanda1.setModel(new SpinnerNumberModel(12, 1,10000,1 ));
demanda1.setBounds(190,150,40,18);
add(demanda1);
lab=new JLabel("Demanda 2");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,175,150,15);
add(lab);
demanda2=new JSpinner();
demanda2.setModel(new SpinnerNumberModel(10, 1,10000,1 ));
demanda2.setBounds(190,175,40,18);
add(demanda2);
lab=new JLabel("Demanda 3");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,200,150,15);
add(lab);
demanda3=new JSpinner();
demanda3.setModel(new SpinnerNumberModel(10, 1,10000,1 ));
demanda3.setBounds(190,200,40,18);
add(demanda3);
lab=new JLabel("Demanda 4");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,225,150,15);
add(lab);
demanda4=new JSpinner();
demanda4.setModel(new SpinnerNumberModel(10, 1,10000,1 ));
demanda4.setBounds(190,225,40,18);
add(demanda4);
lab=new JLabel("Habitacion 1");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,250,150,15);
add(lab);
nroHab1=new JSpinner();
nroHab1.setModel(new SpinnerNumberModel(10, 1,10000,1 ));
nroHab1.setBounds(190,250,40,18);
add(nroHab1);
lab=new JLabel("Habitacion 2");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,275,150,15);
add(lab);
nroHab2=new JSpinner();
nroHab2.setModel(new SpinnerNumberModel(12, 1,10000,1 ));
nroHab2.setBounds(190,275,40,18);
add(nroHab2);
lab=new JLabel("Habitacion 3");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,300,150,15);
add(lab);
nroHab3=new JSpinner();
nroHab3.setModel(new SpinnerNumberModel(15, 1,10000,1 ));
nroHab3.setBounds(190,300,40,18);
add(nroHab3);
lab=new JLabel("Habitacion 4");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,325,150,15);
add(lab);
nroHab4=new JSpinner();
nroHab4.setModel(new SpinnerNumberModel(8, 1,10000,1 ));
nroHab4.setBounds(190,325,40,18);
add(nroHab4);
lab=new JLabel("Temporada");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,350,150,15);
add(lab);
temporada=new JComboBox<String>();
String[] res=new String[]{"Alta","Media","Baja"};
temporada.setModel(new DefaultComboBoxModel<String>(res));
temporada.setBounds(185,350,60,18);
add(temporada);
lab=new JLabel("Tiempo simulacion");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,375,180,15);
add(lab);
tiempoSim=new JSpinner();
tiempoSim.setModel(new SpinnerNumberModel(5,1,500,1));
tiempoSim.setBounds(190,375,40,18);
add(tiempoSim);
lab=new JLabel("Velocidad Simulacion");
lab.setFont(new Font("Lucida Calligraphy", 1, 14));
lab.setForeground(new Color(0,204,204));
lab.setBounds(15,400,200,15);
add(lab);
velocidad=new JSlider(1,100,5);
//velocidad.setOrientation(1);//horizontal
//velocidad.setPaintTicks(true);
velocidad.setPaintLabels(true);
//velocidad.setPaintTrack(true);
velocidad.setOpaque(false);
velocidad.setBounds(10,425,200,15);
add(velocidad);
/*lab=new JLabel("Precios Limpieza");
add(lab);
lab=new JLabel("Precios Comida");
add(lab);*/
}
private void confi_fin() { setVisible(true); }
/*public void paintComponent(Graphics g){
//Dimension tam=pp.getSize();
cambiar_tam();
//ImageIcon imagen = new ImageIcon(getClass().getResource("/imagenes/fondo_03" +".jpg"));
//g.drawImage(imagen.getImage(),0,0,(int)tam.getWidth(),(int)tam.getHeight(),null);
setOpaque(false);
super.paintComponent(g);
}*/
public void habilitar(){
precio1.setEnabled(true);
precio2.setEnabled(true);
precio3.setEnabled(true);
precio4.setEnabled(true);
nroHab1.setEnabled(true);
nroHab2.setEnabled(true);
nroHab3.setEnabled(true);
nroHab4.setEnabled(true);
demanda1.setEnabled(true);
demanda2.setEnabled(true);
demanda3.setEnabled(true);
demanda4.setEnabled(true);
temporada.setEnabled(true);
tiempoSim.setEnabled(true);
}
public void deshabilitar(){
precio1.setEnabled(false);
precio2.setEnabled(false);
precio3.setEnabled(false);
precio4.setEnabled(false);
nroHab1.setEnabled(false);
nroHab2.setEnabled(false);
nroHab3.setEnabled(false);
nroHab4.setEnabled(false);
demanda1.setEnabled(false);
demanda2.setEnabled(false);
demanda3.setEnabled(false);
demanda4.setEnabled(false);
temporada.setEnabled(false);
tiempoSim.setEnabled(false);
}
public int getPrecio1() {
if(precio1.getText().equals("")||precio1.getText().equals(null)||precio1.getText().equals("\n")||precio1.getText().equals(" "))
return 0;
else
return Integer.parseInt(precio1.getText());
}
public void setPrecio1(double precio1) { this.precio1.setText(""+precio1); }
public int getPrecio2() {
if(precio2.getText().equals("")||precio2.getText().equals(null)||precio2.getText().equals("\n")||precio2.getText().equals(" "))
return 0;
else
return Integer.parseInt(precio2.getText());
}
public void setPrecio2(double precio2) { this.precio2.setText(""+precio2);}
public int getPrecio3() {
if(precio3.getText().equals("")||precio3.getText().equals(null)||precio3.getText().equals("\n")||precio3.getText().equals(" "))
return 0;
else
return Integer.parseInt(precio3.getText());
}
public void setPrecio3(double precio3) { this.precio3.setText(""+precio3); }
public int getPrecio4() {
if(precio4.getText().equals("")||precio4.getText().equals(null)||precio4.getText().equals("\n")||precio4.getText().equals(" "))
return 0;
else
return Integer.parseInt(precio4.getText());
}
public void setPrecio4(double precio4) { this.precio4.setText(""+precio4); }
public int getNroHab1() { return (Integer) nroHab1.getValue(); }
public void setNroHab1(int hab1) { this.nroHab1.setValue(""+hab1); }
public int getNroHab2() { return (Integer) nroHab2.getValue(); }
public void setNroHab2(int hab2) { this.nroHab2.setValue(""+hab2); }
public int getNroHab3() { return (Integer) nroHab3.getValue(); }
public void setNroHab3(int hab3) { this.nroHab3.setValue(""+hab3); }
public int getNroHab4() { return (Integer) nroHab4.getValue(); }
public void setNroHab4(int hab4) { this.nroHab4.setValue(""+hab4); }
public int getDemanda1(){ return (Integer)demanda1.getValue(); }
public void setDemanda1(int d1){ this.demanda1.setValue(d1); }
public int getDemanda2(){ return (Integer)demanda2.getValue(); }
public void setDemanda2(int d2){ this.demanda2.setValue(d2); }
public int getDemanda3(){ return (Integer)demanda3.getValue(); }
public void setDemanda3(int d3){ this.demanda3.setValue(d3); }
public int getDemanda4(){ return (Integer)demanda4.getValue(); }
public void setDemanda4(int d4){ this.demanda4.setValue(d4); }
public int getTemporada(){ return (Integer)(temporada.getSelectedIndex())+1;}
public void setTemporada(int temp){ temporada.setSelectedIndex(temp); }
public int getVel() { return velocidad.getValue(); }
public void setVel(int vel){ velocidad.setValue(vel); }
public int getTiempo() { return (Integer)tiempoSim.getValue(); }
public void setTiempo(int t){ tiempoSim.setValue(t); }
} |
package by.twikss.finalwork.ui;
import static by.twikss.finalwork.App.log;
public class MenuList {
private MenuList() {
}
public static void show(){
log.info("Choose menu section");
log.info("Summary:");
log.info("0 - quit");
log.info("1 - add product");
log.info("2 - get product by Id");
log.info("3 - show list products");
log.info("4 - delete product by id");
}
public static void showCategories (){
log.info("Choose category");
log.info("1 - FRUIT");
log.info("2 - VEGETABLE");
}
}
|
package nl.inventid.pressForSuccess.office;
import javax.xml.parsers.ParserConfigurationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;
/**
* This class contacts the data to determine which users are online using https://github.com/inventid/whosonline
*/
public class WhosOnline {
private static final String MACHINES = "machines-online.xml";
private static final String USERS = "users.json";
private static String URL;
private CloseableHttpClient client;
private List<OfficeUser> users;
private boolean canReachRemote = true;
/**
* Determines who is at the office
*/
public WhosOnline() {
try {
client = HttpClientBuilder.create().build();
FileInputStream file = new FileInputStream("./config.txt");
Properties settings = new Properties();
settings.load(file);
file.close();
URL = settings.getProperty("whosonline.url");
if ( settings.getProperty("whosonline.url") == null || settings.getProperty("whosonline.url").isEmpty()) {
throw new IOException();
}
users = readJsonUsers();
}
catch (IOException e) {
}
catch ( IllegalStateException e) {
this.canReachRemote = false;
System.err.println("Could not contact remote whosonline, skipping");
}
}
/**
* Reads the json users in a list
*
* @return List<OfficeUser>
* @throws java.lang.IllegalStateException If the users.json file could not be found
*/
private List<OfficeUser> readJsonUsers() {
ObjectMapper mapper = new ObjectMapper();
List<OfficeUser> users;
try {
CloseableHttpResponse response = client.execute(new HttpGet(URL
+ USERS));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
users = mapper.readValue(response.getEntity().getContent(),
new TypeReference<List<OfficeUser>>() {
});
return users;
}
else {
throw new IOException();
}
}
catch (IOException e) {
throw new IllegalStateException(
"Could not load the users from the JSON file", e);
}
catch (IllegalStateException e) {
throw new IllegalStateException("No correct host was defined",e);
}
}
/**
* Determines who were online when the request was done
*
* @return
*/
public String whosAtTheOffice() {
if ( !this.canReachRemote) {
return "probably some people";
}
try {
CloseableHttpResponse response = client.execute(new HttpGet(URL
+ MACHINES));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String who = parseXml(response.getEntity().getContent());
response.close();
return who;
}
}
catch (IOException | SAXException | ParserConfigurationException e) {
}
return "";
}
private String parseXml(InputStream responseText) throws IOException,
SAXException, ParserConfigurationException {
Document doc = Jsoup.parse(responseText, "UTF-8", "",
Parser.xmlParser());
Elements addresses = doc.getElementsByAttributeValue("addrtype", "mac");
Set<String> macs = Sets.newHashSetWithExpectedSize(addresses.size());
for (Element address : addresses) {
macs.add(address.attr("addr").toUpperCase());
}
List<String> onlineUsers = new ArrayList<>();
for (OfficeUser user : users) {
boolean phone = macs.contains(user.getPhone());
boolean comp = macs.contains(user.getComputer());
boolean tablet = macs.contains(user.getTablet());
if (phone || comp || tablet) {
onlineUsers.add(user.getName());
}
}
System.out.println(onlineUsers);
if (onlineUsers.size() == 0) {
return "";
}
else if (onlineUsers.size() == 1) {
return onlineUsers.get(0);
}
else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < onlineUsers.size() - 1; i++) {
sb.append(onlineUsers.get(i)).append(", ");
}
// Get rid of the unnecessary comma and space
sb.setLength(sb.length() - 2);
sb.append(" & ").append(onlineUsers.get(onlineUsers.size() - 1));
return sb.toString();
}
}
}
|
package br.com.consultemed.model;
import java.io.Serializable;
import javax.persistence.Entity;
@Entity
public class Medico extends Pessoa implements Serializable {
private static final long serialVersionUID = 1L;
private String crm;
public Medico() {
}
public Medico(String crm) {
super();
this.crm = crm;
}
public String getCrm() {
return crm;
}
public void setCrm(String crm) {
this.crm = crm;
}
}
|
package com.ut.healthelink.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import com.ut.healthelink.model.UserActivity;
import com.ut.healthelink.reference.TestCategoryList;
import com.ut.healthelink.reference.USStateList;
import com.ut.healthelink.reference.ProcessCategoryList;
import com.ut.healthelink.service.configurationManager;
import com.ut.healthelink.service.sysAdminManager;
import com.ut.healthelink.service.userManager;
import com.ut.healthelink.model.Macros;
import com.ut.healthelink.model.MoveFilesLog;
import com.ut.healthelink.model.User;
import com.ut.healthelink.model.custom.LogoInfo;
import com.ut.healthelink.model.custom.LookUpTable;
import com.ut.healthelink.model.custom.TableData;
import com.ut.healthelink.model.lutables.lu_Counties;
import com.ut.healthelink.model.lutables.lu_GeneralHealthStatuses;
import com.ut.healthelink.model.lutables.lu_GeneralHealths;
import com.ut.healthelink.model.lutables.lu_Immunizations;
import com.ut.healthelink.model.lutables.lu_Manufacturers;
import com.ut.healthelink.model.lutables.lu_MedicalConditions;
import com.ut.healthelink.model.lutables.lu_Medications;
import com.ut.healthelink.model.lutables.lu_Procedures;
import com.ut.healthelink.model.lutables.lu_ProcessStatus;
import com.ut.healthelink.model.lutables.lu_Tests;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
@Controller
@RequestMapping("/administrator/sysadmin")
public class adminSysAdminController {
@Autowired
private sysAdminManager sysAdminManager;
@Autowired
private userManager usermanager;
@Autowired
private configurationManager configurationmanager;
@Autowired
private ServletContext servletContext;
/**
* The private maxResults variable will hold the number of results to show per list page.
*/
private static int maxResults = 20;
private static int nonPagingMax = 999999;
private static int startPage = 1;
/**
* This shows a dashboard with info for sysadmin components.
* *
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView dashboard(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/dashboard");
/**
* set totals*
*/
int totalLookUpTables = sysAdminManager.findTotalLookUpTable();
Long totalMacroRows = sysAdminManager.findTotalMacroRows();
Long totalHL7Entries = sysAdminManager.findtotalHL7Entries();
Long totalUsers = sysAdminManager.findTotalUsers();
Integer filePaths = sysAdminManager.getMoveFilesLog(1).size();
mav.addObject("totalLookUpTables", totalLookUpTables);
mav.addObject("totalMacroRows", totalMacroRows);
mav.addObject("totalHL7Entries", totalHL7Entries);
mav.addObject("totalUsers", totalUsers);
mav.addObject("filePaths", filePaths);
return mav;
}
/**
* MACROS
* *
*/
@RequestMapping(value = "/macros", method = RequestMethod.GET)
public ModelAndView listMacros() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/macros");
//Return a list of available macros
List<Macros> macroList = sysAdminManager.getMarcoList("%");
mav.addObject("macroList", macroList);
return mav;
}
@RequestMapping(value = "/macros/delete", method = RequestMethod.GET)
public ModelAndView deleteMacro(@RequestParam(value = "i", required = true) int macroId,
RedirectAttributes redirectAttr) throws Exception {
boolean suceeded = sysAdminManager.deleteMacro(macroId);
String returnMessage = "deleted";
if (!suceeded) {
returnMessage = "notDeleted";
}
//This variable will be used to display the message on the details form
redirectAttr.addFlashAttribute("savedStatus", returnMessage);
ModelAndView mav = new ModelAndView(new RedirectView("../macros?msg=" + returnMessage));
return mav;
}
/**
* The '/{urlId}/data.create' GET request will be used to create a new data for selected table
*
*/
@RequestMapping(value = "/macros/create", method = RequestMethod.GET)
public ModelAndView newMacroForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/macro/details");
//create a macro
Macros macro = new Macros();
macro.setId(0);
mav.addObject("macroDetails", macro);
mav.addObject("btnValue", "Create");
return mav;
}
@RequestMapping(value = "/macros/create", method = RequestMethod.POST)
public ModelAndView createMacro(
@Valid @ModelAttribute(value = "macroDetails") Macros macroDetails,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/macro/details");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("macroDetails", macroDetails);
mav.addObject("btnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createMacro(macroDetails);
mav.addObject("success", "macroCreated");
mav.addObject("btnValue", "Update");
return mav;
}
/**
* The '/macros/view' GET request will be used to create a new data for selected table
*
*/
@RequestMapping(value = "/macros/view", method = RequestMethod.GET)
public ModelAndView viewMacroDetails(@RequestParam(value = "i", required = false) Integer i) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/macro/details");
//get macro info here
Macros macroDetails = configurationmanager.getMacroById(i);
mav.addObject("macroDetails", macroDetails);
mav.addObject("btnValue", "Update");
return mav;
}
/**
* UPDATE macros
* *
*/
@RequestMapping(value = "/macros/update", method = RequestMethod.POST)
public ModelAndView updateMacro(
@Valid @ModelAttribute(value = "macroDetails") Macros macroDetails,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/macro/details");
if (result.hasErrors()) {
mav.addObject("macroDetails", macroDetails);
mav.addObject("btnValue", "Update");
return mav;
}
//get macro info here
boolean updated = sysAdminManager.updateMacro(macroDetails);
if (updated) {
mav.addObject("success", "macroUpdated");
} else {
mav.addObject("success", "Error!");
}
mav.addObject("macroDetails", macroDetails);
mav.addObject("btnValue", "Update");
return mav;
}
/**
* END MACROS
* *
*/
/**
* The '/list' GET request will serve up the existing list of lu_ tables in the system
*
* @param page The page parameter will hold the page to view when pagination is built.
* @return The list of look up tables
*
* @Objects (1) An object containing all the found look up tables
*
* @throws Exception
*/
@RequestMapping(value = "/data", method = RequestMethod.GET)
public ModelAndView listLookUpTables() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/tableList");
/**
* we query list of tables for display
*
*/
List<LookUpTable> tableList = sysAdminManager.getTableList("%");
mav.addObject("tableList", tableList);
return mav;
}
/**
* The '/data/std/{urlId}' GET request will serve up the data for a standardize look up table
*
* @param page The page parameter will hold the page to view when pagination is built.
* @param urlId The urlId for the look up table - can't use dynamic table names in Hibernate, and don't want to worry about sql injection and plain view of table name, will do a look up.
* @param searchTerm if a user want to look for a particular term, will be useful when we have a lot of medical services
*
* @return list of TableData
*
* @Objects (1) An object containing all the found look up tables
*
* @throws Exception
*/
@RequestMapping(value = "/data/std/{urlId}", method = RequestMethod.GET)
public ModelAndView listTableData(@PathVariable String urlId) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std");
/**
* we query data for look up table, this view returns all data from table, hence the search term will be %
*
*/
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
List<TableData> dataList = sysAdminManager.getDataList(tableInfo.getUtTableName(), "%");
mav.addObject("dataList", dataList);
mav.addObject("tableInfo", tableInfo);
mav.addObject("goToURL", tableInfo.getUrlId());
mav.addObject("urlIdInfo", tableInfo.getUrlId());
return mav;
}
/**
* The '/data/std/{urlId}/delete?i=' Post request will serve up the date for a look up table
*
* @param page The page parameter will hold the page to view when pagination is built.
* @param urlId The urlId for the look up table - can't use dynamic table names in Hibernate, and don't want to worry about sql injection and plain view of table name, will do a look up.
* @param i if a user want to look for a particular term, will be useful when we have a lot of medical services
*
* @return list of TableData
*
* @Objects (1) An object containing all the found look up tables
*
* @throws Exception
*/
@RequestMapping(value = "/data/std/{urlId}/delete", method = RequestMethod.GET)
public ModelAndView deleteTableData(@RequestParam(value = "i", required = true) int dataId,
@PathVariable String urlId, RedirectAttributes redirectAttr) throws Exception {
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
boolean suceeded = sysAdminManager.deleteDataItem(tableInfo.getUtTableName(), dataId);
String returnMessage = "deleted";
if (!suceeded) {
returnMessage = "notDeleted";
}
//This variable will be used to display the message on the details form
redirectAttr.addFlashAttribute("savedStatus", returnMessage);
ModelAndView mav = new ModelAndView(new RedirectView("../" + urlId));
return mav;
}
/**
* The '/{urlId}/data.create' GET request will be used to create a new data for selected table
*
*/
@RequestMapping(value = "/data/std/{urlId}/create", method = RequestMethod.GET)
public ModelAndView newTableDataForm(@PathVariable String urlId) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
//create a table data
TableData tableData = new TableData();
tableData.setId(0);
tableData.setUrlId(urlId);
mav.addObject("stdForm", "stdForm");
mav.addObject("tableDataDetails", tableData);
mav.addObject("tableInfo", tableInfo);
mav.addObject("objectType", "tableData");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "Create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
/**
* The '/{urlId}/create' POST request will handle submitting the new provider.
*
* @param tableDataForm The object containing the tableData form fields
* @param result The validation result
* @param redirectAttr The variable that will hold values that can be read after the redirect
* @Objects (1) The object containing all the information for the new data item (2) We will extract table from web address
* @throws Exception
*/
@RequestMapping(value = "/data/std/create", method = RequestMethod.POST)
public ModelAndView createTableData(
@Valid @ModelAttribute(value = "tableDataDetails") TableData tableData,
BindingResult result) throws Exception {
LookUpTable tableInfo = sysAdminManager.getTableInfo(tableData.getUrlId());
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "tableData");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("stdForm", "stdForm");
mav.addObject("tableInfo", tableInfo);
mav.addObject("btnValue", "Create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createTableDataHibernate(tableData, tableInfo.getUtTableName());
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "Update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* The '/data/std/{urlId}/tableData?i=' GET request will be used to create a new data for selected table
*
*/
@RequestMapping(value = "/data/std/{urlId}/tableData", method = RequestMethod.GET)
public ModelAndView viewTableData(@PathVariable String urlId,
@RequestParam(value = "i", required = false) Integer i) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
TableData tableData = sysAdminManager.getTableData(i, tableInfo.getUtTableName());
tableData.setUrlId(urlId);
mav.addObject("tableDataDetails", tableData);
mav.addObject("tableInfo", tableInfo);
mav.addObject("objectType", "tableData");
mav.addObject("stdForm", "stdForm");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "Update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* The '/data/std/update' POST request will be used to update a look up data item
*
*/
@RequestMapping(value = "/data/std/update", method = RequestMethod.POST)
public ModelAndView updateTableData(
@Valid @ModelAttribute(value = "tableDataDetails") TableData tableData,
BindingResult result)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "tableData");
mav.addObject("formId", "tabledataform");
mav.addObject("submitBtnValue", "Update");
mav.addObject("btnValue", "Update");
LookUpTable tableInfo = sysAdminManager.getTableInfo(tableData.getUrlId());
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("tableInfo", tableInfo);
mav.addObject("stdForm", "stdForm");
return mav;
}
// now we update
boolean updated = sysAdminManager.updateTableData(tableData, tableInfo.getUtTableName());
// This variable will be used to display the message on the details
if (updated) {
mav.addObject("success", "dataUpdated");
} else {
mav.addObject("success", "- There is an error.");
}
return mav;
}
/**
* here we have the views for the look up tables that do not have the standard 7 columns, these have models in UT
*
*/
@RequestMapping(value = "/data/nstd/{urlId}", method = RequestMethod.GET)
public ModelAndView listTableDataNStd(@PathVariable String urlId) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std");
/**
* we query data for look up table, this view returns all data from table, hence the search term will be %
*
*/
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
List<TableData> dataList = sysAdminManager.getDataList(tableInfo.getUtTableName(), "%");
mav.addObject("dataList", dataList);
mav.addObject("tableInfo", tableInfo);
mav.addObject("goToURL", tableInfo.getUtTableName());
mav.addObject("urlIdInfo", tableInfo.getUrlId());
return mav;
}
@RequestMapping(value = "/data/nstd/{urlId}/delete", method = RequestMethod.GET)
public ModelAndView deleteCountyData(@RequestParam(value = "i", required = true) int dataId,
@PathVariable String urlId, RedirectAttributes redirectAttr) throws Exception {
LookUpTable tableInfo = sysAdminManager.getTableInfo(urlId);
boolean suceeded = sysAdminManager.deleteDataItem(tableInfo.getUtTableName(), dataId);
String returnMessage = "deleted";
if (!suceeded) {
returnMessage = "notDeleted";
}
//This variable will be used to display the message on the details form
redirectAttr.addFlashAttribute("savedStatus", returnMessage);
ModelAndView mav = new ModelAndView(new RedirectView("../" + urlId));
return mav;
}
@RequestMapping(value = "/data/nstd/lu_Counties/create", method = RequestMethod.GET)
public ModelAndView newCountyForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//Get a list of states
USStateList stateList = new USStateList();
//create a lu_Counties
lu_Counties luc = new lu_Counties();
luc.setId(0);
mav.addObject("tableDataDetails", luc);
mav.addObject("objectType", "lu_Counties");
mav.addObject("formId", "tabledataform");
mav.addObject("stateList", stateList.getStates());
mav.addObject("btnValue", "lu_counties/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_counties/create", method = RequestMethod.POST)
public ModelAndView createCounties(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Counties luc,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Counties");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_counties/create");
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createCounty(luc);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_counties/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* view a county's data data/nstd/lu_Counties/tableData*
*/
@RequestMapping(value = "/data/nstd/lu_Counties/tableData", method = RequestMethod.GET)
public ModelAndView viewCountyData(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
USStateList stateList = new USStateList();
lu_Counties luc = sysAdminManager.getCountyById(i);
mav.addObject("tableDataDetails", luc);
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("objectType", "lu_Counties");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_counties/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_counties/update", method = RequestMethod.POST)
public ModelAndView updateCounty(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Counties luc,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Counties");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_counties/update");
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateCounty(luc);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_counties/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* general health *
*/
@RequestMapping(value = "/data/nstd/lu_GeneralHealths/create", method = RequestMethod.GET)
public ModelAndView newGeneralHealthForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_GeneralHealths lu = new lu_GeneralHealths();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_GeneralHealths");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_generalhealths/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_generalhealths/create", method = RequestMethod.POST)
public ModelAndView createGeneralHealth(
@Valid @ModelAttribute(value = "tableDataDetails") lu_GeneralHealths lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_GeneralHealths");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_generalhealths/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createGeneralHealth(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_generalhealths/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_GeneralHealths/tableData", method = RequestMethod.GET)
public ModelAndView viewGeneralHealth(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_GeneralHealths lu = sysAdminManager.getGeneralHealthById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_GeneralHealths");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_generalhealths/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_generalhealths/update", method = RequestMethod.POST)
public ModelAndView updateGeneralHealth(
@Valid @ModelAttribute(value = "tableDataDetails") lu_GeneralHealths lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_GeneralHealths");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_generalhealths/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateGeneralHealth(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_generalhealths/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of general health *
*/
/**
* start of general health statuses *
*/
// this method creates the form for the object
@RequestMapping(value = "/data/nstd/lu_GeneralHealthStatuses/create", method = RequestMethod.GET)
public ModelAndView newGeneralHealthStatusForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_GeneralHealthStatuses lu = new lu_GeneralHealthStatuses();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_GeneralHealthStatuses");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_GeneralHealthStatuses/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//this method saves the object
@RequestMapping(value = "/data/nstd/lu_generalhealthstatuses/create", method = RequestMethod.POST)
public ModelAndView createGeneralHealthStatuses(
@Valid @ModelAttribute(value = "tableDataDetails") lu_GeneralHealthStatuses lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_GeneralHealthStatuses");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_GeneralHealthStatuses/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createGeneralHealthStatus(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_GeneralHealthStatuses/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
// this method queries and displays the object data
@RequestMapping(value = "/data/nstd/lu_GeneralHealthStatuses/tableData", method = RequestMethod.GET)
public ModelAndView viewGeneralHealthStatus(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_GeneralHealthStatuses lu = sysAdminManager.getGeneralHealthStatusById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_GeneralHealthStatuses");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_GeneralHealthStatuses/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//this method updates the object
@RequestMapping(value = "/data/nstd/lu_generalhealthstatuses/update", method = RequestMethod.POST)
public ModelAndView updateGeneralHealthStatus(
@Valid @ModelAttribute(value = "tableDataDetails") lu_GeneralHealthStatuses lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_GeneralHealthStatuses");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_GeneralHealthStatuses/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateGeneralHealthStatus(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_GeneralHealthStatuses/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of general health status *
*/
/**
* start of Immunizations *
*/
// this method creates the form for the object
@RequestMapping(value = "/data/nstd/lu_Immunizations/create", method = RequestMethod.GET)
public ModelAndView newImmunizationsForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_Immunizations lu = new lu_Immunizations();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Immunizations");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Immunizations/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//this method saves the object
@RequestMapping(value = "/data/nstd/lu_immunizations/create", method = RequestMethod.POST)
public ModelAndView createImmunization(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Immunizations lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Immunizations");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Immunizations/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createImmunization(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_Immunizations/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
// this method queries and displays the object data
@RequestMapping(value = "/data/nstd/lu_Immunizations/tableData", method = RequestMethod.GET)
public ModelAndView viewImmunization(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_Immunizations lu = sysAdminManager.getImmunizationById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Immunizations");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Immunizations/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//this method updates the object
@RequestMapping(value = "/data/nstd/lu_immunizations/update", method = RequestMethod.POST)
public ModelAndView updateImmunization(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Immunizations lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Immunizations");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Immunizations/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateImmunization(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_immunizations/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of Immunizations *
*/
/**
* start of Manufacturers *
*/
// this method creates the form for the object
@RequestMapping(value = "/data/nstd/lu_Manufacturers/create", method = RequestMethod.GET)
public ModelAndView newManufacturerForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_Manufacturers lu = new lu_Manufacturers();
lu.setId(0);
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Manufacturers");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Manufacturers/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//this method saves the object
@RequestMapping(value = "/data/nstd/lu_manufacturers/create", method = RequestMethod.POST)
public ModelAndView createManufacturer(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Manufacturers lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Manufacturers");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("btnValue", "lu_Manufacturers/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createManufacturer(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_Manufacturers/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
// this method queries and displays the object data
@RequestMapping(value = "/data/nstd/lu_Manufacturers/tableData", method = RequestMethod.GET)
public ModelAndView viewManufacturer(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_Manufacturers lu = sysAdminManager.getManufacturerById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Manufacturers");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Manufacturers/update");
mav.addObject("submitBtnValue", "Update");
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
return mav;
}
//this method updates the object
@RequestMapping(value = "/data/nstd/lu_manufacturers/update", method = RequestMethod.POST)
public ModelAndView updateManufacturer(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Manufacturers lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Manufacturers");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
//Get a list of states
USStateList stateList = new USStateList();
//Get the object that will hold the states
mav.addObject("stateList", stateList.getStates());
mav.addObject("btnValue", "lu_Manufacturers/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateManufacturer(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_Manufacturers/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of Manufacturers *
*/
/**
* medical conditions *
*/
@RequestMapping(value = "/data/nstd/lu_MedicalConditions/create", method = RequestMethod.GET)
public ModelAndView newMedicalConditionForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_MedicalConditions lu = new lu_MedicalConditions();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_MedicalConditions");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_MedicalConditions/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_medicalconditions/create", method = RequestMethod.POST)
public ModelAndView createMedicalConditon(
@Valid @ModelAttribute(value = "tableDataDetails") lu_MedicalConditions lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_MedicalConditions");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_MedicalConditions/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createMedicalCondition(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_MedicalConditions/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_MedicalConditions/tableData", method = RequestMethod.GET)
public ModelAndView viewMedicalCondition(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_MedicalConditions lu = sysAdminManager.getMedicalConditionById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_MedicalConditions");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_MedicalConditions/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_medicalconditions/update", method = RequestMethod.POST)
public ModelAndView updateMedicalConditon(
@Valid @ModelAttribute(value = "tableDataDetails") lu_MedicalConditions lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_MedicalConditions");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_MedicalConditions/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateMedicalCondition(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_MedicalConditions/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of medical conditions *
*/
/**
* start of medication *
*/
@RequestMapping(value = "/data/nstd/lu_Medications/create", method = RequestMethod.GET)
public ModelAndView newMedicationForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_Medications lu = new lu_Medications();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Medications");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Medications/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_medications/create", method = RequestMethod.POST)
public ModelAndView createMedication(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Medications lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Medications");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Medications/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createMedication(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_Medications/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_Medications/tableData", method = RequestMethod.GET)
public ModelAndView viewMedication(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_Medications lu = sysAdminManager.getMedicationById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Medications");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Medications/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_medications/update", method = RequestMethod.POST)
public ModelAndView updateMedication(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Medications lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Medications");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Medications/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateMedication(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_Medications/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* end of medication *
*/
/**
* Procedures *
*/
@RequestMapping(value = "/data/nstd/lu_Procedures/create", method = RequestMethod.GET)
public ModelAndView newProcedureForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_Procedures lu = new lu_Procedures();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Procedures");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Procedures/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_procedures/create", method = RequestMethod.POST)
public ModelAndView createProcedure(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Procedures lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Procedures");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Procedures/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createProcedure(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_Procedures/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_Procedures/tableData", method = RequestMethod.GET)
public ModelAndView viewProcedure(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_Procedures lu = sysAdminManager.getProcedureById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Procedures");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Procedures/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_procedures/update", method = RequestMethod.POST)
public ModelAndView updateProcedure(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Procedures lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_Procedures");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Procedures/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateProcedure(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_Procedures/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* End of procedures*
*/
/**
* Start of Tests *
*/
@RequestMapping(value = "/data/nstd/lu_Tests/create", method = RequestMethod.GET)
public ModelAndView newTestForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//Get a list of process status categories
TestCategoryList categoryList = new TestCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
//create the object
lu_Tests lu = new lu_Tests();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Tests");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Tests/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_tests/create", method = RequestMethod.POST)
public ModelAndView createTest(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Tests lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//Get a list of process status categories
TestCategoryList categoryList = new TestCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
mav.addObject("objectType", "lu_Tests");
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Tests/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createTest(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_Tests/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_Tests/tableData", method = RequestMethod.GET)
public ModelAndView viewTest(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//Get a list of process status categories
TestCategoryList categoryList = new TestCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
lu_Tests lu = sysAdminManager.getTestById(i);
mav.addObject("tableDataDetails", lu);
mav.addObject("objectType", "lu_Tests");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_Tests/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_tests/update", method = RequestMethod.POST)
public ModelAndView updateTest(
@Valid @ModelAttribute(value = "tableDataDetails") lu_Tests lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//Get a list of process status categories
TestCategoryList categoryList = new TestCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
mav.addObject("objectType", "lu_Tests");
mav.addObject("formId", "tabledataform");
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_Tests/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateTest(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_Tests/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* End of Tests*
*/
/**
* Start of ProcessStatus *
*/
@RequestMapping(value = "/data/nstd/lu_ProcessStatus/create", method = RequestMethod.GET)
public ModelAndView newProcessStatusForm() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
//create the object
lu_ProcessStatus lu = new lu_ProcessStatus();
lu.setId(0);
mav.addObject("tableDataDetails", lu);
//Get a list of process status categories
ProcessCategoryList categoryList = new ProcessCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
mav.addObject("objectType", "lu_ProcessStatus");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_ProcessStatus/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_processstatus/create", method = RequestMethod.POST)
public ModelAndView createProcessStatus(
@Valid @ModelAttribute(value = "tableDataDetails") lu_ProcessStatus lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_ProcessStatus");
//Get a list of process status categories
ProcessCategoryList categoryList = new ProcessCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
mav.addObject("formId", "tabledataform");
// check for error
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_ProcessStatus/create");
mav.addObject("submitBtnValue", "Create");
return mav;
}
//now we save
sysAdminManager.createProcessStatus(lu);
mav.addObject("success", "dataCreated");
mav.addObject("btnValue", "lu_ProcessStatus/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_ProcessStatus/tableData", method = RequestMethod.GET)
public ModelAndView viewProcessStatus(@RequestParam(value = "i", required = false) Integer i)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
lu_ProcessStatus lu = sysAdminManager.getProcessStatusById(i);
mav.addObject("tableDataDetails", lu);
ProcessCategoryList categoryList = new ProcessCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
mav.addObject("objectType", "lu_ProcessStatus");
mav.addObject("formId", "tabledataform");
mav.addObject("btnValue", "lu_ProcessStatus/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
@RequestMapping(value = "/data/nstd/lu_processstatus/update", method = RequestMethod.POST)
public ModelAndView updateProcessStatus(
@Valid @ModelAttribute(value = "tableDataDetails") lu_ProcessStatus lu,
BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/data/std/details");
mav.addObject("objectType", "lu_ProcessStatus");
mav.addObject("formId", "tabledataform");
ProcessCategoryList categoryList = new ProcessCategoryList();
mav.addObject("categoryList", categoryList.getCategories());
/**
* check for error *
*/
if (result.hasErrors()) {
mav.addObject("btnValue", "lu_ProcessStatus/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
//now we save
sysAdminManager.updateProcessStatus(lu);
mav.addObject("success", "dataUpdated");
mav.addObject("btnValue", "lu_ProcessStatus/update");
mav.addObject("submitBtnValue", "Update");
return mav;
}
/**
* End of ProcessStatus*
*/
/**
* Logos
*/
@RequestMapping(value = "/logos", method = RequestMethod.GET)
public @ResponseBody
ModelAndView updateLogosForm(HttpServletRequest request) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/logos");
LogoInfo logoDetails = sysAdminManager.getLogoInfo();
/**
* we had a logo from before *
*/
if (logoDetails.getBackEndLogoName().indexOf("backEndLogo") == 0) {
sysAdminManager.copyBELogo(request, logoDetails);
}
if (logoDetails.getFrontEndLogoName().indexOf("frontEndLogo") == 0) {
sysAdminManager.copyFELogo(request, logoDetails);
}
mav.addObject("btnValue", "Update");
mav.addObject("logoDetails", logoDetails);
return mav;
}
@RequestMapping(value = "/logos", method = RequestMethod.POST)
public ModelAndView updateLogos(@ModelAttribute(value = "logoDetails") LogoInfo logoDetails,
RedirectAttributes redirectAttr) throws Exception {
sysAdminManager.updateLogoInfo(logoDetails);
ModelAndView mav = new ModelAndView(new RedirectView("logos?msg=updated"));
redirectAttr.addFlashAttribute("savedStatus", "updated");
return mav;
}
/** modify admin profile **/
@RequestMapping(value = "/adminInfo", method = RequestMethod.GET)
public @ResponseBody
ModelAndView displayAdminInfo(HttpServletRequest request, Authentication authentication) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/adminInfo/profile");
User userDetails = usermanager.getUserByUserName(authentication.getName());
mav.addObject("btnValue", "Update");
mav.addObject("userdetails", userDetails);
return mav;
}
@RequestMapping(value = "/adminInfo", method = RequestMethod.POST)
public @ResponseBody
ModelAndView updateAdminInfo(HttpServletRequest request, @ModelAttribute(value = "userdetails") User userdetails,
Authentication authentication, BindingResult result) throws Exception {
ModelAndView mav = new ModelAndView();
User user = usermanager.getUserByUserName(authentication.getName());
mav.setViewName("/administrator/sysadmin/adminInfo/profile");
/** we verify existing password **/
boolean okToChange = false;
try {
okToChange = usermanager.authenticate(request.getParameter("existingPassword"), user.getEncryptedPw(), user.getRandomSalt());
} catch(Exception ex) {
okToChange = false;
}
if (okToChange) {
/** we update user **/
user.setFirstName(userdetails.getFirstName());
user.setLastName(userdetails.getLastName());
user.setEmail(userdetails.getEmail());
if (!request.getParameter("newPassword").trim().equalsIgnoreCase("")) {
user.setRandomSalt(usermanager.generateSalt());
user.setEncryptedPw(usermanager.getEncryptedPassword(request.getParameter("newPassword"), user.getRandomSalt()));
}
try {
usermanager.updateUserOnly(user);
} catch (Exception ex) {
ex.printStackTrace();
okToChange = false;
}
}
if (!okToChange) {
mav.addObject("failed", "Please check your existing password. Profile is not updated.");
mav.addObject("btnValue", "Update");
} else {
mav.addObject("userdetails", user);
mav.addObject("success", "Profile is updated");
mav.addObject("btnValue", "Update");
}
return mav;
}
/** login as portion **/
@RequestMapping(value = "/loginAs", method = RequestMethod.GET)
public ModelAndView loginAs() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/loginAs");
//get all active users
List <User> usersList = usermanager.getUsersByStatuRolesAndOrg(true, Arrays.asList(1), Arrays.asList(1), false);
mav.addObject("usersList", usersList);
return mav;
}
@RequestMapping(value = "/loginAs", method = RequestMethod.POST)
public @ResponseBody
ModelAndView checkAdminPW(HttpServletRequest request, Authentication authentication) throws Exception {
ModelAndView mav = new ModelAndView();
User user = usermanager.getUserByUserName(authentication.getName());
mav.setViewName("/administrator/sysadmin/loginAs");
boolean okToLoginAs = false;
/** we verify existing password **/
if (user.getRoleId() == 1 || user.getRoleId() == 4) {
try {
okToLoginAs = usermanager.authenticate(request.getParameter("password"), user.getEncryptedPw(), user.getRandomSalt());
} catch(Exception ex) {
okToLoginAs = false;
}
}
if (!okToLoginAs) {
mav.addObject("msg", "Your credentials are invalid.");
} else {
mav.addObject("msg", "pwmatched");
}
return mav;
}
@RequestMapping(value = "/getLog", method = {RequestMethod.GET})
public void getLog(HttpSession session, HttpServletResponse response, Authentication authentication) throws Exception {
User userInfo = usermanager.getUserByUserName(authentication.getName());
//log user activity
UserActivity ua = new UserActivity();
ua.setUserId(userInfo.getId());
ua.setAccessMethod("GET");
ua.setPageAccess("/getLog");
ua.setActivity("Download Tomcat Log");
usermanager.insertUserLog(ua);
File logFileDir = new File(System.getProperty("catalina.home"), "logs");
File logFile = new File(logFileDir, "catalina.out");
// get your file as InputStream
InputStream is = new FileInputStream(logFile);
String mimeType = "application/octet-stream";
response.setContentType(mimeType);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition", "attachment;filename=catalina.out");
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
is.close();
}
@RequestMapping(value = "/moveFilePaths", method = RequestMethod.GET)
public ModelAndView moveFilePaths(HttpServletRequest request, HttpServletResponse response,
HttpSession session, RedirectAttributes redirectAttr) throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("/administrator/sysadmin/moveFilePaths");
//we get list of programs
List<MoveFilesLog> pathList = sysAdminManager.getMoveFilesLog(1);
mav.addObject("pathList", pathList);
return mav;
}
@RequestMapping(value = "/moveFilePaths", method = RequestMethod.POST)
@ResponseBody
public String associateEntity(@RequestParam(value = "pathId", required = true) Integer pathId) throws Exception {
MoveFilesLog moveFilesLog = new MoveFilesLog();
moveFilesLog.setId(pathId);
sysAdminManager.deleteMoveFilesLog(moveFilesLog);
return "deleted";
}
}
|
/*
* UnionAlignmentPlugin.java
*
* Created on December 22, 2006, 5:02 PM
*
*/
package net.maizegenetics.analysis.data;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.dna.snp.CombineGenotypeTable;
import net.maizegenetics.trait.Phenotype;
import net.maizegenetics.trait.MarkerPhenotype;
import net.maizegenetics.trait.CombinePhenotype;
import java.awt.Frame;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.plugindef.PluginEvent;
import javax.swing.*;
import java.io.StringWriter;
import java.net.URL;
import java.util.List;
/**
*
* @author Ed Buckler
*/
public class UnionAlignmentPlugin extends AbstractPlugin {
/**
* Creates a new instance of UnionAlignmentPlugin
*/
public UnionAlignmentPlugin(Frame parentFrame, boolean isInteractive) {
super(parentFrame, isInteractive);
}
public DataSet performFunction(DataSet input) {
Datum joinedDatum = processData(input, true);
if (joinedDatum == null) {
return null;
}
DataSet output = new DataSet(joinedDatum, this);
//I am setting the firing class as the metadata - so that the control panel know where the event is coming from
fireDataSetReturned(new PluginEvent(output, UnionAlignmentPlugin.class));
return output;
}
protected Datum processData(DataSet input, boolean isUnion) {
try {
Datum outDatum = null;
String userMessage = "This action requires multiple items be simultaneously selected from the data tree "
+ "(Ctrl + mouse click). Please select genotype, trait, and population structure data to isUnion "
+ "from the data tree.";
GenotypeTable aa = null;
Phenotype ca = null;
List<Datum> aaVector = input.getDataOfType(GenotypeTable.class);
List<Datum> caVector = input.getDataOfType(Phenotype.class);
if ((aaVector.size() + caVector.size()) < 2) {
JOptionPane.showMessageDialog(getParentFrame(), userMessage);
return null;
}
StringWriter sw = new StringWriter();
Object result = null;
if (aaVector.size() == 1) {
aa = (GenotypeTable) aaVector.get(0).getData();
} else if (aaVector.size() > 1) {
GenotypeTable[] temp = new GenotypeTable[aaVector.size()];
for (int i = 0; i < aaVector.size(); i++) {
temp[i] = (GenotypeTable) aaVector.get(i).getData();
}
aa = CombineGenotypeTable.getInstance(temp, isUnion);
result = aa;
}
if (caVector.size() > 0) {
ca = (Phenotype) caVector.get(0).getData();
}
for (int i = 1; i < caVector.size(); i++) {
Phenotype ta = (Phenotype) caVector.get(i).getData();
ca = CombinePhenotype.getInstance(ca, ta, isUnion);
result = ca;
}
if ((ca != null) && (aa != null)) {
//then make a concatenated alignment
MarkerPhenotype aac = MarkerPhenotype.getInstance(aa, ca, isUnion);
result = aac;
}
String theName = this.getConcatenatedName(input);
if (isUnion) {
sw.append("Union Join\n");
} else {
sw.append("Intersect Join\n");
}
String theComment = sw.toString();
outDatum = new Datum(theName, result, theComment);
return outDatum;
} finally {
fireProgress(100);
}
}
protected String getConcatenatedName(DataSet theTDS) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < theTDS.getSize(); i++) {
sb.append(theTDS.getData(i).getName());
if (i + 1 != theTDS.getSize()) {
sb.append(" + ");
}
}
return sb.toString();
}
/**
* Icon for this plugin to be used in buttons, etc.
*
* @return ImageIcon
*/
@Override
public ImageIcon getIcon() {
URL imageURL = UnionAlignmentPlugin.class.getResource("/net/maizegenetics/analysis/images/UnionJoin.gif");
if (imageURL == null) {
return null;
} else {
return new ImageIcon(imageURL);
}
}
/**
* Button name for this plugin to be used in buttons, etc.
*
* @return String
*/
@Override
public String getButtonName() {
return "Union Join";
}
/**
* Tool Tip Text for this plugin
*
* @return String
*/
@Override
public String getToolTipText() {
return "Join Datasets by Union of Taxa";
}
}
|
package interfase;
import task.*;
import utils.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Create window for remove task from task list.
*/
public class RemoveTask extends JFrame {
private static final long serialVersionUID = 1L;
private static Task task;
public static TaskList taskList;
public Date date = null;
public String diskr = "";
public String contact = "";
boolean activ = false;
public String id = "";
/**
* @param tl list of tasks.
* @param taskId id task you want to delete.
*/
public RemoveTask(TaskList tl,String taskId){
taskList = tl;
id = taskId;
task = taskList.getById(id);
setTitle("Edit select task");
setSize(382, 227);
MyPanelText panel = new MyPanelText(task.getDescription());
Container pane = getContentPane();
pane.add(panel);
MyPanelButton panel1 = new MyPanelButton();
Container pane1 = getContentPane();
pane1.add(panel1, BorderLayout.SOUTH);
setVisible(true);
}
private class MyPanelText extends JPanel {
private static final long serialVersionUID = 1L;
public String string;
public MyPanelText(String str) {
string = str;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(string, 55, 55);
}
}
private class MyPanelButton extends JPanel {
private static final long serialVersionUID = 1L;
public MyPanelButton() {
JButton OkButton = new JButton("Ok");
add(OkButton);
JButton DeactivateButton = new JButton("Cansel");
add(DeactivateButton);
OkButton.addActionListener(new MyActionOnOk());
DeactivateButton.addActionListener(new MyActionOnCansel());
}
private class MyActionOnOk implements ActionListener {
MyActionOnOk() {
}
public void actionPerformed(ActionEvent event) {
ActionOnTask action = new ActionOnTask(task,2);
SimpleClient.getInstance().clientConnectRead(action);
dispose();
}
}
private class MyActionOnCansel implements ActionListener {
MyActionOnCansel() {
}
public void actionPerformed(ActionEvent event) {
dispose();
}
}
}
} |
package com.gadgetreactor.stocky;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by ASUS on 21/12/2014.
*/
public class StockViewAdapter extends RecyclerView.Adapter<StockViewAdapter.ViewHolder> {
private static JSONArray mDataSet;
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView stockName;
private final TextView symbol;
private final TextView price;
private final TextView change;
private final TextView percentage;
public ViewHolder(View v) {
super(v);
// Define click listener for the ViewHolder's View.
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("StockyViewAdapter", "Test Element " + getPosition() + " clicked.");
Context context = itemView.getContext();
Intent detailIntent = new Intent(context, DetailActivity.class);
JSONObject stock = mDataSet.optJSONObject(getPosition());
detailIntent.putExtra("stock", stock.toString());
context.startActivity(detailIntent);
}
});
stockName = (TextView) v.findViewById(R.id.stockName);
symbol = (TextView) v.findViewById(R.id.symbol);
price = (TextView) v.findViewById(R.id.price);
change = (TextView) v.findViewById(R.id.change);
percentage = (TextView) v.findViewById(R.id.change_percent);
}
}
public StockViewAdapter(JSONArray dataSet) {
mDataSet = dataSet;
}
// BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.stock_view_main, viewGroup, false);
return new ViewHolder(v);
}
// END_INCLUDE(recyclerViewOnCreateViewHolder)
// BEGIN_INCLUDE(recyclerViewOnBindViewHolder)
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// Get element from your dataset at this position and replace the contents of the view
// with that element
Context context;
JSONObject stock = mDataSet.optJSONObject(position);
viewHolder.stockName.setText(stock.optString("Name"));
viewHolder.symbol.setText(stock.optString("symbol"));
viewHolder.price.setText(stock.optString("LastTradePriceOnly"));
viewHolder.change.setText(stock.optString("Change"));
viewHolder.percentage.setText(" ["+stock.optString("ChangeinPercent")+"]");
String changeamt = stock.optString("Change");
if (changeamt.substring(0, 1).equals("+")) {
viewHolder.percentage.setTextColor(Color.parseColor("#00BA00"));
} else if (changeamt.substring(0, 1).equals("-")) {
viewHolder.percentage.setTextColor(Color.parseColor("#E00000"));
}
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataSet.length();
}
}
|
//package sheep.domain;
//
//import javax.persistence.*;
//import java.time.LocalDateTime;
//import java.util.ArrayList;
//import java.util.List;
//
//@Entity
//@Table(name="ORDERS")//디비에 따라서 order가 예약어로 걸려있어서 안되는 경우가 있다.
//public class Order {
//
// @Id
// @GeneratedValue
// @Column(name = "ORDER_ID")
// private Long id;
//
// @ManyToOne(fetch = FetchType.LAZY)
// @JoinColumn(name ="MEMBER_ID")
// private Member member;
//
// @OneToMany(mappedBy = "order",cascade = CascadeType.ALL) //Order생성시 orderItem생성
// private List<OrderItem> orderItems = new ArrayList<>();
//
// private LocalDateTime orderDate; //ORDER_DATE,order_date(부트는 이것을 기본으로 설정해준다.)
//
// @Enumerated(EnumType.STRING)
// private Status orderStatus;
//
// @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL) //Order생성시 Delivery도 같이 생성
// @JoinColumn(name="DELIVERY_ID")
// private Delivery delivery;
//
//
//
//
//}
|
package app;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.MapMessage;
public class Student {
static Logger logger = LogManager.getLogger(Student.class);
MapMessage mapMessage = new MapMessage();
public void doSomething(){
logger.info("qwert from app.Student");
logger.error("error from Student");
}
public void doMapMes() {
mapMessage.put("key", "value");
logger.warn(mapMessage);
}
}
|
package com.datayes.textmining.reportJobs;
import java.io.ObjectInputStream.GetField;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import com.datayes.textmining.Utils.MongoDB;
import com.datayes.textmining.Utils.S3Connection;
import com.datayes.textmining.classification.RptClasifer;
import com.datayes.textmining.classification.RptOrgDataAgent;
import com.datayes.textmining.classification.RptQADataAgent;
import com.datayes.textmining.rptClassification.model.FileInfo;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
public class ReportStream {
public static void procFileByMongoID(String reportIDStr,
RptClasifer rptCls, RptQADataAgent qaRptAg,
RptOrgDataAgent orgRptAg) {
// TODO Auto-generated method stub
FileInfo fileInfo = orgRptAg.getFile(reportIDStr);
try {
rptCls.tryClassify(fileInfo);
qaRptAg.insertQAMongoDBOne(fileInfo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.nio.demo.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NIOServer {
private Selector selector;
private void initServer(int port) throws IOException{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
this.selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void listen() throws IOException{
System.out.println("server is up");
while(true){
selector.select();
Iterator<SelectionKey> iterable = this.selector.selectedKeys().iterator();
while(iterable.hasNext()){
SelectionKey selectionKey = iterable.next();
iterable.remove();
if(selectionKey.isAcceptable()){
ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.write(ByteBuffer.wrap(new String("send a textMessage to client side").getBytes()));
socketChannel.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
read(selectionKey);
}
}
}
}
private void read(SelectionKey selectionKey) throws IOException {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(100);
socketChannel.read(buffer);
buffer.flip();
byte[] data = buffer.array();
String message = new String(data).trim();
System.out.println("received message: " + message);
message = message + ", roger that @client";
ByteBuffer outByteBuffer = ByteBuffer.wrap(message.getBytes());
socketChannel.write(outByteBuffer);
}
public static void main(String[] args) throws IOException{
NIOServer server = new NIOServer();
server.initServer(8000);
server.listen();
}
}
|
package com.netcracker.app.domain.shop.entities;
import javax.persistence.Entity;
@Entity
public class Modem extends Devices {
public Modem() {super();}
public Modem(String name, double price, String description, String shortDescription, String specifications, String imgUrl) {
super(name, price, description, shortDescription, specifications, imgUrl);
}
}
|
public class Main {
public static void main(String[] args) {
Cuadrados listado_cuadrados = new Cuadrados();
listado_cuadrados.cargar_cuadrado(new CuadradoDeColor(4,"Rojo"));
listado_cuadrados.cargar_cuadrado(new CuadradoConNumero(4,12));
listado_cuadrados.mostrar_cuadrados();
}
}
|
package com.nube.core.vo.apps;
import com.nube.core.vo.common.Attribute;
/**
* Application attributes
* @author kamoorr
*
*/
public class AppAttribute implements Attribute{
private String key;
private String value;
private String context;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((context == null) ? 0 : context.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AppAttribute other = (AppAttribute) obj;
if (context == null) {
if (other.context != null)
return false;
} else if (!context.equals(other.context))
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
|
/*
* (c) 2009 Thomas Smits
*/
package de.smits_net.tpe.inheritance;
public class Generic<T> {
public void doIt(T param) {
// ...
}
}
|
/**
* Copyright (c) 2014, Philipp Wagner <bytefish(at)gmx(dot)de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 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 HOLDER 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.bytefish.videofacerecognition.api.constants;
import android.util.Log;
public enum ServiceError {
IMAGE_DECODE_ERROR(10),
IMAGE_RESIZE_ERROR(11),
PREDICTION_ERROR(12),
SERVICE_TEMPORARY_UNAVAILABLE(20),
UNKNOWN_ERROR(21),
INVALID_FORMAT(30),
INVALID_API_KEY(31),
INVALID_API_TOKEN(32),
MISSING_ARGUMENTS(40);
private final int mCode;
ServiceError(int code) {
mCode = code;
}
public int getCode() {
return mCode;
}
/**
* Returns a Service Error by its code.
*
* @param errorCode
* @return
*/
public static ServiceError getServiceErrorByCode(String errorCode) {
ServiceError serviceError = UNKNOWN_ERROR;
try {
Integer errorCodeInt = Integer.parseInt(errorCode);
for(ServiceError err : ServiceError.values()) {
if(err.getCode() == errorCodeInt) {
serviceError = err;
break;
}
}
} catch(NumberFormatException e) {
Log.e("ServiceError", "Unable to parse given error code: " + errorCode);
}
return serviceError;
}
/**
* Returns a human readable error message.
*
* @param serviceError
* @return
*/
public static String getServiceErrorMessage(ServiceError serviceError) {
switch(serviceError) {
case IMAGE_DECODE_ERROR:
return "Error decoding the image.";
case IMAGE_RESIZE_ERROR:
return "Error resizing the image.";
case PREDICTION_ERROR:
return "There was an error predicting the image.";
case SERVICE_TEMPORARY_UNAVAILABLE:
return "The service is temporarily unavailable.";
case UNKNOWN_ERROR:
return "There was an unknown error.";
case INVALID_FORMAT:
return "The request has the wrong format.";
case INVALID_API_KEY:
return "The given API Key is not valid.";
case INVALID_API_TOKEN:
return "The given API Token is invalid.";
case MISSING_ARGUMENTS:
return "The request has missing arguments.";
default:
return "There was an unknown error.";
}
}
}
|
package com.food.debug.web.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 关于静态网页的测试
*/
@Controller
public class TestController {
@RequestMapping(value = "test")
public String test() {
return "test/index";
}
@RequestMapping(value = "/test/{pageName}", method = RequestMethod.GET)
public String initTestStaticPages(@PathVariable("pageName") String pageName) {
return "test/"+pageName;
}
@RequestMapping(value = "admin")
public String admin() {
return "admin/index";
}
@RequestMapping(value = "/admin/{pageName}", method = RequestMethod.GET)
public String initAdminStaticPages(@PathVariable("pageName") String pageName) {
return "admin/"+pageName;
}
@RequestMapping(value = "frontend")
public String frontend() {
return "frontend/index";
}
@RequestMapping(value = "/frontend/{pageName}", method = RequestMethod.GET)
public String initFrontendStaticPages(@PathVariable("pageName") String pageName) {
return "frontend/"+pageName;
}
}
|
package pro.likada.service.serviceImpl;
import org.hibernate.HibernateException;
import pro.likada.dao.TelegramBotDAO;
import pro.likada.model.TelegramBot;
import pro.likada.service.TelegramBotService;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by Yusupov on 4/2/2017.
*/
@Named("telegramBotService")
@Transactional
public class TelegramBotServiceImpl implements TelegramBotService {
@Inject
private TelegramBotDAO telegramBotDAO;
@Override
public TelegramBot findById(Long id) throws HibernateException {
return telegramBotDAO.findById(id);
}
@Override
public TelegramBot findByTelegramBotId(Integer telegramBotId) throws HibernateException {
return telegramBotDAO.findByTelegramBotId(telegramBotId);
}
@Override
public TelegramBot findByTelegramBotUsername(String botUsername) throws HibernateException {
return telegramBotDAO.findByTelegramBotUsername(botUsername);
}
@Override
public List<TelegramBot> findAll() {
return telegramBotDAO.findAll();
}
@Override
public void save(TelegramBot telegramBot) throws HibernateException {
telegramBotDAO.save(telegramBot);
}
@Override
public void delete(TelegramBot telegramBot) throws HibernateException {
telegramBotDAO.delete(telegramBot);
}
@Override
public void deleteByTelegramBotId(Integer botId) throws HibernateException {
telegramBotDAO.deleteByTelegramBotId(botId);
}
}
|
package com.romitus;
import java.util.Scanner;
public class Ejercicio2 {
/*Escribe un programa que pida 20 números enteros. Estos números se deben
introducir en un array de 4 filas por 5 columnas. El programa mostrará las
sumas parciales de filas y columnas igual que si de una hoja de cálculo se
tratara. La suma total debe aparecer en la esquina inferior derecha.*/
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int tablaNumeros[][] = new int[4][5];
for (int i = 0; i < 4; i++) { //Eje x
for (int j = 0; j < 5; j++) { //Eje y
tablaNumeros[i][j] = teclado.nextInt();
}
}
System.out.println();
leerArray(tablaNumeros);
System.out.println();
leerArray(media(tablaNumeros));
}
public static void leerArray(int tablaBidimensional[][]) {
for (int i = 0; i < tablaBidimensional.length; i++) {
for (int j = 0; j < tablaBidimensional[i].length; j++) {
System.out.print(tablaBidimensional[i][j] + " ");
}
System.out.println();
}
}
public static int[][] media(int tabla[][]){
int suma = 0;
int tablaResultado[][] = new int[tabla.length+1][tabla[0].length+1];
for (int i = 0; i < tabla.length; i++) {
for (int j = 0; j < tabla[i].length; j++) {
tablaResultado[i][j] = tabla[i][j];
}
}
for (int i = 0; i < tabla.length; i++) {
for (int j = 0; j < tabla[i].length; j++) {
suma = suma + tablaResultado[i][j];
}
tablaResultado[i][5]= suma / tabla[0].length;
}
for (int i = 0; i < tabla.length; i++) {
for (int j = 0; j < tabla[i].length; j++) {
suma = suma + tablaResultado[j][i];
}
tablaResultado[tabla.length][i]= suma / 4;
}
return tablaResultado;
}
} |
import java.io.*;
import java.util.*;
class thirdchar
{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
String str=kb.nextLine();
int len=str.length();
if(len>0&&len<100001)
{
for(int i=0;i<len;i++)
{
if(i%3==0)
{
System.out.print(str.charAt(i));
}
}
}
System.out.println();
}
}
|
package com.company.Punto1;
public class Libro {
private String title;
private float price;
private int stock;
Autor[] autores;
public Libro(String title, float price, int stock, Autor[] autores) {
this.title=title;
this.price=price;
this.stock=stock;
this.autores=autores;
}
public String getTitle() {
return title;
}
public float getPrice() {
return price;
}
public int getStock() {
return stock;
}
public void recorrerArreglo(Autor[] autores){
for(int i=0;i<autores.length;i++){
System.out.println("Name: "+autores[i].getName());
System.out.println("Surname: "+autores[i].getSurname());
System.out.println("Email: "+autores[i].getEmail());
System.out.println("Gender: "+autores[i].getGender());
System.out.println("-------------------------");
}
}
public void mostrarLibro(){
System.out.println("Title: "+title);
System.out.println("Price: "+price);
System.out.println("Stock: "+stock);
System.out.println("Autor/es: ");
recorrerArreglo(autores);
}
}
|
package com.ziaan.scorm2004.validator.contentpackage;
import java.util.ArrayList;
import java.util.List;
public class SequencingData
{
private String organizationIdentifier;
private String itemIdentifier;
private String seqType;
private String seqIdRef;
private boolean choice;
private boolean choiceExit;
private boolean flow;
private boolean forwardOnly;
private boolean useAttemptObjInfo;
private boolean useAttemptProgressInfo;
private int attemptLimit;
private double attemptDurationLimit;
private String randomTiming;
private int selectCount;
private boolean reorderChildren;
private String selectionTiming;
private boolean tracked;
private boolean completSetbyContent;
private boolean objSetbyContent;
private boolean preventActivation;
private boolean constrainChoice;
private String requiredSatisfied;
private String requiredNotSatisfied;
private String requiredComplete;
private String requiredIncomplete;
private boolean measureSatisfyIfAction;
private boolean rollupObjSatisfied;
private boolean rollupProgressComplete;
private double objMeasureWeight;
private List rollupRuleList;
private List seqRuleList;
private List objectivesList;
public SequencingData()
{
// SCORM2004 Sequencing Spec에 따른 기본값 Setting
choice = true;
choiceExit = true;
flow = false;
forwardOnly = false;
useAttemptObjInfo = true;
useAttemptProgressInfo = true;
attemptLimit = 0;
attemptDurationLimit = 0.0;
randomTiming = "never";
selectCount = 0;
reorderChildren = false;
selectionTiming = "never";
tracked = true;
completSetbyContent = false;
objSetbyContent = false;
preventActivation = false;
constrainChoice = false;
requiredSatisfied = "always";
requiredNotSatisfied = "always";
requiredComplete = "always";
requiredIncomplete = "always";
measureSatisfyIfAction = false;
rollupObjSatisfied = true;
rollupProgressComplete = true;
objMeasureWeight = 1.0000;
rollupRuleList = new ArrayList();
seqRuleList = new ArrayList();;
objectivesList = new ArrayList();;
}
public double getAttemptDurationLimit()
{
return attemptDurationLimit;
}
public void setAttemptDurationLimit(double attemptDurationLimit)
{
this.attemptDurationLimit = attemptDurationLimit;
}
public int getAttemptLimit()
{
return attemptLimit;
}
public void setAttemptLimit(int attemptLimit)
{
this.attemptLimit = attemptLimit;
}
public boolean isChoice()
{
return choice;
}
public void setChoice(boolean choice)
{
this.choice = choice;
}
public boolean isChoiceExit()
{
return choiceExit;
}
public void setChoiceExit(boolean choiceExit)
{
this.choiceExit = choiceExit;
}
public boolean isCompletSetbyContent()
{
return completSetbyContent;
}
public void setCompletSetbyContent(boolean completSetbyContent)
{
this.completSetbyContent = completSetbyContent;
}
public boolean isConstrainChoice()
{
return constrainChoice;
}
public void setConstrainChoice(boolean constrainChoice)
{
this.constrainChoice = constrainChoice;
}
public boolean isFlow()
{
return flow;
}
public void setFlow(boolean flow)
{
this.flow = flow;
}
public boolean isForwardOnly()
{
return forwardOnly;
}
public void setForwardOnly(boolean forwardOnly)
{
this.forwardOnly = forwardOnly;
}
public String getItemIdentifier()
{
return itemIdentifier;
}
public void setItemIdentifier(String itemIdentifier)
{
this.itemIdentifier = itemIdentifier;
}
public boolean isMeasureSatisfyIfAction()
{
return measureSatisfyIfAction;
}
public void setMeasureSatisfyIfAction(boolean measureSatisfyIfAction)
{
this.measureSatisfyIfAction = measureSatisfyIfAction;
}
public double getObjMeasureWeight()
{
return objMeasureWeight;
}
public void setObjMeasureWeight(double objMeasureWeight)
{
this.objMeasureWeight = objMeasureWeight;
}
public boolean isObjSetbyContent()
{
return objSetbyContent;
}
public void setObjSetbyContent(boolean objSetbyContent)
{
this.objSetbyContent = objSetbyContent;
}
public String getOrganizationIdentifier()
{
return organizationIdentifier;
}
public void setOrganizationIdentifier(String organizationIdentifier)
{
this.organizationIdentifier = organizationIdentifier;
}
public boolean isPreventActivation()
{
return preventActivation;
}
public void setPreventActivation(boolean preventActivation)
{
this.preventActivation = preventActivation;
}
public String getRandomTiming()
{
return randomTiming;
}
public void setRandomTiming(String randomTiming)
{
this.randomTiming = randomTiming;
}
public boolean isReorderChildren()
{
return reorderChildren;
}
public void setReorderChildren(boolean reorderChildren)
{
this.reorderChildren = reorderChildren;
}
public String getRequiredComplete()
{
return requiredComplete;
}
public void setRequiredComplete(String requiredComplete)
{
this.requiredComplete = requiredComplete;
}
public String getRequiredIncomplete()
{
return requiredIncomplete;
}
public void setRequiredIncomplete(String requiredIncomplete)
{
this.requiredIncomplete = requiredIncomplete;
}
public String getRequiredNotSatisfied()
{
return requiredNotSatisfied;
}
public void setRequiredNotSatisfied(String requiredNotSatisfied)
{
this.requiredNotSatisfied = requiredNotSatisfied;
}
public String getRequiredSatisfied()
{
return requiredSatisfied;
}
public void setRequiredSatisfied(String requiredSatisfied)
{
this.requiredSatisfied = requiredSatisfied;
}
public boolean isRollupObjSatisfied()
{
return rollupObjSatisfied;
}
public void setRollupObjSatisfied(boolean rollupObjSatisfied)
{
this.rollupObjSatisfied = rollupObjSatisfied;
}
public boolean isRollupProgressComplete()
{
return rollupProgressComplete;
}
public void setRollupProgressComplete(boolean rollupProgressComplete)
{
this.rollupProgressComplete = rollupProgressComplete;
}
public int getSelectCount()
{
return selectCount;
}
public void setSelectCount(int selectCount)
{
this.selectCount = selectCount;
}
public String getSelectionTiming()
{
return selectionTiming;
}
public void setSelectionTiming(String selectionTiming)
{
this.selectionTiming = selectionTiming;
}
public String getSeqIdRef()
{
return seqIdRef;
}
public void setSeqIdRef(String seqIdRef)
{
this.seqIdRef = seqIdRef;
}
public String getSeqType()
{
return seqType;
}
public void setSeqType(String seqType)
{
this.seqType = seqType;
}
public boolean isTracked()
{
return tracked;
}
public void setTracked(boolean tracked)
{
this.tracked = tracked;
}
public boolean isUseAttemptObjInfo()
{
return useAttemptObjInfo;
}
public void setUseAttemptObjInfo(boolean useAttemptObjInfo)
{
this.useAttemptObjInfo = useAttemptObjInfo;
}
public boolean isUseAttemptProgressInfo()
{
return useAttemptProgressInfo;
}
public void setUseAttemptProgressInfo(boolean useAttemptProgressInfo)
{
this.useAttemptProgressInfo = useAttemptProgressInfo;
}
public List getRollupRuleList()
{
return rollupRuleList;
}
public void setRollupRuleList(List rollupRuleList)
{
this.rollupRuleList = rollupRuleList;
}
public void setSeqRuleList(List seqRuleList)
{
this.seqRuleList = seqRuleList;
}
public List getSeqRuleList()
{
return seqRuleList;
}
public List getObjectivesList()
{
return objectivesList;
}
public void setObjectivesList(List objectivesList)
{
this.objectivesList = objectivesList;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append( "\n Sequencing---------------------------------" );
sb.append( "\n organizationIdentifier : " + organizationIdentifier );
sb.append( "\n itemIdentifier : " + itemIdentifier );
sb.append( "\n seqType : " + seqType );
sb.append( "\n seqIdRef : " + seqIdRef );
sb.append( "\n choice : " + choice );
sb.append( "\n choiceExit : " + choiceExit );
sb.append( "\n flow : " + flow );
sb.append( "\n forwardOnly : " + forwardOnly );
sb.append( "\n useAttemptObjInfo : " + useAttemptObjInfo );
sb.append( "\n useAttemptProgressInfo : " + useAttemptProgressInfo );
sb.append( "\n attemptLimit : " + attemptLimit );
sb.append( "\n attemptDurationLimit : " + attemptDurationLimit );
sb.append( "\n randomTiming : " + randomTiming );
sb.append( "\n selectCount : " + selectCount );
sb.append( "\n reorderChildren : " + reorderChildren );
sb.append( "\n selectionTiming : " + selectionTiming );
sb.append( "\n tracked : " + tracked );
sb.append( "\n completSetbyContent : " + completSetbyContent );
sb.append( "\n objSetbyContent : " + objSetbyContent );
sb.append( "\n preventActivation : " + preventActivation );
sb.append( "\n constrainChoice : " + constrainChoice );
sb.append( "\n requiredSatisfied : " + requiredSatisfied );
sb.append( "\n requiredNotSatisfied : " + requiredNotSatisfied );
sb.append( "\n requiredComplete : " + requiredComplete );
sb.append( "\n requiredIncomplete : " + requiredIncomplete );
sb.append( "\n measureSatisfyIfAction : " + measureSatisfyIfAction );
sb.append( "\n rollupObjSatisfied : " + rollupObjSatisfied );
sb.append( "\n rollupProgressComplete : " + rollupProgressComplete );
sb.append( "\n objMeasureWeight : " + objMeasureWeight );
sb.append( "\n ---------------------------------------" );
return sb.toString();
}
}
|
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public abstract class TargetScreen implements Screen {
protected Creature player;
private String letters;
protected World world;
protected abstract String getVerb();
protected abstract boolean isAcceptable(Creature creature);
protected abstract Screen use(Creature creature);
protected boolean isPlayer(Creature creature) {
if (creature.glyph() == '@') {
return true;
}
return false;
}
public TargetScreen(Creature player, World world){
this.player = player;
this.world = world;
this.letters = "abcdefghijklmnopqrstuvwxyz";
}
private ArrayList<String> getList() {
ArrayList<String> lines = new ArrayList<String>();
//Item[] inventory = player.inventory().getItems();
ArrayList<Creature> creatures = world.Creatures();
ArrayList<Creature> creatures2 = new ArrayList<>();
for (Creature creature : creatures) {
if (player.canSee(creature.x, creature.y) && !isPlayer(creature)) {
creatures2.add(creature);
}
}
for (int i = 0; i < creatures2.size(); i++){
Creature creature = creatures2.get(i);
if (creature == null || !isAcceptable(creature)) {
continue;
}
String line = letters.toUpperCase().charAt(i) + " - (" + creature.glyph() + ") " + creature.name() + " distance: " + getDistance(player, creature);
lines.add(line);
}
return lines;
}
public void displayOutput(AsciiPanel terminal) {
ArrayList<String> lines = getList();
int y = 23 - lines.size();
int x = 4;
if (lines.size() > 0)
terminal.clear(' ', x, y, 20, lines.size());
for (String line : lines){
terminal.write(line, x, y++);
}
terminal.clear(' ', 0, 23, 80, 1);
terminal.write("Choose a target to " +
getVerb() + " " +
player.equipped().name() +
" at?", 2, 23);
terminal.repaint();
}
public Screen respondToUserInput(KeyEvent key) {
char c = key.getKeyChar();
ArrayList<Creature> creatures = world.Creatures();
ArrayList<Creature> creatures2 = new ArrayList<>();
for (Creature creature : creatures) {
if (player.canSee(creature.x, creature.y) && !isPlayer(creature)) {
creatures2.add(creature);
}
}
if (letters.indexOf(c) > -1
&& creatures2.size() > letters.indexOf(c)
&& creatures2.get(letters.indexOf(c)) != null
&& isAcceptable(creatures2.get(letters.indexOf(c)))) {
return use(creatures2.get(letters.indexOf(c)));
}
else if (key.getKeyCode() == KeyEvent.VK_ESCAPE){
return null;
}
else{
return this; }
}
public int getDistance(Creature creature, Creature creature2) {
return (int) Math.round(Math.sqrt((creature2.x - creature.x )* (creature2.x - creature.x) + (creature2.y - creature.y) * (creature2.y - creature.y)));
}
} |
package com.mahang.weather.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class WeatherViewPager extends ViewPager {
private boolean mEnableScroll = true;
private static final int DELAY_TIME = 300;
public WeatherViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WeatherViewPager(Context context) {
super(context);
init(context);
}
private void init(Context context) {
setPageTransformer(true, new TransformerDepthPage());
}
public void setEnableScroll(boolean enable) {
mEnableScroll = enable;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if (mEnableScroll) {
return super.onTouchEvent(arg0);
} else {
return false;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if (mEnableScroll) {
return super.onInterceptTouchEvent(arg0);
} else {
return false;
}
}
@Override
public void setCurrentItem(int item) {
setCurrentItem(item, false);
}
@Override
public void setCurrentItem(final int item, final boolean smoothScroll) {
postDelayed(new Runnable() {
@Override
public void run() {
WeatherViewPager.super.setCurrentItem(item,smoothScroll);
}
},DELAY_TIME);
}
}
|
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Test synchronization primitives.
*
* TODO: this should be re-written to be a little more rigorous and/or
* useful. Also, the ThreadDeathHandler stuff should be exposed or
* split out.
*/
public class Main {
public static void main(String[] args) {
System.out.println("Sleep Test");
sleepTest();
System.out.println("\nCount Test");
countTest();
System.out.println("\nInterrupt Test");
interruptTest();
}
static void sleepTest() {
System.out.println("GOING");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("INTERRUPT!");
ie.printStackTrace(System.out);
}
System.out.println("GONE");
}
static void countTest() {
CpuThread one, two;
one = new CpuThread(1);
two = new CpuThread(2);
synchronized (one) {
one.start();
try {
one.wait();
} catch (InterruptedException ie) {
System.out.println("INTERRUPT!");
ie.printStackTrace(System.out);
}
}
two.start();
//System.out.println("main: off and running");
try {
one.join();
two.join();
} catch (InterruptedException ie) {
System.out.println("INTERRUPT!");
ie.printStackTrace(System.out);
}
System.out.println("main: all done");
}
static void interruptTest() {
SleepyThread sleepy, pesky;
sleepy = new SleepyThread(null);
pesky = new SleepyThread(sleepy);
sleepy.setPriority(4);
sleepy.start();
pesky.start();
pesky.setPriority(3);
}
}
class CpuThread extends Thread {
static Object mSyncable = new Object();
static int mCount = 0;
int mNumber;
CpuThread(int num) {
super("CpuThread " + num);
mNumber = num;
}
public void run() {
//System.out.print("thread running -- ");
//System.out.println(Thread.currentThread().getName());
synchronized (mSyncable) {
synchronized (this) {
this.notify();
}
for (int i = 0; i < 10; i++) {
output(mNumber);
}
System.out.print("Final result: ");
System.out.println(mCount);
}
}
void output(int num) {
int count = mCount;
System.out.print("going: ");
System.out.println(num);
/* burn CPU; adjust end value so we exceed scheduler quantum */
for (int j = 0; j < 5000; j++) {
;
}
count++;
mCount = count;
}
}
class SleepyThread extends Thread {
private SleepyThread mOther;
private Integer[] mWaitOnMe; // any type of object will do
private volatile boolean otherDone;
private static int count = 0;
SleepyThread(SleepyThread other) {
mOther = other;
otherDone = false;
mWaitOnMe = new Integer[] { 1, 2 };
setName("thread#" + count);
count++;
}
public void run() {
System.out.println("SleepyThread.run starting");
if (false) {
ThreadDeathHandler threadHandler =
new ThreadDeathHandler("SYNC THREAD");
Thread.currentThread().setUncaughtExceptionHandler(threadHandler);
throw new NullPointerException("die");
}
if (mOther == null) {
boolean intr = false;
try {
do {
synchronized (mWaitOnMe) {
mWaitOnMe.wait(9000);
}
} while (!otherDone);
} catch (InterruptedException ie) {
// Expecting this; interrupted should be false.
System.out.println(Thread.currentThread().getName() +
" interrupted, flag=" + Thread.interrupted());
intr = true;
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
if (!intr)
System.out.println("NOT INTERRUPTED");
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
System.out.println("PESKY INTERRUPTED?");
}
System.out.println("interrupting other (isAlive="
+ mOther.isAlive() + ")");
mOther.interrupt();
mOther.otherDone = true;
}
}
}
|
package com.gsccs.sme.plat.auth.model;
import java.io.Serializable;
/**
* 系统用户
*
* @author x.d zhang
*
*/
public class User implements Serializable {
private Long id; // 编号
private Long orgid; // 所属公司
private String account; // 用户登录名
private String password; // 密码
private String title; // 用户名称
private String phone; // 电话
private String email; // 邮件地址
private String salt; // 加密密码的盐
private String usertype; // 用户类型
private String userclass; // 用户分类(企业/服务机构/专家)
private Boolean locked = Boolean.FALSE;
// 公司名称
private String orgname;
public User() {
}
public User(String account, String password) {
this.account = account;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getOrgid() {
return orgid;
}
public void setOrgid(Long orgid) {
this.orgid = orgid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getCredentialsSalt() {
return account + salt;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOrgname() {
return orgname;
}
public void setOrgname(String orgname) {
this.orgname = orgname;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public String getUserclass() {
return userclass;
}
public void setUserclass(String userclass) {
this.userclass = userclass;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
if (id != null ? !id.equals(user.id) : user.id != null)
return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", orgid=" + orgid + ", account='"
+ account + '\'' + ", password='" + password + '\''
+ ", salt='" + salt + '\'' + ", locked=" + locked + '}';
}
}
|
package com.mohmedhassan.cleaningapp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mohmedhassan.cleaningapp.Companies.CompaniesActivity;
import com.mohmedhassan.cleaningapp.HTTP_POST.HttpCall_Post;
import com.mohmedhassan.cleaningapp.HTTP_POST.HttpRequest_Post;
import com.mohmedhassan.cleaningapp.Login.LoginActivity;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.HashMap;
import java.util.Locale;
public class SideMenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Context context;
LinearLayout Linearlayour_CarWash,Linearlayour_HouseCleaning,Linearlayour_Landry;
ImageView imageViewGoProfile, ImageProfile;
TextView textViewGoProfile,NameUserProfile,CityUSerProfile;
Button btn_sign_out;
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_side_menu);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerLayout = navigationView.getHeaderView(0);
ImageProfile = headerLayout.findViewById(R.id.circle_imageview_sideMenu);
imageViewGoProfile = headerLayout.findViewById(R.id.imageView_go_profile_sideMenu);
textViewGoProfile = headerLayout.findViewById(R.id.tv_go_profile_sideMenu);
NameUserProfile = headerLayout.findViewById(R.id.tv_name_profile_sideMenu);
btn_sign_out = headerLayout.findViewById(R.id.btn_sign_out_side_menu);
navigationView.setNavigationItemSelectedListener(this);
Linearlayour_CarWash = findViewById(R.id.linearlayout_car_wash);
Linearlayour_HouseCleaning = findViewById(R.id.linearlayout_house_cleaning);
Linearlayour_Landry = findViewById(R.id.linearlayout_landry);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// ShowImageProfileAndName();
Linearlayour_CarWash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SideMenuActivity.this, CompaniesActivity.class);
startActivity(intent);
}
});
imageViewGoProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SideMenuActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
/* btn_sign_out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SideMenuActivity.this, "Sign Out", Toast.LENGTH_SHORT).show();
}
});*/
textViewGoProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SideMenuActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
ImageProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SideMenuActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
Linearlayour_HouseCleaning.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Linearlayour_Landry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
onDestroy();
} else {
super.onBackPressed();
onDestroy();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slide_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
}
*/
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Home) {
// Handle the camera action
} else if (id == R.id.nav_order) {
} else if (id == R.id.nav_vouchres) {
} else if (id == R.id.nav_point) {
} else if (id == R.id.nav_contact_us) {
} else if (id == R.id.nav_about_app) {
} else if (id == R.id.nav_change_language) {
Intent intent = new Intent(SideMenuActivity.this, ChangeLangaugeAcitivty.class);
startActivity(intent);
} else if (id == R.id.nav_sign_out) {
SharedPreferences sharedPreferences = getSharedPreferences("names", Context.MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
startActivity(new Intent(SideMenuActivity.this, LoginActivity.class));
finish();
// Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}/*else if (R.id.nav_sign_out == item.getActionView().findViewById(R.id.btn_sign_out_side_menu).getId()) {
SharedPreferences sharedPreferences = getSharedPreferences("names", Context.MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
startActivity(new Intent(SideMenuActivity.this, LoginActivity.class));
finish();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private boolean SelectLanguage() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.change_language, null);
Button btn_arabic = (Button) alertLayout.findViewById(R.id.btn_arabic_changeLanguage);
Button btn_english = (Button) alertLayout.findViewById(R.id.btn_english_changeLanguage);
btn_arabic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchLocal(context,"ar",SideMenuActivity.this);
}
});
btn_english.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchLocal(context,"en",SideMenuActivity.this);
}
});
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// this is set the View from XML inside AlertDialog
alert.setView(alertLayout);
// disallow cancel of AlertDialog on click of back button and outside touch
dialog = alert.create();
dialog.show();
return false;
}
public static void switchLocal(Context context, String lcode, Activity activity) {
if (lcode.equalsIgnoreCase(""))
return;
Resources resources = context.getResources();
Locale locale = new Locale(lcode);
Locale.setDefault(locale);
android.content.res.Configuration config = new
android.content.res.Configuration();
config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
//restart base activity
activity.finish();
activity.startActivity(activity.getIntent());
}
}
|
package com.grape.service;
import com.grape.domain.User;
/**
* @author RuntimeException
*/
public interface UserService {
User getUserByUsername(String username);
}
|
package com.citibank.ods.modules.client.portfolioprvt.functionality;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.functionality.ODSListFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
import com.citibank.ods.entity.pl.TbgOfficerEntity;
import com.citibank.ods.modules.client.portfolioprvt.functionality.valueobject.BasePortfolioPrvtListFncVO;
import com.citibank.ods.modules.client.portfolioprvt.functionality.valueobject.PortfolioPrvtListFncVO;
import com.citibank.ods.persistence.bg.dao.TbgOfficerDAO;
import com.citibank.ods.persistence.pl.dao.TplPortfolioPrvtDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.modules.client.portfolioprvt.functionality;
* @version 1.0
* @author l.braga,31/03/2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class PortfolioPrvtListFnc extends BasePortfolioPrvtListFnc implements
ODSListFnc
{
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#createFncVO()
*/
public BaseFncVO createFncVO()
{
return new PortfolioPrvtListFncVO();
}
/*
* Parametro PortfolioPrvtListFncVO Retorno vazil O metodo recupera as
* carteiras do banco, com os parametros passado pela tela, e seta no fncVO.
* @see com.citibank.ods.common.functionality.ODSListFnc#list(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void list( BaseFncVO fncVO_ )
{
BasePortfolioPrvtListFncVO fncVO = ( BasePortfolioPrvtListFncVO ) fncVO_;
if ( !fncVO.hasErrors() )
{
ODSDAOFactory factory = ODSDAOFactory.getInstance();
TplPortfolioPrvtDAO portfolioPrvtDAO = factory.getTplPortfolioPrvtDAO();
DataSet result = portfolioPrvtDAO.listPortfolio(
fncVO.getPortfCode(),
fncVO.getPortfNameText(),
fncVO.getPortfOffcrNbr(),
fncVO.getOffcrNameText() );
fncVO.setResults( result );
if ( result.size() > 0 )
{
fncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS );
}
else
{
fncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND );
}
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSListFnc#load(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void load( BaseFncVO fncVO_ )
{
PortfolioPrvtListFncVO listFncVO = ( PortfolioPrvtListFncVO ) fncVO_;
if ( listFncVO.isFromSearch() )
{
loadOfficerText( listFncVO );
listFncVO.setFromSearch( false );
}
else
{
listFncVO.setPortfCode( null );
listFncVO.setPortfNameText( null );
listFncVO.setPortfOffcrNbr( null );
listFncVO.setOffcrNameText( null );
listFncVO.setResults( null );
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSListFnc#validateList(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void validateList( BaseFncVO fncVO_ )
{
//
}
public void loadOfficerText( PortfolioPrvtListFncVO portfolioPrvtListFncVO_ )
{
if ( portfolioPrvtListFncVO_.getPortfOffcrNbr() != null
&& portfolioPrvtListFncVO_.getPortfOffcrNbr().intValue() > 0 )
{
TbgOfficerEntity officerEntity = new TbgOfficerEntity();
officerEntity.getData().setOffcrNbr(
portfolioPrvtListFncVO_.getPortfOffcrNbr() );
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TbgOfficerDAO tbgOfficerDAO = factory.getTbgOfficerDAO();
//Realiza a consulta no DAO
officerEntity = ( TbgOfficerEntity ) tbgOfficerDAO.find( officerEntity );
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
portfolioPrvtListFncVO_.setOffcrNameText( officerEntity.getData().getOffcrNameText() );
}
else
{
portfolioPrvtListFncVO_.setOffcrNameText( "" );
}
}
} |
package com.example.pemik_000.appe;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
/**
* Created by pemik_000 on 05.06.2015.
*/
public class ChargingDialog extends DialogFragment {
Context context;
private int itemCharging;
TaskManager taskManager = new TaskManager();
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] mCharging = { "Charging", "Discharging"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Charging")
.setCancelable(false)
.setNeutralButton("Назад",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNeutralButton("Окей",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
taskManager.setItemCharging(itemCharging);
dialog.cancel();
}
})
.setSingleChoiceItems(mCharging, -1,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(context,"item: " + item, Toast.LENGTH_LONG).show();
setItemCharging(item);
}
});
return builder.create();
}
private void setItemCharging(int itemCharging) {
this.itemCharging = itemCharging;
}
}
|
package com.esum.comp.tcpip;
import com.esum.common.exception.XTrusException;
public class TCPIPException extends XTrusException{
public TCPIPException(String code, String location, Exception e) {
super(code, location, e);
}
public TCPIPException(String code, String location, String message, Throwable cause) {
super(code, location, message, cause);
}
public TCPIPException(String code, String location, String message) {
super(code, location, message);
}
}
|
package goosetech.limitbreaker;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class SignUp extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
final private static String TAG = "debugging_SignUp";
private EditText fullname,username, emailView,password1,password2,phone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//Init firebase stuff
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
//Get views that are needed
fullname = findViewById(R.id.fullname_edit_text);
username = findViewById(R.id.username_edit_text);
emailView = findViewById(R.id.email_edit_text);
password1 = findViewById(R.id.password1_edit_text);
password2 = findViewById(R.id.password2_edit_text);
phone = findViewById(R.id.phone_edit_text);
Button register = findViewById(R.id.register_button);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String pass1 = password1.getText().toString();
String pass2 = password2.getText().toString();
String emailText = emailView.getText().toString();
Log.w(TAG,pass1+" "+pass2);
//Verify that passwords match
if(pass1.equals(pass2)){
Toast.makeText(SignUp.this,"Adding new user...",
Toast.LENGTH_LONG).show();
String fname = fullname.getText().toString();
String uname = username.getText().toString();
String phoneNum = phone.getText().toString();
user newUser = new user(fname,uname,emailText,phoneNum);
createUser(emailText,pass1,newUser);
}
else{
Toast.makeText(SignUp.this,"Passwords do not match!",
Toast.LENGTH_LONG).show();
}
}
});
}
public void createUser(String email, String password, final user newUser) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.w(TAG, "User created successfully");
//Now that user is made store info into database
Log.w(TAG,"Attempting to store user...");
mDatabase.child("profiles").child("users").child(mAuth.getUid()).setValue(newUser);
Log.w(TAG,"User stored");
Toast.makeText(SignUp.this, "User created!",
Toast.LENGTH_SHORT).show();
//Set up a timeout to give user chance to view Toast
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent mainActivity = new Intent(
SignUp.this,MainActivity.class);
startActivity(mainActivity);
}
},
300);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "User was not created"+ task.getException());
Toast.makeText(SignUp.this, "Error registering your data",
Toast.LENGTH_LONG).show();
}
}
});
}
}
|
//file: Problem_3_8.java
//author: Victoria Cameron
//course: CMPT 220
//assignment: Lab 2
//due date: February 9, 2017
//version: 1.0
import java.util.Scanner;
public class Problem_3_8{
public static void main (String [] args){
Scanner input = new Scanner(System.in);
//get numbers from user
System.out.print ("Enter three intergers: ");
int numb1 = input.nextInt();
int numb2 = input.nextInt();
int numb3 = input.nextInt();
int numbX = 0; //I am using this as a placeholder because I dont want to love stored values
//sort the numbers in incresing order
if (numb2 < numb1 || numb3 < numb1){
if (numb2 < numb1){
numbX = numb1;
numb1 = numb2;
numb2 = numbX;
}
if (numb3 < numb1){
numbX = numb1;
numb1 = numb3;
numb3 = numbX;
}
if (numb3 < numb2){
numbX = numb2;
numb2 = numb3;
numb3 = numbX;
}
//print the numbers in their new order
System.out.print (numb1 + " " + numb2 + " " + numb3);
}
}
} |
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
private int openSites;
private int size;
private WeightedQuickUnionUF uf;
private boolean[][] grid;
public Percolation(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Grid must be at least 1x1");
}
this.uf = new WeightedQuickUnionUF(n * n + 2);
this.openSites = 0;
this.size = n;
this.grid = new boolean[n][n];
for (int i = 1; i <= grid.length; i++) {
uf.union(0, convertCoordinatesToId(1, i));
uf.union(n * n + 1, convertCoordinatesToId(n, i));
}
}
public void open(int row, int col) {
if (size < row || row < 1 || col < 1 || col > size) {
throw new IllegalArgumentException("Index must be in bounds. Min index is 1, max index is " + size);
}
openSites++;
int current = convertCoordinatesToId(row, col);
grid[row - 1][col - 1] = true;
if (col > 1 && isOpen(row, col - 1)) {
uf.union(current, convertCoordinatesToId(row, col - 1));
}
if (row < size && isOpen(row + 1, col)) {
uf.union(current, convertCoordinatesToId(row + 1, col));
}
if (col < size && isOpen(row, col + 1)) {
uf.union(current, convertCoordinatesToId(row, col + 1));
}
if (row > 1 && isOpen(row - 1, col)) {
uf.union(current, convertCoordinatesToId(row - 1, col));
}
}
public boolean isOpen(int row, int col) {
return grid[row - 1][col - 1];
}
public boolean isFull(int row, int col) {
return isOpen(row, col) && uf.connected(convertCoordinatesToId(row, col), 0);
}
public int numberOfOpenSites() {
return openSites;
}
public boolean percolates() {
return uf.connected(0, size * size + 1);
}
public static void main(String[] args) {
}
private int convertCoordinatesToId(int row, int column) {
return (row - 1) * grid.length + column;
}
}
|
package com.example.user.lr1_notif;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
int i = 0;
TextView text1;
TextView text2;
Button button1;
Button button2;
Context ctn;
String click;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
text1 = (TextView) findViewById(R.id.text1);
text2 =(TextView) findViewById(R.id.text2);
View.OnClickListener clickBtn1 = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
text1.setText("Hello World");
text2.setText("Click №" + new Integer(i).toString());
i = i+1;
}
};
button1.setOnClickListener(clickBtn1);
click = String.valueOf(i);
View.OnClickListener clickBtn2 = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
NotificationCompat.Builder builder =
new NotificationCompat.Builder(ctn)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Количество нажатий")
.setContentText(click);
Notification notification = builder.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
}
};
button2.setOnClickListener(clickBtn2);
}
}
|
package com.beike.core.service.trx.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beike.biz.service.trx.OrderFilmService;
import com.beike.common.entity.trx.AccountHistory;
import com.beike.common.entity.trx.Payment;
import com.beike.common.entity.trx.RefundRecord;
import com.beike.common.entity.trx.TrxOrder;
import com.beike.common.entity.trx.TrxorderGoods;
import com.beike.common.enums.trx.ActHistoryType;
import com.beike.common.enums.trx.BizType;
import com.beike.common.enums.trx.PaymentType;
import com.beike.core.service.trx.AccountHistoryService;
import com.beike.dao.trx.AccountHistoryDao;
import com.beike.dao.trx.PaymentDao;
import com.beike.dao.trx.TrxorderGoodsDao;
import com.beike.dao.trx.soa.proxy.GoodsSoaDao;
import com.beike.util.BankInfoUtil;
import com.beike.util.EnumUtil;
import com.beike.util.StringUtils;
@Service("accountHistoryService")
public class AccountHistoryServiceImpl implements AccountHistoryService {
private static Log logger = LogFactory
.getLog(AccountHistoryServiceImpl.class);
@Autowired
private PaymentDao paymentDao;
@Autowired
private TrxorderGoodsDao trxorderGoodsDao;
@Autowired
private AccountHistoryDao accountHistoryDao;
@Autowired
private GoodsSoaDao goodsSoaDao;
@Autowired
private OrderFilmService orderFilmService;
/**
* 根据交易Id和交易类型获取payment对象
*/
public Payment findPaymentByUserIdAndType(Long trxId,
PaymentType paymentType) {
Payment payment = paymentDao.findByTrxIdAndType(trxId, paymentType);
return payment;
}
public List<TrxorderGoods> findTxGoodsByTrxOrderId(Long trxId) {
List<TrxorderGoods> tgLisg = trxorderGoodsDao.findByTrxId(trxId);
return tgLisg;
}
public List<TrxorderGoods> findRabateByTrxId(Long trxId) {
List<TrxorderGoods> resList = accountHistoryDao
.findRabateByTrxId(trxId);
return resList;
}
public List<RefundRecord> getRefundDetailByTreOrderId(Long trxOrderId) {
List<RefundRecord> rsList = accountHistoryDao
.findRefundInfoByTrxOrderId(trxOrderId);
return rsList;
}
public List<TrxorderGoods> findGoodsIdByTrxOrderId(Long trxOrderId) {
List<TrxorderGoods> rsList = trxorderGoodsDao.findByTrxId(trxOrderId);
return rsList;
}
public List<TrxorderGoods> findGoodsById(long id) {
List<TrxorderGoods> rsList = accountHistoryDao.findGoodsById(id);
return rsList;
}
@Override
public List<AccountHistory> getHistoryInfoByUserId(Long userId) {
// 获取账户id,beiker_account表中通过userId查询
List<String> accIdList = accountHistoryDao.findAccIdByUserId(userId);
StringBuffer accStr = new StringBuffer();
if (accIdList == null) {
return null;
}
for (String accId : accIdList) {
if (accId != null) {
accStr.append(accId).append(",");
}
}
if (accStr.length() != 0) {
accStr = accStr.delete(accStr.length() - 1, accStr.length());
}
// 查询beiker_accounthistory表中信息
List<AccountHistory> resultList = accountHistoryDao
.findAccounthistoryByAccId(accStr.toString());
List<AccountHistory> accList = null;
if (resultList != null) {
for (AccountHistory acchObj : resultList) {
List<TrxOrder> toList = accountHistoryDao
.findTrxOrderObjById(acchObj.getTrxOrderId());
if (toList != null) {
TrxOrder tmpObj = toList.get(0);
acchObj.setOrdAmount(tmpObj.getOrdAmount());
acchObj.setRequestId(tmpObj.getRequestId());
acchObj.setDescription(tmpObj.getDescription());
acchObj.setExternalId(tmpObj.getExternalId());
acchObj.setTrxStatus(tmpObj.getTrxStatus().toString());
}
}
long refundFlagId = 0;// 退款时,相同trxOrderId的时候,代表其trxOrderId,当trxOrderId改变时,修改为当前trxOrderId
long trxIdFlag = 0; // 在历史表中,有交易Id相同这种情况出现,当出现这种情况时,只使用一条此Id的记录,剩余不使用
int accFlag = 0; // 代表退款时退款数据数组的index
long salesFlag = 0; // 购买时,同一个trx_order_id只能到beiker_trxorder_goods表中查询一次,通过此变量标志来处理
accList = new ArrayList<AccountHistory>();
for (AccountHistory acch : resultList) {
long trxOrderId = acch.getTrxOrderId();
long trxId = 0L;
if (ActHistoryType.RABATE.equals(acch.getActHistoryType())) {
if ("rebate".equals(acch.getDescription())) {
trxId = 0L;
} else {
trxId = Long.valueOf(acch.getDescription().toString());// 12
// 11改动为商品详情表ID
}
}
ActHistoryType actHistoryType = acch.getActHistoryType();
if (actHistoryType.equals(ActHistoryType.LOAD)) {
Payment payment = null;
if(trxOrderId==0){
payment = paymentDao.findById(acch.getTrxId());
}else{
payment = findPaymentByUserIdAndType(trxOrderId,
PaymentType.PAYCASH);
}
if (payment != null) {
if (payment.getPayChannel() != null) {
payment.setPayChannelName(BankInfoUtil
.getInstanceForBankMap().get(
payment.getProviderType().name()+"-"+payment.getPayChannel()));
}
if (payment.getProviderType() != null) {
payment.setProviderName(BankInfoUtil
.getInstanceForPayMap().get(
payment.getProviderType()
.toString()));
}
}
acch.setPayment(payment);
accList.add(acch);
} else if (actHistoryType.equals(ActHistoryType.SALES)) {
if (salesFlag != 0 && salesFlag == trxOrderId) {
continue;
}
salesFlag = trxOrderId; // 标志位赋值,当trxOrderId变化时,标志位重新赋值
List<TrxorderGoods> togList = findGoodsIdByTrxOrderId(trxOrderId);
if (togList != null) {
for (TrxorderGoods trxo : togList) {
//如果是网上选座 add by ljp 20121212
if(trxo.getBizType() == 2){
try {
Long cinemaId = orderFilmService.queryCinemaIdByTrxGoodsId(trxo.getId());
trxo.setCinemaId(cinemaId);
} catch (Exception e) {
e.printStackTrace();
}
}
AccountHistory tmpAcch = cloneAcchObj(acch);
List<TrxorderGoods> trxorderGoodsList = new ArrayList<TrxorderGoods>();
trxorderGoodsList.add(trxo);
String name = trxo.getGoodsName();
trxo.setGoodsName(StringUtils.cutffStr(name, 10,
"..."));
tmpAcch.setTrxAmount(trxo.getPayPrice());
tmpAcch.setTrxOrderGoodsList(trxorderGoodsList);
accList.add(tmpAcch);
}
} else {
logger
.info("can't find the TrxorderGoods by trxorder_id "
+ trxOrderId);
acch.setTrxOrderGoodsList(togList);
accList.add(acch);
}
} else if (actHistoryType.equals(ActHistoryType.REFUND)) {
if (refundFlagId == 0 || refundFlagId != trxOrderId) {
refundFlagId = trxOrderId;
accFlag = 0;
}
// 如果trxId未发生变化且不为初始状态,继续循环
if (trxIdFlag != 0 && trxIdFlag == trxId) {
continue;
}
trxIdFlag = trxId;
List<RefundRecord> rrList = getRefundDetailByTreOrderId(trxOrderId);
if (rrList != null && rrList.size() > accFlag) {
RefundRecord rr = rrList.get(accFlag);
List<TrxorderGoods> togList = findGoodsById(rr
.getTrxGoodsId());
TrxorderGoods trxorderGoods = null;
if (togList != null) {
trxorderGoods = togList.get(0);
//如果是网上选座 add by ljp 20121212
if(trxorderGoods.getBizType() == 2){
Map<String, Object> cinema = goodsSoaDao.getCinemaIdByTrxGoodsId(trxorderGoods.getId());
trxorderGoods.setCinemaId((Long)cinema.get("cinema_id"));
}
trxorderGoods.setGoodsName(StringUtils.cutffStr(
trxorderGoods.getGoodsName(), 10, "..."));
}
List<TrxorderGoods> trxorderGoodsList = new ArrayList<TrxorderGoods>();
trxorderGoodsList.add(trxorderGoods);
acch.setTrxAmount(rr.getTrxGoodsAmount());// 存放交易金额
acch.setTrxOrderGoodsList(trxorderGoodsList);
accList.add(acch);
accFlag++;
}
} else if (actHistoryType.equals(ActHistoryType.RABATE)) {
List<TrxorderGoods> tmpList = findRabateByTrxId(trxId);
if (tmpList != null) {
for (TrxorderGoods tog : tmpList) {
String name = tog.getGoodsName();
tog.setGoodsName(StringUtils.cutffStr(name, 10,
"..."));
}
} else {
logger.info("can't find the TrxorderGoods by ID "
+ trxId);
}
acch.setTrxOrderGoodsList(tmpList);
accList.add(acch);
} else {
accList.add(acch);
}
}
}
return accList;
}
/**
* 卖出商品时,因为相同对象要复制成好几份,所以使用此方法尽心对象复制
*
* @param acch
* 历史交易记录对象
* @return 返回历史交易记录对象
*/
public AccountHistory cloneAcchObj(AccountHistory acch) {
AccountHistory tmpAcch = new AccountHistory();
tmpAcch.setId(acch.getId());
tmpAcch.setAccountId(acch.getAccountId());
tmpAcch.setActHistoryType(acch.getActHistoryType());
tmpAcch.setBalance(acch.getBalance());
tmpAcch.setBizType(acch.getBizType());
tmpAcch.setCreateDate(acch.getCreateDate());
tmpAcch.setDescription(acch.getDescription());
tmpAcch.setDispaly(acch.isDispaly());
tmpAcch.setTrxId(acch.getTrxId());
tmpAcch.setTrxAmount(acch.getTrxAmount());
tmpAcch.setTrxOrderId(acch.getTrxOrderId());
return tmpAcch;
}
@Override
public List<AccountHistory> listAccountHistory(Long actId) {
String actHistoryType = "'" + ActHistoryType.INSIDEREBATE.name()
+ "','" + ActHistoryType.RABATE.name() + "','"
+ ActHistoryType.VMDIS.name() + "'";
List<AccountHistory> listAccHistory = accountHistoryDao
.findAccountIdByActType(actId, actHistoryType);
if (listAccHistory != null) {
int actHisListMaxIndex = listAccHistory.size() - 1;
for (int i = actHisListMaxIndex; i >= 0; i--) {
AccountHistory item = listAccHistory.get(i);
ActHistoryType actHistoryTypeEnum = item.getActHistoryType();
String actHistoryBizType = item.getBizType();
if (ActHistoryType.VMDIS.equals(actHistoryTypeEnum)
&& EnumUtil.transEnumToString(BizType.CARDLOAD).equals(
actHistoryBizType)) {
listAccHistory.remove(item);
}
}
}
if (listAccHistory != null) {
for (int i = 0; i < listAccHistory.size(); i++) {
AccountHistory accHistory = listAccHistory.get(i);
if (ActHistoryType.RABATE
.equals(accHistory.getActHistoryType())) {
if ("rebate".equals(accHistory.getDescription())) {
} else {
TrxorderGoods trxOrderGoods = trxorderGoodsDao
.findById(Long.valueOf(accHistory
.getDescription().trim()));
accHistory.setGoodsId(trxOrderGoods.getGoodsId());
String name = trxOrderGoods.getGoodsName();
accHistory.setGoodsName(StringUtils.cutffStr(name, 10,
"..."));
}
}
}
}
return listAccHistory;
}
}
|
/*
* Copyright (c) 2015-2018 Dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.panda_lang.lily;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.panda_lang.lily.plugin.PluginFinder;
import org.panda_lang.lily.plugin.PluginManager;
import org.panda_lang.lily.ui.LilyUI;
import org.panda_lang.panda.Panda;
public class Lily extends Application {
public static Lily instance;
private final Panda panda;
private final PluginManager pluginManager;
private final LilyComposition composition;
private Stage stage;
private LilyUI ui;
public Lily() {
instance = this;
this.panda = new Panda();
this.pluginManager = new PluginManager(this);
this.composition = new LilyComposition(this);
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
this.ui = new LilyUI(this);
PluginFinder pluginFinder = new PluginFinder(pluginManager);
pluginFinder.find();
ui.initialize();
pluginManager.loadPlugins();
pluginManager.enablePlugins();
stage.show();
}
public void exit() {
pluginManager.disablePlugins();
Platform.exit();
System.exit(-1);
}
public LilyUI getUI() {
return this.ui;
}
public Stage getStage() {
return this.stage;
}
public LilyComposition getComposition() {
return composition;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public Panda getPanda() {
return panda;
}
public static Lily getInstance() {
return instance;
}
}
|
package J2EE小组项目尝试1;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
* @Auther: LBW
* @Date: 2019/3/3
* @Description: J2EE小组项目尝试1
* @version: 1.0
*/
public class ServerThread
{
Socket so =null;
BufferedReader br = null;
public ServerThread(Socket so)throws IOException
{
this.so = so;
br = new BufferedReader(new InputStreamReader(so.getInputStream()));
}
private String readFromClient()
{
try
{
return br.readLine();
}
catch(IOException e)
{
e.printStackTrace(); //
}
return null;
}
public void run()throws IOException
{
String content = null;
while((content = readFromClient()) != null )
{
for(Socket s : MyServer.socketList)
{
PrintStream ps = new PrintStream(so.getOutputStream());
ps.println(content);
}
}
}
}
|
package com.binarysprite.evemat.page.character.data;
/**
*
* @author Tabunoki
*
*/
public class CharacterPortrait {
public final String picture;
public final String name;
public final String corporation;
public final String location;
public final String activeShip;
public final String skills;
public final String wealth;
public final String securityStatus;
public CharacterPortrait(String picture, String name, String corporation, String location, String activeShip,
String skills, String wealth, String securityStatus) {
super();
this.picture = picture;
this.name = name;
this.corporation = corporation;
this.location = location;
this.activeShip = activeShip;
this.skills = skills;
this.wealth = wealth;
this.securityStatus = securityStatus;
}
} |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.appcloud.core.dto;
public class ContainerServiceProxy {
private int id;
private String serviceName;
private String serviceProtocol;
private int servicePort;
private String serviceBackendPort;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceProtocol() {
return serviceProtocol;
}
public void setServiceProtocol(String serviceProtocol) {
this.serviceProtocol = serviceProtocol;
}
public int getServicePort() {
return servicePort;
}
public void setServicePort(int servicePort) {
this.servicePort = servicePort;
}
public String getServiceBackendPort() {
return serviceBackendPort;
}
public void setServiceBackendPort(String serviceBackendPort) {
this.serviceBackendPort = serviceBackendPort;
}
}
|
package mihau.eu.githubsearch.utils.list.item;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.mikepenz.fastadapter.items.AbstractItem;
import java.util.List;
import mihau.eu.githubsearch.R;
import mihau.eu.githubsearch.databinding.ItemUserBinding;
import mihau.eu.githubsearch.model.User;
public class UserItem extends AbstractItem<UserItem, UserItem.ViewHolder> {
public User user;
public UserItem(User user) {
this.user = user;
}
@Override
public int getType() {
return R.id.item_user;
}
@Override
public int getLayoutRes() {
return R.layout.item_user;
}
@Override
public void bindView(@NonNull UserItem.ViewHolder holder, @NonNull List<Object> payloads) {
super.bindView(holder, payloads);
holder.binding.setUser(user);
}
@Override
public long getIdentifier() {
return user.getId();
}
@NonNull
@Override
public UserItem.ViewHolder getViewHolder(View v) {
return new UserItem.ViewHolder(v);
}
static class ViewHolder extends RecyclerView.ViewHolder {
ItemUserBinding binding;
ViewHolder(View view) {
super(view);
binding = ItemUserBinding.bind(itemView);
}
}
} |
package com.example.movieapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LogIn extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Button signUp = findViewById(R.id.sign_btn);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent (LogIn.this, Register.class);
startActivity(intent);
}
});
EditText username = findViewById(R.id.username);
EditText password = findViewById(R.id.password);
Button logBtn = findViewById(R.id.log_btn);
logBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(username.getText().toString().isEmpty()){
username.setError("Email is missing");
return;
}
firebaseAuth.signInWithEmailAndPassword(username.getText().toString(),password.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(getApplicationContext(), ResponseActivity.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LogIn.this, "Error with log in", Toast.LENGTH_SHORT).show();
}
});
}
});
}
} |
package com.huaxiao47.just4fun;
public class Tracker {
public Tracker(){
}
public void init(double l){
}
// public native static long create();
}
|
package com.ipincloud.iotbj.srv.service.impl;
import com.ipincloud.iotbj.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSONObject;
import com.ipincloud.iotbj.srv.domain.Camera;
import com.ipincloud.iotbj.srv.dao.*;
import com.ipincloud.iotbj.srv.service.CameraService;
import com.ipincloud.iotbj.utils.ParaUtils;
//(Camera)摄像机 服务实现类
//generate by redcloud,2020-07-24 19:59:20
@Service("CameraService")
public class CameraServiceImpl implements CameraService {
@Resource
private CameraDao cameraDao;
@Value("${algorithm.push}")
String algorithmPush;
//@param id 主键
//@return 实例对象Camera
@Override
public Camera queryById(Long id) {
return this.cameraDao.queryById(id);
}
//@param jsonObj 调用参数
//@return 实例对象Camera
@Override
public JSONObject addInst(JSONObject jsonObj) {
jsonObj = ParaUtils.removeSurplusCol(jsonObj, "id,cameraIndex,title,region_id,region_title,pos,resolution,url,codec,scene,framerate,corp,videoa,state,algorithms,planview,algorithms_id,pushaddress");
this.cameraDao.addInst(jsonObj);
String pushaddress = "";
if (StringUtils.isNotEmpty(jsonObj.getString("id"))) {
pushaddress = "http://" + algorithmPush + "/live/" + jsonObj.getString("id") + ".flv";
} else {
pushaddress = jsonObj.getString("videoa");
}
jsonObj.put("pushaddress", pushaddress);
cameraDao.updateInst(jsonObj);
// jsonObj.put("id",genId);
return jsonObj;
}
//@param jsonObj 调用参数
//@return 影响记录数
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Integer deletesCameraInst(JSONObject jsonObj) {
Integer delNum1 = this.cameraDao.deletesInst(jsonObj);
return delNum1;
}
//@param jsonObj 过滤条件等
//@return 对象查询Camera 分页
@Override
public Map cameraList(JSONObject jsonObj) {
int totalRec = this.cameraDao.countCameraList(jsonObj);
jsonObj = ParaUtils.checkStartIndex(jsonObj, totalRec);
List<Map> pageData = this.cameraDao.cameraList(jsonObj);
Map retMap = new HashMap();
retMap.put("pageData", pageData);
retMap.put("totalRec", totalRec);
retMap.put("cp", jsonObj.get("cp"));
retMap.put("rop", jsonObj.get("rop"));
return retMap;
}
//@param jsonObj 调用参数
//@return 影响记录数Camera
@Override
public void updateInst(JSONObject jsonObj) {
String pushaddress = "";
if (StringUtils.isNotEmpty(jsonObj.getString("id"))) {
pushaddress = "http://" + algorithmPush + "/live/" + jsonObj.getString("id") + ".flv";
} else {
pushaddress = jsonObj.getString("videoa");
}
jsonObj.put("pushaddress", pushaddress);
cameraDao.updateInst(jsonObj);
jsonObj = ParaUtils.removeSurplusCol(jsonObj, "id,cameraIndex,title,region_id,region_title,pos,resolution,url,codec,scene,framerate,corp,videoa,state,algorithms,planview,algorithms_id,pushaddress");
this.cameraDao.updateInst(jsonObj);
}
//设备相关接口,参看api接口/deviceopen
//设备相关接口,参看api接口/devicerestart
//设备相关接口,参看api接口/devicesync
//设备相关接口,参看api接口/deviceclose
}
|
package com.edasaki.rpg.music.api;
public enum NotePitch {
NOTE_0(0, 0.50000F),
NOTE_1(1, 0.52973F),
NOTE_2(2, 0.56123F),
NOTE_3(3, 0.59461F),
NOTE_4(4, 0.62995F),
NOTE_5(5, 0.66741F),
NOTE_6(6, 0.70711F),
NOTE_7(7, 0.74916F),
NOTE_8(8, 0.79370F),
NOTE_9(9, 0.84089F),
NOTE_10(10, 0.89091F),
NOTE_11(11, 0.94386F),
NOTE_12(12, 1.00000F),
NOTE_13(13, 1.05945F),
NOTE_14(14, 1.12245F),
NOTE_15(15, 1.18920F),
NOTE_16(16, 1.25993F),
NOTE_17(17, 1.33484F),
NOTE_18(18, 1.41420F),
NOTE_19(19, 1.49832F),
NOTE_20(20, 1.58741F),
NOTE_21(21, 1.68180F),
NOTE_22(22, 1.78180F),
NOTE_23(23, 1.88775F),
NOTE_24(24, 2.00000F);
public int note;
public float pitch;
private NotePitch(int note, float pitch) {
this.note = note;
this.pitch = pitch;
}
public static float getPitch(int note) {
for (NotePitch notePitch : values()) {
if (notePitch.note == note) {
return notePitch.pitch;
}
}
return 0.0F;
}
} |
package kizil_berkouk.BE.Scenarios;
import java.util.ArrayList;
import java.util.Map;
import enstabretagne.base.logger.Logger;
import enstabretagne.base.time.LogicalDateTime;
import enstabretagne.simulation.components.IEntity;
import enstabretagne.simulation.components.ScenarioId;
import enstabretagne.simulation.components.data.SimFeatures;
import enstabretagne.simulation.components.data.SimInitParameters;
import enstabretagne.simulation.components.implementation.SimEntity;
import enstabretagne.simulation.components.implementation.SimScenario;
import enstabretagne.simulation.core.implementation.SimEvent;
import kizil_berkouk.BE.SimEntity.Artefact.Artefact;
import kizil_berkouk.BE.SimEntity.Artefact.ArtefactFeatures;
import kizil_berkouk.BE.SimEntity.Artefact.ArtefactInit;
import kizil_berkouk.BE.SimEntity.Bateau.Bateau;
import kizil_berkouk.BE.SimEntity.Bateau.BateauFeatures;
import kizil_berkouk.BE.SimEntity.Bateau.BateauInit;
import kizil_berkouk.BE.SimEntity.Drone.EntityDrone;
import kizil_berkouk.BE.SimEntity.Drone.EntityDroneFeature;
import kizil_berkouk.BE.SimEntity.Drone.EntityDroneInit;
import kizil_berkouk.BE.SimEntity.Ocean.EntityOcean;
import kizil_berkouk.BE.SimEntity.Ocean.EntityOceanFeature;
import kizil_berkouk.BE.SimEntity.Ocean.EntityOceanInit;
public class Scenario extends SimScenario{
protected static ArrayList<EntityDrone> listEntityDrones = new ArrayList<>();
public Scenario(ScenarioId id, SimFeatures features, LogicalDateTime start, LogicalDateTime end) {
super(id, features, start, end);
}
public static ArrayList<EntityDrone> getListEntityDrones() {
return listEntityDrones;
}
@Override
protected void initializeSimEntity(SimInitParameters init) {
super.initializeSimEntity(init);
}
@Override
protected void AfterActivate(IEntity sender, boolean starting) {
super.AfterActivate(sender, starting);
ScenarioFeatures feature = (ScenarioFeatures) getFeatures();
Logger.Detail(this, "afteractivate", "taille liste artefacts = %s", feature.getArtefacts().size());
for(Map.Entry<ArtefactFeatures, ArtefactInit> e : feature.getArtefacts().entrySet())
{
Logger.Detail(this, "afteractivate", "artefact à créer = %s , %s", e.getValue(),e.getKey());
Post(new ArtefactArrival(e.getValue(),e.getKey()));
}
for(Map.Entry<EntityDroneFeature, EntityDroneInit> e : feature.getDrones().entrySet())
{
Logger.Detail(this, "afteractivate", "drone à créer = %s , %s", e.getValue(),e.getKey());
Post(new DroneArrival(e.getValue(),e.getKey()));
}
for(Map.Entry<BateauFeatures, BateauInit> e : feature.getBateau().entrySet())
{
Logger.Detail(this, "afteractivate", "bateau à créer = %s , %s", e.getValue(),e.getKey());
Post(new BateauArrival(e.getValue(),e.getKey()));
}
for(Map.Entry<EntityOceanFeature, EntityOceanInit> e : feature.getOcean().entrySet())
{
Logger.Detail(this, "afteractivate", "océan à créer = %s , %s", e.getValue(),e.getKey());
Post(new OceanArrival(e.getValue(),e.getKey()));
}
}
class BateauArrival extends SimEvent
{
private BateauInit i;
private BateauFeatures f;
public BateauInit getI() {
return i;
}
public BateauFeatures getF() {
return f;
}
public BateauArrival(BateauInit i, BateauFeatures f) {
this.i=i;
this.f=f;
}
@Override
public void Process() {
Logger.Detail(this, "BateauArrival.Process", "Création du bateau " + i);
SimEntity b = createChild(Bateau.class, i.getName() , f);
b.initialize(getI());
b.activate();
}
}
class DroneArrival extends SimEvent
{
private EntityDroneInit i;
private EntityDroneFeature f;
public EntityDroneInit getI() {
return i;
}
public EntityDroneFeature getF() {
return f;
}
public DroneArrival(EntityDroneInit i, EntityDroneFeature f) {
this.i=i;
this.f=f;
}
@Override
public void Process() {
Logger.Detail(this, "DroneArrival.Process", "Création du drone " + i.getName());
SimEntity b = createChild(EntityDrone.class, i.getName() , f);
EntityDrone drone = (EntityDrone) b;
listEntityDrones.add(drone);
b.initialize(getI());
b.activate();
}
}
class ArtefactArrival extends SimEvent
{
private ArtefactInit i;
private ArtefactFeatures f;
public ArtefactInit getI() {
return i;
}
public ArtefactFeatures getF() {
return f;
}
public ArtefactArrival(ArtefactInit i, ArtefactFeatures f) {
this.i=i;
this.f=f;
}
@Override
public void Process() {
Logger.Detail(this, "ArtefactArrival.Process", "Création de l'artefact" + i.getName());
SimEntity b = createChild(Artefact.class, i.getName() , f);
b.initialize(getI());
b.activate();
}
}
class OceanArrival extends SimEvent
{
private EntityOceanInit i;
private EntityOceanFeature f;
public EntityOceanInit getI() {
return i;
}
public EntityOceanFeature getF() {
return f;
}
public OceanArrival(EntityOceanInit i, EntityOceanFeature f) {
this.i=i;
this.f=f;
}
@Override
public void Process() {
Logger.Detail(this, "OceanArrival.Process", "Création de l'océan" + i.getName());
SimEntity b = createChild(EntityOcean.class, i.getName() , f);
b.initialize(getI());
b.activate();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.