text
stringlengths 10
2.72M
|
|---|
package com.gtambit.gt.app.mission;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ambit.city_guide.R;
import com.gtambit.gt.app.api.GtApi;
import com.gtambit.gt.app.api.gson.GtLocationObj;
import com.gtambit.gt.app.component.URActionBarActivity;
import com.gtambit.gt.app.member.MemberWebActivity;
import com.gtambit.gt.app.mission.api.TaskApi;
import com.gtambit.gt.app.mission.api.TaskRequestApi;
import com.gtambit.gt.app.mission.api.TaskSharedPreferences;
import com.gtambit.gt.app.mission.obj.RedeemTaskResultType;
import com.gtambit.gt.app.mission.obj.TaskDetailType;
import com.hyxen.analytics.AnalyticsTracker;
import org.json.JSONException;
import org.json.JSONObject;
import lib.hyxen.ui.SimpleDialog;
import ur.ga.URBigData;
import ur.ga.URGAManager;
public class TaskTask10_20 extends URActionBarActivity implements OnClickListener
{
private ProgressDialog progressDialog;
private Handler mHandler = new Handler();
private String taskId;
private int redeemErrorCode = 1;
private boolean isCancelDialog = false;
private TextView mTextView_Name;
private TextView mTextView_Point;
private TextView mTextView_Deadline;
private TextView mTextView_LimitMember;
private WebView mWebView;
private ImageView vipTagImage;
private boolean isRefreshTaskList = false;
private RedeemTaskResultType mRedeemType;
private TaskDetailType mDetail;
private boolean isGeofence = false;
private boolean isLocationEvent = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.t_task_detail);
readBundle();
initialLayout();
getDatailInfo();
setTitleName(getString(R.string.mission_type_10));
String api_token = TaskSharedPreferences.getApiToken(this);
if (api_token.equals("")) {
// GtApi.LoginCheck(this,"執行解任務");
SimpleDialog.showAlert(getSupportFragmentManager(), "尚未登入會員", "您需要登入會員才能進行賺點數活動喔!", "登入/註冊", "知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(TaskTask10_20.this, MemberWebActivity.class));
TaskTask10_20.this.finish();
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TaskTask10_20.this.finish();
}
});
}
}
@Override
protected void onResume() {
super.onResume();
if(isLocationEvent) {
TaskApi.setTaskLocationView(TaskTask10_20.this, mDetail, isGeofence, mHandler);
}
}
private void readBundle()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
taskId = bundle.getString("taskId");
isGeofence = bundle.getBoolean(GtLocationObj.KEY_GEOFENCE, false);
}
private void initialLayout()
{
// findViewById(R.id.ImageButtonBack).setOnClickListener(this);
findViewById(R.id.Button_DoTask).setOnClickListener(this);
findViewById(R.id.Button_DoTask).setVisibility(View.VISIBLE);
findViewById(R.id.Button_RedoTask).setVisibility(View.GONE);
findViewById(R.id.Button_DoTaskStep2).setVisibility(View.GONE);
mTextView_Name = (TextView) findViewById(R.id.TextView_TaskName);
mTextView_Point = (TextView) findViewById(R.id.TextView_TaskPoint);
mTextView_Deadline = (TextView) findViewById(R.id.TextView_Deadline);
mTextView_LimitMember = (TextView) findViewById(R.id.TextView_LimitMember);
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.ProgressBar);
mWebView = (WebView) findViewById(R.id.WebView);
mWebView.setBackgroundColor(0);
mWebView.setHorizontalScrollBarEnabled(false);
WebSettings bs = mWebView.getSettings();
bs.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
mHandler.post(new Runnable() {
@Override
public void run()
{
mProgressBar.setVisibility(View.VISIBLE);
}
});
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url)
{
mHandler.post(new Runnable() {
@Override
public void run()
{
mProgressBar.setVisibility(View.GONE);
}
});
super.onPageFinished(view, url);
}
// @Override
// public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//// super.onReceivedSslError(view, handler, error);
// handler.proceed();
// }
});
}
private void getDatailInfo()
{
isCancelDialog = false;
progressDialog = ProgressDialog.show(this, "", getString(R.string.reading), false, true, new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog)
{
isCancelDialog = true;
}
});
Thread t = new Thread(){
@Override
public void run()
{
mDetail = TaskRequestApi.getTaskDetail(TaskTask10_20.this, taskId);
mHandler.post(new Runnable() {
@Override
public void run()
{
findViewById(R.id.ur_task_detail_img_vip).setVisibility(mDetail != null && mDetail.isForVip() ? View.VISIBLE : View.INVISIBLE);
if (isCancelDialog) {
return;
}
progressDialog.dismiss();
if (mDetail == null)
{
GtApi.alertOKMessage(TaskTask10_20.this, "", getString(R.string.t_cannot_get_data), null);
}
else if (mDetail.errorCode == 0)
{
if(mDetail.loc_type != 1) isLocationEvent = true;
TaskApi.setTaskLocationView(TaskTask10_20.this, mDetail, isGeofence, mHandler);
findViewById(R.id.LinearLayout_Content).setVisibility(View.VISIBLE);
findViewById(R.id.RelativeLayout_Bottom).setVisibility(View.VISIBLE);
ImageView mImageView_TypeIcon = (ImageView) findViewById(R.id.ImageView_TypeIcon);
int image = TaskApi.getTaskTypeImage(mDetail.taskType);
mImageView_TypeIcon.setImageResource(image);
mTextView_Name.setText(mDetail.taskName);
URGAManager.sendScreenName(getApplicationContext(), getString(R.string.ga_task) + "_" + mDetail.taskName);
mTextView_Point.setText(mDetail.point);
if (mDetail.limitNum.equals("-1"))
{
mTextView_LimitMember.setText(getString(R.string.mission_limit_without));
}
else
{
mTextView_LimitMember.setText(mDetail.limitNum);
}
mTextView_Deadline.setText(TaskApi.getDateFromTs(mDetail.endTs*1000));
mWebView.loadDataWithBaseURL ("http://zerocard.tw/", mDetail.taskHtml, "text/html", "utf-8", "http://zerocard.tw/");
}
else if (mDetail.errorCode == -100)
{
GtApi.alertOKMessage(TaskTask10_20.this, getString(R.string.member_login_fb_overdue_title), getString(R.string.member_login_fb_overdue_des), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
startActivity(new Intent(TaskTask10_20.this, MemberWebActivity.class));
finish();
}
});
}
else
{
GtApi.alertOKMessage(TaskTask10_20.this, "", getString(R.string.t_cannot_get_data), null);
}
}
});
}
};
t.start();
}
private void doTask() {
isCancelDialog = false;
progressDialog = ProgressDialog.show(this, "", getString(R.string.task_verify), false, true, new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog)
{
isCancelDialog = true;
}
});
Thread t = new Thread(){
@Override
public void run()
{
String optJson = "";
try
{
JSONObject json = new JSONObject();
json.put("type", 10);
optJson = json.toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
String verifyCode = TaskRequestApi.varifyCode(TaskTask10_20.this, taskId, mDetail.taskKey);
mRedeemType = TaskRequestApi.redeemTask(TaskTask10_20.this, taskId, optJson, verifyCode);
redeemErrorCode = mRedeemType.errorCode;
mHandler.post(new Runnable() {
@Override
public void run()
{
if (isCancelDialog) {
return;
}
progressDialog.dismiss();
if (redeemErrorCode == 0)
{
TaskApi.openTaskResult(TaskTask10_20.this, TaskTask10_20.this, mDetail, mRedeemType);
TaskTask10_20.this.finish();
}
else if (redeemErrorCode == -100)
{
GtApi.alertOKMessage(TaskTask10_20.this, getString(R.string.member_login_fb_overdue_title), getString(R.string.member_login_fb_overdue_des), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
startActivity(new Intent(TaskTask10_20.this, MemberWebActivity.class));
}
});
}
}
});
}
};
t.start();
}
@Override
public void finish() {
if (isRefreshTaskList) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
}
super.finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case TaskTaskResult.TaskRequestCode_Result:
isRefreshTaskList = true;
finish();
break;
}
}
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.Button_DoTask:
URGAManager.setGaEvent(getApplicationContext(),"任務活動","任務-"+mDetail.taskName,"任務-"+mDetail.taskName+"-執行任務");
URBigData.MissionExecuteBigData(TaskTask10_20.this, taskId);
doTask();
isRefreshTaskList = true;
break;
}
}
}
|
import java.util.Arrays;
import java.util.Scanner;
/* URL
http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=1144&sca=50&sfl=wr_hit&stx=1871&sop=and
*/
public class Main1871_줄세우기_lis {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] arr = new int[n+1];
for (int i = 1; i <= n; i++) {
arr[i] = s.nextInt();
}
s.close();
int dynamic[] = new int[n+1]; // len[x] : x번째 수를 마지막 원소로 가지는 lis의 길이
for (int i = 1; i <= n; i++) {// 기존 증가수열에 덧붙일 대상
for (int j = 0 ; j < i; j++) { // 맨 처음 원소부터 덧붙일 대상 전 원소 각각과 비교하여 덧불일 수 있는지 체크하고
// 덧붙일 수 있다면 덧붙이는 것이 자신의 기존 최장길이보다 유리할 경우만 update
// len[j] + 1 > len[i] 비교해야하는 이유
// len[i] : j처리전까지의 최대길이, len[j]+1 : j뒤에 i를 덧붙였을때까지의 길이
// 정렬이 되어 있는 데이터가 아니므로 j처리전까지의 최대길이가 j까지의최대길이+1보다 더 클수 있다.
// 결국 i전에 세울수 있는 번호들 중 최대길이값을 이용하게 됨 ==> 인덱스트리 활용포인트
if (arr[j] < arr[i] && dynamic[j] + 1 > dynamic[i]) {
dynamic[i] = dynamic[j] + 1;
}
}
}
Arrays.sort(dynamic);//오름차순 정렬하여 가장 큰값이 끝으로 오게함.(max값 : 최장증가수열의 길이)
System.out.println(n - dynamic[n]); // 이동할 아이의 수이므로 전체인원수에서 최장증가수열의 길이(이동하지 않는 아이의 최대길이)를 뺀다.
}
}
|
package org.group.projects.simple.gis.online.service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.group.projects.simple.gis.online.client.SimpleGisApiClient;
import org.group.projects.simple.gis.online.model.entity.Building;
import org.group.projects.simple.gis.online.model.transport.SearchRequest;
import org.group.projects.simple.gis.online.model.transport.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@AllArgsConstructor
@Service
public class SearchService {
@Autowired
private final SimpleGisApiClient simpleGisApiClient;
public SearchResult getResult(SearchRequest request, int limit) {
log.warn("Send request to simple-gis/api controller {}", request);
SearchResult searchResult = simpleGisApiClient.findBuildings(request);
log.warn("Response {}", searchResult.toString());
return new SearchResult(searchResult.getResults()
.stream()
.map(eachBuilding -> new SearchResult.Result(
eachBuilding.getLon(),
eachBuilding.getLat(),
eachBuilding.getAddress()))
.collect(Collectors.toList()),
request.getContent());
}
}
|
package com.cd.reddit.json.mapping;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonValue;
/**
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class RedditAfter extends RedditType{
private String after;
public String getAfter() {
return this.after;
}
public void setAfter(String after) {
this.after = after;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RedditAfter [after=");
builder.append(this.after);
builder.append("]");
return builder.toString();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.burgosanchez.tcc.venta.ejb;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author TID01
*/
@Embeddable
public class HorarioPK implements Serializable {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 30)
@Column(name = "COD_HORARIO")
private String codHorario;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 30)
@Column(name = "COD_EVENTO")
private String codEvento;
public HorarioPK() {
}
public HorarioPK(String codHorario, String codEvento) {
this.codHorario = codHorario;
this.codEvento = codEvento;
}
public String getCodHorario() {
return codHorario;
}
public void setCodHorario(String codHorario) {
this.codHorario = codHorario;
}
public String getCodEvento() {
return codEvento;
}
public void setCodEvento(String codEvento) {
this.codEvento = codEvento;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codHorario != null ? codHorario.hashCode() : 0);
hash += (codEvento != null ? codEvento.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof HorarioPK)) {
return false;
}
HorarioPK other = (HorarioPK) object;
if ((this.codHorario == null && other.codHorario != null) || (this.codHorario != null && !this.codHorario.equals(other.codHorario))) {
return false;
}
if ((this.codEvento == null && other.codEvento != null) || (this.codEvento != null && !this.codEvento.equals(other.codEvento))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.burgosanchez.tcc.venta.ejb.HorarioPK[ codHorario=" + codHorario + ", codEvento=" + codEvento + " ]";
}
}
|
package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ResourceBundle;
public class ChatController {
ClientImpl client;
ChatView chatView;
public ChatController(ClientImpl client, ChatView view) {
this.client = client;
chatView = view;
client.setController(this);
view.setController(this);
}
public void setClient(ClientImpl client) {
this.client = client;
}
public void setView(ChatView view) {
chatView = view;
}
public void sendMessage(Message message) {
try {
client.sendMsg(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void displayMessage(Message message) {
chatView.addFormattedMessage(message);
}
public void close() {
try {
client.closeConnection();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
|
package com.gurkensalat.calendar.perrypedia.releasecalendar;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.mediawiki.xml.export_0.MediaWikiType;
import org.mediawiki.xml.export_0.PageType;
import org.mediawiki.xml.export_0.RevisionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
@EntityScan
@EnableJpaRepositories
public class Application
{
private static final Logger logger = LoggerFactory.getLogger(Application.class);
private static final String MACRO_PREFIX_ROMAN = "{{Roman";
private static final String MACRO_PREFIX_HANDLUNGSZUSAMMENFASSUNG = "{{Handlungszusammenfassung";
private static final String MACRO_POSTFIX = "}}";
@Autowired
private Environment environment;
@Autowired
private WikiPageRepository wikiPageRepository;
public static void main(String[] args)
{
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner work() throws Exception
{
// first, calculate which issues we need to check
DateTime start = DateTime.now().minusDays(7).withMillisOfDay(0);
DateTime end = DateTime.now().plusDays(60).withMillisOfDay(0);
List<Issue> issuesToCheck = new ArrayList<Issue>();
// check Perry Rhodan Classic first
issuesToCheck.addAll(calculateIssues(new PerryRhodanSeries(), 2838, 2860, start, end));
// check Perry Rhodan NEO next
issuesToCheck.addAll(calculateIssues(new PerryRhodanNeoSeries(), 110, 120, start, end));
// check Perry Rhodan NEO Story next
issuesToCheck.addAll(calculateIssues(new PerryRhodanNeoStorySeries(), 1, 12, start, end));
// check Perry Rhodan Arkon next
issuesToCheck.addAll(calculateIssues(new PerryRhodanArkonSeries(), 1, 12, start, end));
// Now, to the Perrypedia checks...
for (Issue issue : issuesToCheck)
{
checkIssueOnPerryPedia(issue);
}
return null;
}
private List<Issue> calculateIssues(Series series, int startIssue, int endIssue, DateTime start, DateTime end)
{
List<Issue> result = new ArrayList<Issue>();
for (int i = startIssue; i < endIssue; i++)
{
DateTime issueDate = series.getIssueReleaseDate(i);
if (issueDate != null)
{
if (start.isBefore(issueDate))
{
if (end.isAfter(issueDate))
{
Issue issue = new Issue(series, i);
result.add(issue);
}
}
}
}
return result;
}
private void checkIssueOnPerryPedia(Issue issue)
{
logger.info("Have to check issue {}", issue);
WikiPage wikiPage = findFirstWikiPage(issue);
// logger.debug(" Wiki Page is {}", wikiPage);
if (wikiPage == null)
{
wikiPage = new WikiPage();
wikiPage.setSeriesPrefix(issue.getSeries().getSourcePrefix());
wikiPage.setIssueNumber(issue.getNumber());
}
// logger.debug(" before save {}", wikiPage);
wikiPage = wikiPageRepository.save(wikiPage);
// logger.debug(" after save {}", wikiPage);
if (!(WikiPage.getVALID().equals(wikiPage.getSourcePageValid())))
{
try
{
wikiPage.setSourcePageTitle("Quelle:" + issue.getSeries().getSourcePrefix() + issue.getNumber());
wikiPage = wikiPageRepository.save(wikiPage);
MediaWikiType mwt = downloadAndDecode(wikiPage.getSourcePageTitle());
if ((mwt.getPage() != null) && (mwt.getPage().size() > 0))
{
PageType page = mwt.getPage().get(0);
logger.info(" page: {}", page);
logger.info(" id: {}", page.getId());
logger.info(" title: {}", page.getTitle());
logger.info(" redir: {}", page.getRedirect().getTitle());
wikiPage.setSourcePageId(page.getId().toString());
wikiPage.setFullPageTitle(page.getRedirect().getTitle());
if (StringUtils.isNotEmpty(wikiPage.getSourcePageId()) && StringUtils.isNotEmpty(wikiPage.getSourcePageTitle()))
{
if (StringUtils.isNotEmpty(wikiPage.getFullPageTitle()))
{
wikiPage.setSourcePageValid(WikiPage.getVALID());
}
}
wikiPage = wikiPageRepository.save(wikiPage);
}
}
catch (Exception e)
{
logger.error("While loading 'Quelle' page", e);
}
}
if (WikiPage.getVALID().equals((wikiPage.getSourcePageValid())))
{
if (!(WikiPage.getVALID().equals(wikiPage.getFullPageValid())))
{
try
{
MediaWikiType mwt = downloadAndDecode(wikiPage.getFullPageTitle());
if ((mwt.getPage() != null) && (mwt.getPage().size() > 0))
{
PageType page = mwt.getPage().get(0);
logger.info(" page: {}", page);
logger.info(" id: {}", page.getId());
wikiPage.setFullPageId(page.getId().toString());
wikiPage.setFullPageTitle(page.getTitle());
wikiPage.setFullPageText(null);
if (StringUtils.isNotEmpty(wikiPage.getFullPageId()) && StringUtils.isNotEmpty(wikiPage.getFullPageId()))
{
if ((page.getRevisionOrUpload() != null) && (page.getRevisionOrUpload().size() > 0))
{
RevisionType revision = (RevisionType) page.getRevisionOrUpload().get(0);
String text = revision.getText().getValue();
int startMacroPrefixRoman = text.indexOf(MACRO_PREFIX_ROMAN);
if (startMacroPrefixRoman > -1)
{
text = text.substring(startMacroPrefixRoman);
int startMacroPostfix = text.indexOf(MACRO_POSTFIX);
if (startMacroPostfix > -1)
{
text = text.substring(0, startMacroPostfix);
wikiPage.setFullPageValid(wikiPage.getValid());
wikiPage.setFullPageText(text);
}
}
int startMacroPrefixNeo = text.indexOf(MACRO_PREFIX_HANDLUNGSZUSAMMENFASSUNG);
if (startMacroPrefixNeo > -1)
{
text = text.substring(startMacroPrefixNeo);
int startMacroPostfix = text.indexOf(MACRO_POSTFIX);
if (startMacroPostfix > -1)
{
text = text.substring(0, startMacroPostfix);
wikiPage.setFullPageValid(wikiPage.getValid());
wikiPage.setFullPageText(text);
}
}
}
}
// if (StringUtils.isNotEmpty(wikiPage.getFullPageText()))
// {
// wikiPage.setFullPageValid(wikiPage.getVALID());
// }
wikiPage = wikiPageRepository.save(wikiPage);
}
}
catch (Exception e)
{
logger.error("While loading full page", e);
}
}
}
String wikiPageAsString = ToStringBuilder.reflectionToString(wikiPage, ToStringStyle.MULTI_LINE_STYLE);
logger.info("wikiPage is {}", wikiPageAsString);
}
private WikiPage findFirstWikiPage(Issue issue)
{
WikiPage wikiPage = null;
List<WikiPage> wikiPages = wikiPageRepository.findBySeriesPrefixAndIssueNumber(issue.getSeries().getSourcePrefix(), issue.getNumber());
if ((wikiPages != null) && (wikiPages.size() > 0))
{
wikiPage = wikiPages.get(0);
}
return wikiPage;
}
// @Bean
public CommandLineRunner seriesCalculator() throws Exception
{
logger.info("seriesCalculator method called...");
Series classic = new PerryRhodanSeries();
logger.info("Series {}", classic);
Series neo = new PerryRhodanNeoSeries();
logger.info("Series {}", neo);
Series neoStory = new PerryRhodanNeoStorySeries();
logger.info("Series {}", neoStory);
Series arkon = new PerryRhodanArkonSeries();
logger.info("Series {}", arkon);
return null;
}
private MediaWikiType downloadAndDecode(String pageName) throws Exception
{
logger.debug("downloadAndDecode '{}'", pageName);
// String url = "http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit";
// curl 'http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit' \
// --data 'catname=&pages=Quelle:PRN111&curonly=1&wpDownload=1'
// curl 'http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit' \
// --data 'catname=&pages=Seid+ihr+wahres+Leben%3F&curonly=1&wpDownload=1'
// curl 'http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit' \
// --data 'catname=&pages=Leticrons+S%C3%A4ule&curonly=1&wpDownload=1'
// GEHT NICHT...
// curl 'http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit' \
// --data 'catname=&pages=Leticrons+S%E4ule&curonly=1&wpDownload=1'
final String EXPORT_URL = "http://www.perrypedia.proc.org/mediawiki/index.php?title=Spezial:Exportieren&action=submit";
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpGet httpGet = new HttpGet(url);
HttpPost httpPost = new HttpPost(EXPORT_URL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("catname", ""));
params.add(new BasicNameValuePair("pages", pageName));
params.add(new BasicNameValuePair("curonly", "1"));
params.add(new BasicNameValuePair("wpDownload", "1"));
httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
CloseableHttpResponse response1 = httpclient.execute(httpPost);
MediaWikiType mwt = null;
try
{
logger.debug("{}", response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// logger.debug("{}", entity1.getContent());
// do something useful with the response body
String data = EntityUtils.toString(entity1);
// logger.debug("{}", data);
JAXBContext jaxbContext = JAXBContext.newInstance(MediaWikiType.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StreamSource source = new StreamSource(new StringReader(data));
JAXBElement<MediaWikiType> userElement = unmarshaller.unmarshal(source, MediaWikiType.class);
mwt = userElement.getValue();
// logger.debug("Parsed Data: {}", mwt);
// for (PageType page : mwt.getPage())
// {
// logger.debug(" page: {}", page);
// logger.debug(" id: {}", page.getId());
// logger.debug(" title: {}", page.getTitle());
// logger.debug(" redir: {}", page.getRedirect().getTitle());
// }
// and ensure it is fully consumed
EntityUtils.consume(entity1);
}
finally
{
response1.close();
}
return mwt;
}
}
|
/*
* 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 Model;
/**
*
* @author HermanCosta
*/
public class Computer {
String brand, model, serialNumber, processor, ram, storage, gpu, screen, notes;
int computerId, qty;
double price;
public Computer(String brand, String _model, String _serialNumber, String _processor, String _ram, String _storage,
String _gpu, String _screen, String _notes, int _qty, double _price) {
this.brand = brand;
this.model = _model;
this.serialNumber = _serialNumber;
this.processor = _processor;
this.ram = _ram;
this.storage = _storage;
this.gpu = _gpu;
this.screen = _screen;
this.notes = _notes;
this.qty = _qty;
this.price = _price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getProcessor() {
return processor;
}
public void setProcessor(String processor) {
this.processor = processor;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getStorage() {
return storage;
}
public void setStorage(String storage) {
this.storage = storage;
}
public String getGpu() {
return gpu;
}
public void setGpu(String gpu) {
this.gpu = gpu;
}
public String getScreen() {
return screen;
}
public void setScreen(String screen) {
this.screen = screen;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getComputerId() {
return computerId;
}
public void setComputerId(int computerId) {
this.computerId = computerId;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
|
package edu.banking.macias.marcus;
import edu.jenks.dist.banking.AbstractCheckingAccount;
import edu.jenks.dist.banking.AbstractSavingsAccount;
import edu.jenks.dist.banking.Account;
public class CheckingAccount extends AbstractCheckingAccount {
public CheckingAccount() {
}
public CheckingAccount(double balance, double accountInterestAPR) {
setBalance(balance);
setAccountInterestAPR(accountInterestAPR);
}
public void payInterest(int days) {
setBalance(getBalance() * Math.exp(((double)days / DAYS_IN_A_YEAR) * (this.getAccountInterestAPR()/100)));
//setBalance(getBalance() + money);
}
public double transfer(Account destination, double amount) {
if (getBalance() < amount || !destination.canTransact()) {
return 0;
} else {
destination.deposit(amount);
setBalance(getBalance() - amount);
//this.getLinkedSavingsAccount().setNumTransactions(getLinkedSavingsAccount().getNumTransactions() + 1);
return amount;
}
}
public static void main(String[] args) {
CheckingAccount run = new CheckingAccount(100,10);
SavingsAccount thing = new SavingsAccount(200,10);
run.setLinkedSavingsAccount(thing);
run.getLinkedSavingsAccount().setMaxMonthlyTransactions(5);
run.getLinkedSavingsAccount().setNumTransactions(0);
run.setOverdraftProtected(true);
run.setOverdraftMax(50);
System.out.println("Linked before withdraw $" + run.getLinkedSavingsAccount().getBalance());
System.out.println("Before withdraw $" + run.getBalance());
System.out.println(run.withdraw(101));
System.out.println("Linked After withdraw $" + run.getLinkedSavingsAccount().getBalance());
System.out.println("After Withdraw $" + run.getBalance());
System.out.println(run.getLinkedSavingsAccount().getNumTransactions());
//run.getLinkedSavingsAccount().deposit(100);
//run.withdraw(100);
/*System.out.println(run.withdraw(20));
System.out.println("Linked before withdraw $" + run.getLinkedSavingsAccount().getBalance());
System.out.println("After Withdraw $" + run.getBalance());
*/
}
public double withdraw(double amount) {
double remaining = amount;
boolean isLinked = getLinkedSavingsAccount() != null;
double max = getBalance() + this.getOverdraftMax();
if(remaining <= getBalance()) {
setBalance(getBalance() - remaining);
return amount;
}
if(isLinked) {
if((max + this.getLinkedSavingsAccount().getBalance()) < amount) {
return 0;
}else {
remaining -= getBalance();
if(remaining <= this.getLinkedSavingsAccount().getBalance() && this.getLinkedSavingsAccount().canTransact()) {
setBalance(0);
this.getLinkedSavingsAccount().setBalance(this.getLinkedSavingsAccount().getBalance() - remaining);
this.getLinkedSavingsAccount().setNumTransactions(this.getLinkedSavingsAccount().getNumTransactions() + 1);
return amount;
}
remaining -= this.getLinkedSavingsAccount().getBalance();
if(remaining <= this.getOverdraftMax() && this.isOverdraftProtected() && this.getLinkedSavingsAccount().canTransact()) {
setBalance(-remaining);
this.getLinkedSavingsAccount().setBalance(0);
this.getLinkedSavingsAccount().setNumTransactions(this.getLinkedSavingsAccount().getNumTransactions() + 1);
this.setNumberOverdrafts(getNumberOverdrafts() + 1);
return amount;
}
}
}else if(max >= amount && this.isOverdraftProtected()) {
setBalance(getBalance() - amount);
this.setNumberOverdrafts(getNumberOverdrafts() + 1);
return amount;
}
return 0;
}
}
|
package com.zhanwei.java.test2;
public class ThreadLocalTest {
public static void main(String[] args) {
SequenceA sequence = new SequenceA();
ThreadDemo demo1 = new ThreadDemo(sequence);
ThreadDemo demo2 = new ThreadDemo(sequence);
ThreadDemo demo3 = new ThreadDemo(sequence);
demo1.start();
demo2.start();
demo3.start();
}
}
|
package pl.coderslab.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import pl.coderslab.entity.Author;
import pl.coderslab.entity.Book;
import pl.coderslab.entity.Category;
import pl.coderslab.entity.Publisher;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Long>, BookRepositoryCustom {
// List<Book> findByTitle(String title);
List<Book> findAllByCategory(Category category);
List<Book> findAllByCategoryId(Long id);
List<Book> findAllByAuthors(Author author);
List<Book> findAllByPublisherName(String name);
List<Book> findAllByRating(Double rating);
// Book findFirstByCategoryOrderByTitle(Category category);
@Query ("SELECT b FROM Book b WHERE title = :title")
List<Book> findByTitle(@Param("title") String title);
@Query("SELECT b FROM Book b WHERE b.category = :category")
List<Book> findByCategory(@Param("category") Category category);
@Query("SELECT b FROM Book b WHERE b.rating BETWEEN :min AND :max")
List<Book> findByRatingBetweenMinAndMax(@Param("min") Double min, @Param("max") Double max);
@Query("SELECT b FROM Book b WHERE b.publisher = :publisher")
List<Book> findByPublisher(@Param("publisher") Publisher publisher);
@Query(value = "SELECT * FROM books WHERE category_id = ?1 ORDER BY title ASC LIMIT 1", nativeQuery = true)
Book findFirstByCategoryOrderByTitle(@Param("category") Category category);
}
|
package com.oldschool.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import com.oldschool.ejb.EjbGenericoLocal;
import com.oldschool.ejb.EjbLoginLocal;
import com.oldschool.ejb.EjbUsuariosLocal;
import com.oldschool.model.Rol;
import com.oldschool.model.Usuario;
import com.oldschool.util.Mensaje;
import com.oldschool.util.Util;
@ManagedBean(name= UsuariosBean.BEAN_NAME)
@ViewScoped
public class UsuariosBean implements Serializable {
/*Variables Bean*/
public static final String BEAN_NAME = "usuariosBean";
private static final long serialVersionUID = 1461272576618969285L;
@EJB private EjbGenericoLocal ejbGenerico;
@EJB private EjbUsuariosLocal ejbUsuarios;
@EJB private EjbLoginLocal ejbLogin;
/*Variables de sesión*/
@ManagedProperty(value = "#{sesionBean}")
private SesionBean sesionBean;
/*Variables*/
private List<Rol> listaRoles;
private List<Usuario> listaUsuarios;
private Usuario usuarioSeleccionado;
//Formulario de registro
private String nombre;
private String apellido;
private String genero;
private String username;
private String pass;
private String rolesSeleccionados;
private String rolesSeleccionadosMod;
//Cambiar contraseña
private String confirmarPass;
//Filtro usuario
private String filtroNombre;
private String filtroEstado;
/*Métodos privados*/
private void cargarListaUsuarios(byte estado){
try {
listaUsuarios = ejbUsuarios.listarUsuarios(estado);
// listaUsuarios = (List<Usuario>)(List<?>)ejbGenerico.listarTodo(new Usuario());
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void cargarListaRoles(){
try {
this.listaRoles = (List<Rol>)(List<?>)ejbGenerico.listarTodo(new Rol());
} catch (Exception e) {
e.printStackTrace();
}
}
private Rol obtenerRolPorNombre(String nombreRol){
for (Rol rol : listaRoles) {
if(rol.getNombre_Rol().equals(nombreRol)){
return rol;
}
}
return null;
}
/*Métodos públicos*/
@PostConstruct
public void init(){
limpiar();
cargarListaUsuarios(Usuario.ESTADO_ACTIVO);
cargarListaRoles();
}
public void limpiar(){
this.listaUsuarios = new ArrayList<>();
this.usuarioSeleccionado = new Usuario();
this.nombre = null;
this.apellido = null;
this.genero = null;
this.username = null;
this.pass = null;
this.confirmarPass = null;
this.filtroNombre = null;
this.rolesSeleccionados = null;
this.rolesSeleccionadosMod = null;
}
public void crearUsuario(){
try {
//Validar campos vacios
boolean validar = false;
if(this.usuarioSeleccionado!=null){
if(Util.isEmpty(this.nombre)){
validar = true;
}
if(Util.isEmpty(this.apellido)){
validar = true;
}
if(Util.isEmpty(this.genero)){
validar = true;
}
if(Util.isEmpty(this.username)){
validar = true;
}
if(Util.isEmpty(this.pass)){
validar = true;
}
if(Util.isEmpty(this.rolesSeleccionados)){
validar = true;
}
}
//Validar si el nombre de usuario ya existe
if(!validar){
boolean existeUsuario = ejbUsuarios.existeUsuarioConLogin(this.username);
if(existeUsuario){
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ya existe un recurso registrado con ese nombre usuario.");
}else{
//Roles
List<Rol> roles = new ArrayList<>();
String[] rolesStr = rolesSeleccionados.split(",");
for (String nombreRol : rolesStr) {
roles.add(obtenerRolPorNombre(nombreRol));
}
//Usuario
Usuario usuario = new Usuario();
usuario.setNombre_Usuario(nombre);
usuario.setApellido(apellido);
usuario.setGenero(genero);
usuario.setActivo(Usuario.ESTADO_ACTIVO);
usuario.setLogin(this.username);
String encPass = Util.encriptarPass(this.username, this.pass);
usuario.setContraseña(encPass);
usuario.setRols(roles);
//Crear usuario
boolean resultado = ejbUsuarios.registrarUsuario(usuario);
if(resultado){
Mensaje.mostrarMensaje(Mensaje.INFO, "Se registró el usuario correctamente");
limpiar();
cargarListaUsuarios(Usuario.ESTADO_ACTIVO);
}else{
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ha ocurrido un error creando el usuario, por favor intentelo de nuevo más tarde.");
}
}
}else{
Mensaje.mostrarMensaje(Mensaje.WARN, "Hay campos vacíos, por favor verifique y vuelva a intentarlo");
}
} catch (Exception e) {
Mensaje.mostrarMensaje(Mensaje.FATAL, "Ha ocurrido una excepción, intentelo de nuevo más tarde. Si el error persiste contacte a su administrador.");
e.printStackTrace();
}
}
public void filtrarUsuario(){
try {
//Por defecto busca los activos
byte estado = Usuario.ESTADO_ACTIVO;
//En caso de que se seleccione inactivo
if(this.filtroEstado.equals("I")){
estado = Usuario.ESTADO_INACTIVO;
}
//Filtro de nombre
if(!Util.isEmpty(filtroNombre)){
this.listaUsuarios = ejbUsuarios.filtrarUsuariosPorNombreYEstado(filtroNombre, estado);
}else{
//Mostrar todo
cargarListaUsuarios(estado);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void editarUsuario(){
try {
//Validar campos vacios
boolean validar = false;
if(this.usuarioSeleccionado!=null){
if(Util.isEmpty(this.usuarioSeleccionado.getNombre_Usuario())){
validar = true;
}
if(Util.isEmpty(this.usuarioSeleccionado.getApellido())){
validar = true;
}
if(Util.isEmpty(this.usuarioSeleccionado.getGenero())){
validar = true;
}
}
//Actualizar
if(!validar){
//Roles
List<Rol> roles = new ArrayList<>();
String[] rolesStr = rolesSeleccionadosMod.split(",");
for (String nombreRol : rolesStr) {
roles.add(obtenerRolPorNombre(nombreRol));
}
usuarioSeleccionado.setRols(roles);
boolean result = ejbUsuarios.actualizarDatosUsuario(usuarioSeleccionado);
if(result){
Mensaje.mostrarMensaje(Mensaje.INFO, "Se actualizaron los datos del usuario exitosamente.");
limpiar();
cargarListaUsuarios(Usuario.ESTADO_ACTIVO);
}else{
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ha ocurrido un error actualizando los datos del usuario, por favor intentelo de nuevo más tarde.");
}
}else{
Mensaje.mostrarMensaje(Mensaje.WARN, "Hay campos vacíos, por favor verifique y vuelva a intentarlo");
}
} catch (Exception e) {
Mensaje.mostrarMensaje(Mensaje.FATAL, "Ha ocurrido una excepción, intentelo de nuevo más tarde. Si el error persiste contacte a su administrador.");
e.printStackTrace();
}
}
public void inhabilitarUsuario(){
try {
if(this.usuarioSeleccionado!=null){
boolean result = ejbUsuarios.cambiarEstadoDeUsuario(usuarioSeleccionado.getId_usuario(), Usuario.ESTADO_INACTIVO);
if(result){
Mensaje.mostrarMensaje(Mensaje.INFO, "Se Inhabilitó el usuario correctamente.");
limpiar();
cargarListaUsuarios(Usuario.ESTADO_ACTIVO);
}else{
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ha ocurrido un error inhabilitando el usuario, por favor intentelo de nuevo más tarde.");
}
}
} catch (Exception e) {
Mensaje.mostrarMensaje(Mensaje.FATAL, "Ha ocurrido una excepción, intentelo de nuevo más tarde. Si el error persiste contacte a su administrador.");
}
}
public void reactivarUsuario(){
try {
if(this.usuarioSeleccionado!=null){
boolean result = ejbUsuarios.cambiarEstadoDeUsuario(usuarioSeleccionado.getId_usuario(), Usuario.ESTADO_ACTIVO);
if(result){
Mensaje.mostrarMensaje(Mensaje.INFO, "Se re-activó el usuario correctamente.");
limpiar();
cargarListaUsuarios(Usuario.ESTADO_INACTIVO);
}else{
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ha ocurrido un error re-activando el usuario, por favor intentelo de nuevo más tarde.");
}
}
} catch (Exception e) {
Mensaje.mostrarMensaje(Mensaje.FATAL, "Ha ocurrido una excepción, intentelo de nuevo más tarde. Si el error persiste contacte a su administrador.");
}
}
public void cambiarPassword(){
try {
if(this.usuarioSeleccionado!=null && this.usuarioSeleccionado.getId_usuario()!=0 && !Util.isEmpty(this.usuarioSeleccionado.getLogin())){
//Validar contraseñas
if(Util.isEmpty(pass) || Util.isEmpty(confirmarPass)){
Mensaje.mostrarMensaje(Mensaje.WARN, "No pueden haber campos vacíos.");
}else{
//Comparar si las contraseñas son iguales
if(pass.equals(confirmarPass)){
String encPass = Util.encriptarPass(this.usuarioSeleccionado.getLogin(), this.pass);
this.usuarioSeleccionado.setContraseña(encPass);
boolean resultado = ejbUsuarios.cambiarPassword(usuarioSeleccionado);
if(resultado){
Mensaje.mostrarMensaje(Mensaje.INFO, "Se cambió la contraseña correctamente.");
}else{
Mensaje.mostrarMensaje(Mensaje.ERROR, "Ha ocurrido un error cambiando la contraseña, por favor intente de nuevo.");
}
}else{
Mensaje.mostrarMensaje(Mensaje.WARN, "Las contraseñas no coinciden, intentelo de nuevo.");
}
}
}
limpiar();
cargarListaUsuarios(Usuario.ESTADO_ACTIVO);
} catch (Exception e) {
e.printStackTrace();
}
}
/*Get & Set*/
public SesionBean getSesionBean() {
return sesionBean;
}
public void setSesionBean(SesionBean sesionBean) {
this.sesionBean = sesionBean;
}
public List<Rol> getListaRoles() {
return listaRoles;
}
public void setListaRoles(List<Rol> listaRoles) {
this.listaRoles = listaRoles;
}
public List<Usuario> getListaUsuarios() {
return listaUsuarios;
}
public void setListaUsuarios(List<Usuario> listaUsuarios) {
this.listaUsuarios = listaUsuarios;
}
public Usuario getUsuarioSeleccionado() {
return usuarioSeleccionado;
}
public void setUsuarioSeleccionado(Usuario usuarioSeleccionado) {
this.usuarioSeleccionado = usuarioSeleccionado;
if(this.usuarioSeleccionado.getRols()!=null){
StringBuilder nombresRoles = new StringBuilder();
for (Rol rol : this.usuarioSeleccionado.getRols()) {
if(nombresRoles.length() != 0){
nombresRoles.append(",");
}
nombresRoles.append( rol.getNombre_Rol() );
}
this.rolesSeleccionadosMod = nombresRoles.toString();
}
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getGenero() {
return genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getFiltroNombre() {
return filtroNombre;
}
public void setFiltroNombre(String filtroNombre) {
this.filtroNombre = filtroNombre;
}
public String getFiltroEstado() {
return filtroEstado;
}
public void setFiltroEstado(String filtroEstado) {
this.filtroEstado = filtroEstado;
}
public String getRolesSeleccionados() {
return rolesSeleccionados;
}
public void setRolesSeleccionados(String rolesSeleccionados) {
this.rolesSeleccionados = rolesSeleccionados;
}
public String getRolesSeleccionadosMod() {
return rolesSeleccionadosMod;
}
public void setRolesSeleccionadosMod(String rolesSeleccionadosMod) {
this.rolesSeleccionadosMod = rolesSeleccionadosMod;
}
public String getConfirmarPass() {
return confirmarPass;
}
public void setConfirmarPass(String confirmarPass) {
this.confirmarPass = confirmarPass;
}
}
|
package org.ingue.jpa.domain;
import lombok.*;
import org.ingue.jpa.domain.member.Member;
import org.ingue.jpa.domain.support.CreatedAndModifiedEntity;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "member_chatroom_mapping")
@Getter
@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class MemberChatroomMapping extends CreatedAndModifiedEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long memberChatroomId;
private String chatroomName;
private LocalDateTime joinAt;
@ManyToOne
@JoinColumn(name = "memberId")
private Member member;
@ManyToOne
@JoinColumn(name = "chatroomId")
private Chatroom chatroom;
}
|
package ru.timxmur.test.tochka.domain;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Setter
@Getter
public class NewsSourceForm {
@NotEmpty
private String name;
@NotEmpty
private String uri;
@NotNull
private NewsSourceTypeEnum type=NewsSourceTypeEnum.RSS;
private String topElement="";
private String topElementType="";
private String titleRule="";
private String titleType="";
private String contentType="";
private String urlType="";
private String contentRule="";
private String urlRule="";
}
|
package com.wxt.designpattern.abstractfactory.nodp;
/**
* @Auther: weixiaotao
* @ClassName MainboardApi
* @Date: 2018/10/22 20:46
* @Description:主板的接口
*/
public interface MainboardApi {
/**
* 示意方法,主板都具有安装CPU的功能
*/
void installCPU();
}
|
package dataModels;
import java.util.List;
public class Office {
private int officeNumber;
private Address address;
private int phoneNumber;
private List<Car> cars;
public int getOfficeNumber() {
return officeNumber;
}
public void setOfficeNumber(int officeNumber) {
this.officeNumber = officeNumber;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
|
/*
* 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 DAO;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import model.Question;
import model.User;
/**
*
* @author bako
*/
public interface QuestionDAO {
public List getAll() throws SQLException;
public Question create(Question question)throws SQLException;
public Question update(Question question) throws SQLException;
public boolean remove(Question question) throws SQLException;
public Question findById(int id) throws SQLException;
public Question findById(String id) throws SQLException;
}
|
package br.com.zolp.estudozolp.service.impl;
import br.com.zolp.estudozolp.bean.AuditoriaEstudo;
import br.com.zolp.estudozolp.bean.SaidaEstudo;
import br.com.zolp.estudozolp.bean.UnidadePesquisa;
import br.com.zolp.estudozolp.bean.filtro.FiltroConsultaAuditoria;
import br.com.zolp.estudozolp.bean.filtro.FiltroSaidaEstudo;
import br.com.zolp.estudozolp.bean.filtro.FiltroUnidadePesquisa;
import br.com.zolp.estudozolp.converters.*;
import br.com.zolp.estudozolp.entity.TbAuditoriaEstudo;
import br.com.zolp.estudozolp.entity.TbSaidaEstudo;
import br.com.zolp.estudozolp.entity.TbUnidadePesquisa;
import br.com.zolp.estudozolp.exception.EstudoZolpException;
import br.com.zolp.estudozolp.exception.PersistenciaException;
import br.com.zolp.estudozolp.exception.RegistroNaoLocalizadoException;
import br.com.zolp.estudozolp.log.LogManager;
import br.com.zolp.estudozolp.repository.AuditoriaEstudoRepository;
import br.com.zolp.estudozolp.repository.SaidaEstudoRepository;
import br.com.zolp.estudozolp.repository.UnidadePesquisaRepository;
import br.com.zolp.estudozolp.service.EstudoZolpService;
import br.com.zolp.estudozolp.types.TipoLog;
import br.com.zolp.estudozolp.util.Eval;
import org.slf4j.event.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Classe responsavel pela implementacao das operacoes de persistencia no Banco de Dados
* das informações referente a auditoria, unidadePesquisa, saida estudo.
*
* @author mamede
* @version 0.0.1-SNAPSHOT
*/
@Service
@Transactional
public class EstudoZolpServiceImpl implements EstudoZolpService {
@Autowired
private AuditoriaEstudoRepository auditoriaEstudoRepository;
@Autowired
private AuditoriaEstudoToBean auditoriaEstudoToBean;
@Autowired
private AuditoriaEstudoToEntity auditoriaEstudoToEntity;
@Autowired
private UnidadePesquisaRepository unidadePesquisaRepository;
@Autowired
private UnidadePesquisaToBean unidadePesquisaToBean;
@Autowired
private UnidadePesquisaToEntity unidadePesquisaToEntity;
@Autowired
private SaidaEstudoRepository saidaEstudoRepository;
@Autowired
private SaidaEstudoToBean saidaEstudoToBean;
@Autowired
private SaidaEstudoToEntity saidaEstudoToEntity;
@PersistenceContext
private EntityManager entityManager;
// --- QUERIES SQL --------------------------------------------------------
// Query
private static final String
// Query
SQL_SELECT_XPTO = " SELECT "
+ " FROM XPTO "
+ "WHERE 1=1 ",
// Condicoes incrementais da clausula WHERE:
AND_XPTO = " AND XPTO = ",
AND_XPTO_1 = " AND XPTO_1 = ",
// Ordenacao
SQL_ORDER_BY = " ORDER BY XPTO ";
// --- CADASTRO DE AUDITORIA ------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public AuditoriaEstudo obterAuditoria(Long idAuditoriaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "obterAuditoria");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "obterAuditoria",
" Efetuando a consulta [ idAuditoriaEstudo: " + idAuditoriaEstudo + " ].");
// Busca o registro
Optional<TbAuditoriaEstudo> retorno;
try {
retorno = auditoriaEstudoRepository.findById(idAuditoriaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterAuditoria",
" Erro ao efetuar a consulta das informações. ", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacaoes.", e);
}
// Converte o entity
AuditoriaEstudo auditoriaEstudo = null;
if (retorno.isPresent()) {
try {
auditoriaEstudo = auditoriaEstudoToBean.convert(retorno.get());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterAuditoria",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados.");
}
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "obterAuditoria");
return auditoriaEstudo;
}
/**
* {@inheritDoc}
*/
@Override
public List<AuditoriaEstudo> consultarAuditoria(FiltroConsultaAuditoria filtro) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "consultarAuditoria");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "consultarAuditoria",
" Efetuando a consulta [ " + filtro + " ].");
// Valida se o filtro foi preenchido
if (Eval.isNull(filtro) || Eval.isAllEmpty(filtro.getId(), filtro.getDescricao())) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarAuditoria",
" Nenhum dado informado nos filtros.");
throw new EstudoZolpException("Nenhum dado informado nos filtros.");
}
// Busca os registros de auditoria
final List<AuditoriaEstudo> listaAuditoria = new ArrayList<>();
// Monta comando SQL
final StringBuilder sqlSelect = new StringBuilder(SQL_SELECT_XPTO);
if (Eval.isNotEmpty(filtro.getDescricao())) {
sqlSelect.append(AND_XPTO)
.append(filtro.getDescricao());
}
sqlSelect.append(SQL_ORDER_BY);
// Executa a consulta SQL
try {
final Query query = entityManager.createNativeQuery(sqlSelect.toString());
((List<?>) query.getResultList())
.forEach(object -> listaAuditoria
.add(auditoriaEstudoToBean.convert((Object[]) object)));
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarAuditoria",
" Erro ao efetuar a consulta das informacoes [" + " Consulta SQL: '" + sqlSelect
+ "' ].", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "consultarAuditoria");
return listaAuditoria;
}
/**
* {@inheritDoc}
*/
@Override
public void incluirAuditoria(AuditoriaEstudo auditoriaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "incluirAuditoria");
// Remove o Id para que o mesmo obtenha um novo sequencial
auditoriaEstudo.setIdAuditoriaEstudo(null);
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "incluirAuditoria",
" Dados entrada [ " + auditoriaEstudo + " ].");
TbAuditoriaEstudo tbAuditoriaEstudo;
// Efetua a conversao
try {
tbAuditoriaEstudo = auditoriaEstudoToEntity.convert(auditoriaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirAuditoria",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados [ "
+ auditoriaEstudo + " ].");
}
// Inclui na base de dados
try {
auditoriaEstudoRepository.save(tbAuditoriaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirAuditoria",
" Erro ao efetuar a inclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a inclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "incluirAuditoria");
}
/**
* {@inheritDoc}
*/
@Override
public AuditoriaEstudo alterarAuditoria(AuditoriaEstudo auditoriaEstudo) throws EstudoZolpException,
RegistroNaoLocalizadoException, PersistenciaException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "alterarAuditoria");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarAuditoria",
" Dados entrada [ " + auditoriaEstudo + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarAuditoria",
" Efetuando a consulta das informacoes de Usuario.");
// Efetua a busca
Optional<TbAuditoriaEstudo> retorno;
try {
retorno = auditoriaEstudoRepository.findById(auditoriaEstudo.getIdAuditoriaEstudo());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarAuditoria",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// Obtem a entity recuperada da base
TbAuditoriaEstudo tbAuditoriaEstudo = retorno.get();
tbAuditoriaEstudo.setUsername(auditoriaEstudo.getUsername());
tbAuditoriaEstudo.setDtModificacao(auditoriaEstudo.getDtModificacao());
tbAuditoriaEstudo.setTpModificacao(auditoriaEstudo.getTpModificacao());
tbAuditoriaEstudo.setDsModificacao(auditoriaEstudo.getDsModificacao());
tbAuditoriaEstudo.setTpEntidade(auditoriaEstudo.getTpEntidade());
tbAuditoriaEstudo.setIdPaciente(auditoriaEstudo.getIdPaciente());
// Efetiva a atualizacao (update) na base oracle
try {
auditoriaEstudoRepository.save(tbAuditoriaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarAuditoria",
" Erro ao efetuar a atualizacao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a atualizacao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "alterarAuditoria");
return auditoriaEstudoToBean.convert(tbAuditoriaEstudo);
}
@Override
public void excluirAuditoria(Long idAuditoriaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "excluirAuditoria");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirAuditoria",
" Dados entrada [ " + idAuditoriaEstudo + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirAuditoria",
" Efetuando a consulta das informacoes.");
Optional<TbAuditoriaEstudo> retorno;
try {
retorno = auditoriaEstudoRepository.findById(idAuditoriaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirAuditoria",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// Obtem informacao da base
TbAuditoriaEstudo auditoriaCadastrada = retorno.get();
// Efetiva a exclusao do usuario
try {
auditoriaEstudoRepository.delete(auditoriaCadastrada);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirAuditoria",
" Erro ao efetuar a exclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a exclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "excluirAuditoria");
}
// --- CADASTRO DE UNIDADE DE PESQUISA ------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public UnidadePesquisa obterUnidadePesquisa(Long idUnidadePesquisa) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "obterUnidadePesquisa");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "obterUnidadePesquisa",
" Efetuando a consulta [ idUnidadePesquisa: " + idUnidadePesquisa + " ].");
// Busca o registro
Optional<TbUnidadePesquisa> retorno;
try {
retorno = unidadePesquisaRepository.findById(idUnidadePesquisa);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterUnidadePesquisa",
" Erro ao efetuar a consulta das informações. ", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacaoes.", e);
}
// Converte o entity
UnidadePesquisa unidadePesquisa = null;
if (retorno.isPresent()) {
try {
unidadePesquisa = unidadePesquisaToBean.convert(retorno.get());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterUnidadePesquisa",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados.");
}
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "obterUnidadePesquisa");
return unidadePesquisa;
}
/**
* {@inheritDoc}
*/
@Override
public List<UnidadePesquisa> consultarUnidadePesquisa(FiltroUnidadePesquisa filtro) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "consultarUnidadePesquisa");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "consultarUnidadePesquisa",
" Efetuando a consulta [ " + filtro + " ].");
// Valida se o filtro foi preenchido
if (Eval.isNull(filtro) || Eval.isAllEmpty(filtro.getId(), filtro.getDescricao())) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarUnidadePesquisa",
" Nenhum dado informado nos filtros.");
throw new EstudoZolpException("Nenhum dado informado nos filtros.");
}
// Busca os registros de usuario
final List<UnidadePesquisa> listUnidadePesquisa = new ArrayList<>();
// Monta comando SQL
final StringBuilder sqlSelect = new StringBuilder(SQL_SELECT_XPTO);
if (Eval.isNotEmpty(filtro.getDescricao())) {
sqlSelect.append(AND_XPTO)
.append(filtro.getDescricao());
}
sqlSelect.append(SQL_ORDER_BY);
// Executa a consulta SQL
try {
final Query query = entityManager.createNativeQuery(sqlSelect.toString());
((List<?>) query.getResultList())
.forEach(object -> listUnidadePesquisa
.add(unidadePesquisaToBean.convert((Object[]) object)));
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarUnidadePesquisa",
" Erro ao efetuar a consulta das informacoes [" + " Consulta SQL: '" + sqlSelect
+ "' ].", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "consultarUnidadePesquisa");
return listUnidadePesquisa;
}
/**
* {@inheritDoc}
*/
@Override
public void incluirUnidadePesquisa(UnidadePesquisa unidadePesquisa) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "incluirUnidadePesquisa");
// Remove o Id para que o mesmo obtenha um novo sequencial
unidadePesquisa.setIdUnidadePesquisa(null);
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "incluirUnidadePesquisa",
" Dados entrada [ " + unidadePesquisa + " ].");
TbUnidadePesquisa tbUnidadePesquisa;
// Efetua a conversao
try {
tbUnidadePesquisa = unidadePesquisaToEntity.convert(unidadePesquisa);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirUnidadePesquisa",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados [ "
+ unidadePesquisa + " ].");
}
// Inclui na base de dados
try {
unidadePesquisaRepository.save(tbUnidadePesquisa);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirUnidadePesquisa",
" Erro ao efetuar a inclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a inclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "incluirUnidadePesquisa");
}
/**
* {@inheritDoc}
*/
@Override
public UnidadePesquisa alterarUnidadePesquisa(UnidadePesquisa unidadePesquisa) throws EstudoZolpException,
RegistroNaoLocalizadoException, PersistenciaException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa",
" Dados entrada [ " + unidadePesquisa + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa",
" Efetuando a consulta das informacoes.");
// Efetua a busca do usuario
Optional<TbUnidadePesquisa> retorno;
try {
retorno = unidadePesquisaRepository.findById(unidadePesquisa.getIdUnidadePesquisa());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// obtem a entity recuperada da base,
TbUnidadePesquisa tbUnidadePesquisa = retorno.get();
tbUnidadePesquisa.setDsUnidade(unidadePesquisa.getDsUnidade());
tbUnidadePesquisa.setSiglaUnidade(unidadePesquisa.getSiglaUnidade());
tbUnidadePesquisa.setTelUnidade(unidadePesquisa.getTelUnidade());
tbUnidadePesquisa.setEndereco(unidadePesquisa.getEndereco());
tbUnidadePesquisa.setCidade(unidadePesquisa.getCidade());
tbUnidadePesquisa.setUf(unidadePesquisa.getUf());
tbUnidadePesquisa.setCep(unidadePesquisa.getCep());
tbUnidadePesquisa.setInvestigador(unidadePesquisa.getInvestigador());
tbUnidadePesquisa.setCoordenador(unidadePesquisa.getCoordenador());
tbUnidadePesquisa.setEmail(unidadePesquisa.getEmail());
tbUnidadePesquisa.setNuUnidade(unidadePesquisa.getNuUnidade());
// Efetiva a atualizacao (update) na base oracle
try {
unidadePesquisaRepository.save(tbUnidadePesquisa);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa",
" Erro ao efetuar a atualizacao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a atualizacao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "alterarUnidadePesquisa");
return unidadePesquisaToBean.convert(tbUnidadePesquisa);
}
/**
* {@inheritDoc}
*/
@Override
public void excluirUnidadePesquisa(Long idUnidadePesquisa) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa",
" Dados entrada [ " + idUnidadePesquisa + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa",
" Efetuando a consulta das informacoes.");
Optional<TbUnidadePesquisa> retorno;
try {
retorno = unidadePesquisaRepository.findById(idUnidadePesquisa);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// Obtem informacao da base
TbUnidadePesquisa unidadePesquisaCadastrada = retorno.get();
// Efetiva a exclusao do usuario
try {
unidadePesquisaRepository.delete(unidadePesquisaCadastrada);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa",
" Erro ao efetuar a exclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a exclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "excluirUnidadePesquisa");
}
// --- CADASTRO DE SAIDA ESTUDO ------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public SaidaEstudo obterSaidaEstudo(Long idSaidaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "obterSaidaEstudo");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "obterSaidaEstudo",
" Efetuando a consulta [ idSaidaEstudo: " + idSaidaEstudo + " ].");
// Busca o registro
Optional<TbSaidaEstudo> retorno;
try {
retorno = saidaEstudoRepository.findById(idSaidaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterSaidaEstudo",
" Erro ao efetuar a consulta das informações. ", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacaoes.", e);
}
// Converte o entity
SaidaEstudo saidaEstudo = null;
if (retorno.isPresent()) {
try {
saidaEstudo = saidaEstudoToBean.convert(retorno.get());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "obterSaidaEstudo",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados.");
}
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "obterSaidaEstudo");
return saidaEstudo;
}
/**
* {@inheritDoc}
*/
@Override
public List<SaidaEstudo> consultarSaidaEstudo(FiltroSaidaEstudo filtro) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "consultarSaidaEstudo");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "consultarSaidaEstudo",
" Efetuando a consulta [ " + filtro + " ].");
// Valida se o filtro foi preenchido
if (Eval.isNull(filtro) || Eval.isAllEmpty(filtro.getId(), filtro.getDescricao())) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarSaidaEstudo",
" Nenhum dado informado nos filtros.");
throw new EstudoZolpException("Nenhum dado informado nos filtros.");
}
// Busca os registros de usuario
final List<SaidaEstudo> saidaEstudos = new ArrayList<>();
// Monta comando SQL
final StringBuilder sqlSelect = new StringBuilder(SQL_SELECT_XPTO);
if (Eval.isNotEmpty(filtro.getDescricao())) {
sqlSelect.append(AND_XPTO)
.append(filtro.getDescricao());
}
sqlSelect.append(SQL_ORDER_BY);
// Executa a consulta SQL
try {
final Query query = entityManager.createNativeQuery(sqlSelect.toString());
((List<?>) query.getResultList())
.forEach(object -> saidaEstudos
.add(saidaEstudoToBean.convert((Object[]) object)));
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "consultarSaidaEstudo",
" Erro ao efetuar a consulta das informacoes [" + " Consulta SQL: '" + sqlSelect
+ "' ].", e);
throw new PersistenciaException("Erro ao efetuar a consulta das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "consultarSaidaEstudo");
return saidaEstudos;
}
/**
* {@inheritDoc}
*/
@Override
public void incluirSaidaEstudo(SaidaEstudo saidaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "incluirSaidaEstudo");
// Remove o Id para que o mesmo obtenha um novo sequencial
saidaEstudo.setIdSaidaEstudo(null);
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "incluirSaidaEstudo",
" Dados entrada [ " + saidaEstudo + " ].");
TbSaidaEstudo tbSaidaEstudo;
// Efetua a conversao
try {
tbSaidaEstudo = saidaEstudoToEntity.convert(saidaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirSaidaEstudo",
" Erro ao efetuar a conversao dos dados.", e);
throw new EstudoZolpException("Erro ao efetuar a conversao dos dados [ "
+ saidaEstudo + " ].");
}
// Inclui na base de dados
try {
saidaEstudoRepository.save(tbSaidaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "incluirSaidaEstudo",
" Erro ao efetuar a inclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a inclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "incluirSaidaEstudo");
}
/**
* {@inheritDoc}
*/
@Override
public SaidaEstudo alterarSaidaEstudo(SaidaEstudo saidaEstudo) throws EstudoZolpException,
RegistroNaoLocalizadoException, PersistenciaException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "alterarSaidaEstudo");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarSaidaEstudo",
" Dados entrada [ " + saidaEstudo + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "alterarSaidaEstudo",
" Efetuando a consulta das informacoes.");
// Efetua a busca do usuario
Optional<TbSaidaEstudo> retorno;
try {
retorno = saidaEstudoRepository.findById(saidaEstudo.getIdSaidaEstudo());
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarSaidaEstudo",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// obtem a entity recuperada da base,
TbSaidaEstudo tbSaidaEstudo = retorno.get();
tbSaidaEstudo.setIdPaciente(saidaEstudo.getIdPaciente());
tbSaidaEstudo.setDtInclusao(saidaEstudo.getDtInclusao());
tbSaidaEstudo.setNuVisita(saidaEstudo.getNuVisita());
tbSaidaEstudo.setDtSaida(saidaEstudo.getDtSaida());
tbSaidaEstudo.setDtOcorrencia(saidaEstudo.getDtOcorrencia());
tbSaidaEstudo.setMotivo(saidaEstudo.getMotivo());
tbSaidaEstudo.setFlEvolucaoObito(saidaEstudo.getFlEvolucaoObito());
tbSaidaEstudo.setStAprovacao(saidaEstudo.getStAprovacao());
tbSaidaEstudo.setAssinatura(saidaEstudo.getAssinatura());
tbSaidaEstudo.setDtAssinatura(saidaEstudo.getDtAssinatura());
tbSaidaEstudo.setObservacao(saidaEstudo.getObservacao());
// Efetiva a atualizacao (update) na base oracle
try {
saidaEstudoRepository.save(tbSaidaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "alterarSaidaEstudo",
" Erro ao efetuar a atualizacao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a atualizacao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "alterarSaidaEstudo");
return saidaEstudoToBean.convert(tbSaidaEstudo);
}
/**
* {@inheritDoc}
*/
@Override
public void excluirSaidaEstudo(Long idSaidaEstudo) throws EstudoZolpException {
// Logging de entrada
LogManager.log(Level.INFO, TipoLog.ENTRADA, EstudoZolpServiceImpl.class, "excluirSaidaEstudo");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirSaidaEstudo",
" Dados entrada [ " + idSaidaEstudo + " ].");
LogManager.logDetalhe(Level.INFO, EstudoZolpServiceImpl.class, "excluirSaidaEstudo",
" Efetuando a consulta das informacoes.");
Optional<TbSaidaEstudo> retorno;
try {
retorno = saidaEstudoRepository.findById(idSaidaEstudo);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirSaidaEstudo",
" Erro ao verificar a existencia do registro.", e);
throw new PersistenciaException("Erro ao verificar a existencia do registro.", e);
}
if (!retorno.isPresent()) {
throw new RegistroNaoLocalizadoException("O registro nao foi localizado na base de dados.");
}
// Obtem informacao da base
TbSaidaEstudo saidaEstudoCadastrado = retorno.get();
// Efetiva a exclusao do usuario
try {
saidaEstudoRepository.delete(saidaEstudoCadastrado);
} catch (Exception e) {
LogManager.logDetalhe(Level.ERROR, EstudoZolpServiceImpl.class, "excluirSaidaEstudo",
" Erro ao efetuar a exclusao das informacoes.", e);
throw new PersistenciaException("Erro ao efetuar a exclusao das informacoes.", e);
}
// Logging de saida
LogManager.log(Level.INFO, TipoLog.SAIDA, EstudoZolpServiceImpl.class, "excluirSaidaEstudo");
}
}
|
/* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ==================================================================== *
*/
package com.aof.webapp.action.prm.expense;
import java.sql.SQLException;
import java.util.Locale;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.*;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import com.aof.util.UtilDateTime;
import com.aof.webapp.action.ActionErrorLog;
import com.aof.webapp.action.BaseAction;
import com.aof.component.prm.project.*;
import com.aof.component.prm.util.EmailService;
import com.aof.component.domain.party.*;
import com.aof.component.prm.expense.*;
import com.aof.core.persistence.hibernate.Hibernate2Session;
/**
* @author xxp
* @version 2003-7-2
*
*/
public class EditExpenseAction extends BaseAction {
protected ActionErrors errors = new ActionErrors();
protected ActionErrorLog actionDebug = new ActionErrorLog();
private boolean mailFlag = false;
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// Extract attributes we will need
ActionErrors errors = this.getActionErrors(request.getSession());
Logger log = Logger.getLogger(EditExpenseAction.class.getName());
Locale locale = getLocale(request);
MessageResources messages = getResources();
SimpleDateFormat Date_formater = new SimpleDateFormat("yyyy-MM-dd");
String FormStatus = request.getParameter("FormStatus");
String ClaimType = request.getParameter("ClaimType");
String action = request.getParameter("FormAction");
String ExpenseCurrency = request.getParameter("ExpenseCurrency");
String CurrencyRate = request.getParameter("CurrencyRate");
if (FormStatus == null)
FormStatus = "Draft";
if (ClaimType == null)
ClaimType = "CN";
if (action == null)
action = "view";
if (ExpenseCurrency == null)
ExpenseCurrency = "RMB";
if (CurrencyRate == null)
CurrencyRate = "0";
if (!isTokenValid(request)) {
if (action.equals("create") || action.equals("update")) {
return (mapping.findForward("list"));
}
}
saveToken(request);
try {
String DataId = request.getParameter("DataId");
net.sf.hibernate.Session hs = Hibernate2Session.currentSession();
Transaction tx = null;
Query q = null;
if (action.equals("update")) {
if ((DataId == null) || (DataId.length() < 1))
actionDebug
.addGlobalError(errors, "error.context.required");
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
try {
tx = hs.beginTransaction();
ExpenseMaster findmaster = (ExpenseMaster) hs.load(
ExpenseMaster.class, new Long(DataId));
if (findmaster.getApprovalDate() == null) {
// if (!findmaster.getStatus().equals("Approved")) {
String ExpType[] = request
.getParameterValues("ExpType");
String DateId[] = request.getParameterValues("DateId");
if (ExpType != null && DateId != null) {
int RowSize = java.lang.reflect.Array
.getLength(DateId);
int ColSize = java.lang.reflect.Array
.getLength(ExpType);
float AmtValue[] = new float[ColSize];
for (int j = 0; j < ColSize; j++) {
AmtValue[j] = 0;
}
ExpenseDetail ed = null;
for (int i = 0; i < RowSize; i++) {
String RecId[] = request
.getParameterValues("RecId" + i);
String RecordVal[] = request
.getParameterValues("RecordVal" + i);
for (int j = 0; j < ColSize; j++) {
if (RecId[j].trim().equals("")) {
// Create a new Record
if (!(new Float(RecordVal[j])
.floatValue() == 0)) {
ed = new ExpenseDetail();
Date ExpenseDate = UtilDateTime
.toDate2(DateId[i]
+ " 00:00:00.000");
ed.setExpenseDate(ExpenseDate);
ed.setUserAmount((new Float(
RecordVal[j])));
AmtValue[j] = AmtValue[j]
+ (new Float(RecordVal[j])
.floatValue());
ExpenseType eType = (ExpenseType) hs
.load(ExpenseType.class,
new Integer(
ExpType[j]));
ed.setExpType(eType);
ed.setExpMaster(findmaster);
hs.save(ed);
}
} else {
// Update Record
ed = (ExpenseDetail) hs.load(
ExpenseDetail.class, new Long(
RecId[j]));
Date ExpenseDate = UtilDateTime
.toDate2(DateId[i]
+ " 00:00:00.000");
ed.setExpenseDate(ExpenseDate);
ed.setUserAmount((new Float(
RecordVal[j])));
AmtValue[j] = AmtValue[j]
+ (new Float(RecordVal[j])
.floatValue());
ExpenseType eType = (ExpenseType) hs
.load(ExpenseType.class,
new Integer(ExpType[j]));
ed.setExpType(eType);
ed.setExpMaster(findmaster);
hs.update(ed);
}
}
// Update Comments table
String CmtRecId = request
.getParameter("CmtRecId" + i);
String CmtVal = request.getParameter("CmtVal"
+ i);
if (CmtRecId.trim().equals("")) {
if (!CmtVal.trim().equals("")) {
ExpenseComments ec = new ExpenseComments();
ec.setComments(CmtVal);
Date ExpenseDate = UtilDateTime
.toDate2(DateId[i]
+ " 00:00:00.000");
ec.setExpenseDate(ExpenseDate);
ec.setExpMaster(findmaster);
hs.save(ec);
}
} else {
ExpenseComments ec = (ExpenseComments) hs
.load(ExpenseComments.class,
new Long(CmtRecId));
ec.setComments(CmtVal);
hs.update(ec);
}
}
// Update the Amount summary table
ArrayList al = new ArrayList();
if (findmaster.getProject().getExpenseTypes() != null) {
Iterator itr = findmaster.getProject()
.getExpenseTypes().iterator();
while (itr.hasNext()) {
ExpenseType expType = (ExpenseType) itr
.next();
al.add(expType.getExpId());
}
}
if (findmaster.getAmounts().size() == 0) {
List expList = this.getAllExpenseType();
for (int j = 0; j < ColSize; j++) {
ExpenseType eType = (ExpenseType) hs.load(
ExpenseType.class, new Integer(
ExpType[j]));
if(expList.indexOf(eType)>-1)
expList.remove(eType);
ExpenseAmount ea = new ExpenseAmount();
if (eType.getExpAccDesc().equalsIgnoreCase(
"CN")
&& ClaimType.equals("CY")) {
ea.setUserAmount(new Float(0));
} else {
ea
.setUserAmount(new Float(
AmtValue[j]));
}
ea.setExpType(eType);
ea.setExpMaster(findmaster);
hs.save(ea);
}
} else {
Iterator amt = findmaster.getAmounts()
.iterator();
List expList = this.getAllExpenseType();
Iterator expit = expList.iterator();
ExpenseType tempType = null;
if (expit.hasNext())
tempType = (ExpenseType) expit.next();
while (amt.hasNext()) {
ExpenseAmount ea = (ExpenseAmount) amt
.next();
if (ClaimType.equals("CY")
&& (ea.getExpMaster()
.getClaimType()
.equals("CN"))) {
if (al.contains(ea.getExpType()
.getExpId())) {
int tempCol = -1;
for (int x = 0; x < ExpType.length; x++) {
if (Integer
.parseInt(ExpType[x]) == ea
.getExpType()
.getExpId().intValue())
tempCol = x;
}
if (tempCol != -1)
ea.setUserAmount(new Float(
AmtValue[tempCol]));
else
ea.setUserAmount(new Float(0));
hs.update(ea);
} else {
if (ea.getExpType().getExpAccDesc()
.equalsIgnoreCase("CN"))
hs.delete(ea);
else {
ea.setUserAmount(new Float(0));
hs.update(ea);
}
}
Iterator ied = ea.getExpMaster()
.getDetails().iterator();
while (ied.hasNext()) {
ExpenseDetail edt = (ExpenseDetail) ied
.next();
if (edt.getExpType()
.getExpAccDesc()
.equalsIgnoreCase("CN")
|| !al.contains(edt
.getExpType()
.getExpId())) {
hs.delete(edt);
}
}
} else if (ClaimType.equals("CN")
&& (ea.getExpMaster()
.getClaimType()
.equals("CY"))) {
int index = expList.indexOf(ea.getExpType());
if(index>-1)
expList.remove(index);
} else {
if (AmtValue.length == 5) {
if (ea.getExpType().getExpId()
.intValue() == 1)
ea.setUserAmount(new Float(
AmtValue[0]));
else if (ea.getExpType().getExpId()
.intValue() == 2)
ea.setUserAmount(new Float(
AmtValue[1]));
else if (ea.getExpType().getExpId()
.intValue() == 3)
ea.setUserAmount(new Float(
AmtValue[2]));
else if (ea.getExpType().getExpId()
.intValue() == 4) {
// hs.delete(ea);
ea.setUserAmount(new Float(0));
} else if (ea.getExpType()
.getExpId().intValue() == 5) {
ea.setUserAmount(new Float(
AmtValue[3]));
} else if (ea.getExpType()
.getExpId().intValue() == 6) {
ea.setUserAmount(new Float(
AmtValue[4]));
} else
// hs.delete(ea);
ea.setUserAmount(new Float(0));
} else {
int tempCol = -1;
for (int x = 0; x < ExpType.length; x++) {
if (Integer
.parseInt(ExpType[x]) == ea
.getExpType()
.getExpId().intValue())
tempCol = x;
}
if (tempCol != -1)
ea.setUserAmount(new Float(
AmtValue[tempCol]));
else
ea.setUserAmount(new Float(0));
}
hs.update(ea);
}
}
if(ClaimType.equals("CN")
&& (findmaster.getClaimType()
.equals("CY")))
{
expit = expList.iterator();
while(expit.hasNext())
{
tempType = (ExpenseType) expit.next();
ExpenseAmount expamount = new ExpenseAmount();
expamount.setExpType(tempType);
expamount
.setUserAmount(new Float(
0));
expamount
.setExpMaster(findmaster);
hs.save(expamount);
}
}
}
}
if (findmaster.getStatus().equals("Draft")
|| findmaster.getStatus().equals("Rejected"))
mailFlag = true;
if (!findmaster.getStatus().equals("Verified")) {
findmaster.setStatus(FormStatus);
}
findmaster.setClaimType(ClaimType);
if (FormStatus.equals("Submitted"))
mailFlag = true;
CurrencyType ct = (CurrencyType) hs.load(
CurrencyType.class, ExpenseCurrency);
findmaster.setExpenseCurrency(ct);
findmaster.setCurrencyRate(new Float(CurrencyRate));
hs.update(findmaster);
tx.commit();
hs.flush();
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
if (action.equals("create")) {
try {
tx = hs.beginTransaction();
ExpenseMaster findmaster = new ExpenseMaster();
String projectCode = request.getParameter("projId");
String DataPeriod = request.getParameter("DataPeriod");
String UserId = request.getParameter("UserId");
if (projectCode == null)
projectCode = "";
if (DataPeriod == null)
DataPeriod = Date_formater.format(UtilDateTime
.nowTimestamp());
if (UserId == null)
UserId = "";
ProjectMaster projectMaster = (ProjectMaster) hs.load(
ProjectMaster.class, projectCode);
findmaster.setProject(projectMaster);
UserLogin ul = (UserLogin) hs.load(UserLogin.class, UserId);
findmaster.setExpenseUser(ul);
findmaster.setClaimType(ClaimType);
Date dayStart = UtilDateTime.toDate2(DataPeriod
+ " 00:00:00.000");
dayStart = UtilDateTime.getThisWeekDay(dayStart, 1);
findmaster.setExpenseDate(dayStart);
Date entryDate = UtilDateTime.toDate2((Date_formater
.format(UtilDateTime.nowDate()) + " 00:00:00.000"));
findmaster.setEntryDate(entryDate);
ExpenseService Service = new ExpenseService();
findmaster.setFormCode(Service.getFormNo(findmaster, hs));
CurrencyType ct = (CurrencyType) hs.load(
CurrencyType.class, ExpenseCurrency);
findmaster.setExpenseCurrency(ct);
findmaster.setCurrencyRate(new Float(CurrencyRate));
if (FormStatus.equals("Submitted"))
mailFlag = true;
findmaster.setStatus(FormStatus);
hs.save(findmaster);
tx.commit();
hs.flush();
DataId = findmaster.getId().toString();
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
if (action.equals("delete")) {
try {
tx = hs.beginTransaction();
ExpenseMaster findmaster = (ExpenseMaster) hs.load(
ExpenseMaster.class, new Long(DataId));
// if (!findmaster.getStatus().equals("Approved")) {
if (findmaster.getApprovalDate() == null) {
Iterator itdet = findmaster.getDetails().iterator();
while (itdet.hasNext()) {
ExpenseDetail ed = (ExpenseDetail) itdet.next();
hs.delete(ed);
}
itdet = findmaster.getAmounts().iterator();
while (itdet.hasNext()) {
ExpenseAmount ed = (ExpenseAmount) itdet.next();
hs.delete(ed);
}
itdet = findmaster.getComments().iterator();
while (itdet.hasNext()) {
ExpenseComments ed = (ExpenseComments) itdet.next();
hs.delete(ed);
}
hs.delete(findmaster);
}
tx.commit();
hs.flush();
return (mapping.findForward("list"));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
if (action.equals("view") || action.equals("create")
|| action.equals("update")
|| action.equals("showArAndApDetail")) {
ExpenseMaster findmaster = null;
if (!((DataId == null) || (DataId.length() < 1)))
findmaster = (ExpenseMaster) hs.load(ExpenseMaster.class,
new Long(DataId));
List detailList = null;
ArrayList DateList = new ArrayList();
if (findmaster != null) {
q = hs
.createQuery("select ed from ExpenseDetail as ed inner join ed.ExpMaster as em inner join ed.ExpType as et where em.Id =:DataId order by ed.ExpenseDate, et.expSeq ASC");
q.setParameter("DataId", DataId);
detailList = q.list();
Date dayStart = findmaster.getExpenseDate();
for (int i = 0; i < 14; i++) {
DateList.add(UtilDateTime.getDiffDay(dayStart, i));
}
request.setAttribute("FreezeFlag",
FreezeDateCheck(findmaster.getApprovalDate()));
request.setAttribute("findmaster", findmaster);
request.setAttribute("detailList", detailList);
request.setAttribute("DateList", DateList);
q = hs
.createQuery("select ec from ExpenseComments as ec inner join ec.ExpMaster as em where em.Id =:DataId order by ec.ExpenseDate");
q.setParameter("DataId", DataId);
detailList = q.list();
request.setAttribute("CommentsList", detailList);
q = hs
.createQuery("select ea from ExpenseAmount as ea inner join ea.ExpMaster as em inner join ea.ExpType as et where em.Id =:DataId order by et.expSeq ASC");
q.setParameter("DataId", DataId);
detailList = q.list();
request.setAttribute("AmountList", detailList);
}
if (action.equals("showArAndApDetail")) {
return (mapping.findForward("showArAndApDetail"));
}
if (action.equals("update") && FormStatus.equals("Submitted")
&& mailFlag) {
EmailService.notifyUser(findmaster);
mailFlag = false;
return (mapping.findForward("list"));
}
return (mapping.findForward("view"));
}
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
return (mapping.findForward("view"));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return (mapping.findForward("view"));
} finally {
try {
Hibernate2Session.closeSession();
} catch (HibernateException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
} catch (SQLException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
}
}
}
private List getAllExpenseType() {
Session hs;
List list = new ArrayList();
try {
hs = Hibernate2Session.currentSession();
Query q = hs
.createQuery("from ExpenseType as e order by e.expSeq asc");
list = q.list();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
|
package org.jscep.transaction;
import net.jcip.annotations.Immutable;
/**
* This <tt>Exception</tt> represents the situation where the <tt>Nonce</tt>
* received in a server response does not match the <tt>Nonce</tt> send in the
* client request, or where the <tt>Nonce</tt> received has been used before.
*
* @see Nonce
*/
@Immutable
public class InvalidNonceException extends TransactionException {
private static final String MISMATCH = "Nonce mismatch. Sent: %s. Receieved: %s";
private static final String REPLAY = "Nonce encountered before: %s";
private static final long serialVersionUID = 3875364340108674893L;
/**
* Constructs a new <tt>InvalidNonceException</tt> for a <tt>Nonce</tt>
* mismatch.
*
* @param sent
* the sent <tt>Nonce</tt>
* @param recd
* the received <tt>Nonce</tt>
*/
public InvalidNonceException(final Nonce sent, final Nonce recd) {
super(String.format(MISMATCH, sent, recd));
}
/**
* Constructs a new <tt>InvalidNonceException</tt> for a replayed
* <tt>Nonce</tt>
*
* @param nonce
* the replayed <tt>Nonce</tt>.
*/
public InvalidNonceException(final Nonce nonce) {
super(String.format(REPLAY, nonce));
}
}
|
package view;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/**
*
* @author Guillaume Woreth, Luca Borruto, Ahmed Ben Mbarek
*
*/
public class Panel extends JPanel {
private static final long serialVersionUID = 1L;
public int size = 32;
public int arrayx = 20;
public int arrayy = 12;
public BufferedImage img[][] = new BufferedImage[arrayx][arrayy];
public static Lorann lorann1 = new Lorann();
public static int erasex[][] = new int[20][12];
public static int erasey[][] = new int[20][12];
public Panel() {
}
public void paintComponent(Graphics g) {
/**
* Load all the sprite on the map and display them at their own coordinate
*/
if (Window.debut == 1) {
for (int x1 = 0; x1 < arrayx; x1++) {
for (int y1 = 0; y1 < arrayy; y1++) {
g.drawImage(img[x1][y1], x1 * size, y1 * size, null);
}
}
}
repaint();
}
}
|
package ch03;
import java.util.*;
public class Ch03_04_Minju {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("n과 k를 각각 입력하세요. ");
int n = scn.nextInt();
int k = scn.nextInt();
int count = 0;
int x;
if(n%k == 0) {
x = n/k;
count++;
if(x != 1) {
}
} else {
x = n-1;
}
}
}
|
package com.prangbi.android.prfilelist;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private static final String ROOT_PATH = "/";
/**
* Layout.
*/
private Toast toast = null;
private Button rootBtn = null;
private Button sdCardBtn = null;
private ListView listView = null;
/**
* Variable.
*/
private String currentPath = null;
private List<String> fileNames = new ArrayList<String>();
private boolean startedFromSdcard = false;
/**
* Lifecycle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fileNames);
rootBtn = (Button)findViewById(R.id.rootBtn);
rootBtn.setOnClickListener(onClickListener);
sdCardBtn = (Button)findViewById(R.id.sdCardBtn);
sdCardBtn.setOnClickListener(onClickListener);
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(onItemClickListener);
moveToRoot();
}
/**
* Event.
*/
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int viewId = v.getId();
switch(viewId) {
case R.id.rootBtn:
moveToRoot();
break;
case R.id.sdCardBtn:
moveToSdCard();
break;
}
}
};
private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String fileName = fileNames.get(position);
clickedFileName(fileName);
}
};
private void clickedFileName(String fileName) {
if(true != fileName.endsWith("/")) {
showToast("This is a file.");
return;
}
fileName = fileName.substring(0, fileName.length()-1);
String filePath = null;
if(true == fileName.equals("..")) {
int lastIndexOf = currentPath.lastIndexOf("/");
if(0 == lastIndexOf) {
filePath = ROOT_PATH;
} else {
filePath = currentPath.substring(0, currentPath.lastIndexOf("/"));
}
} else {
filePath = (true == currentPath.equals(ROOT_PATH) ? "" : currentPath) + "/" + fileName;
}
File f = new File(filePath);
if(null == f || false == f.canRead()) {
showToast("Can't open the directory.");
return;
}
currentPath = f.getAbsolutePath();
fileNames.clear();
if(true == filePath.equals(ROOT_PATH)) {
} else if (true == startedFromSdcard &&
true == filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
} else {
fileNames.add("../");
}
fileNames.addAll(getSubFileNames(f));
((ArrayAdapter)listView.getAdapter()).notifyDataSetChanged();
}
/**
* Method.
*/
private void moveToRoot() {
File f = new File(ROOT_PATH);
if(null == f || false == f.canRead()) {
showToast("Can't open root directory.");
return;
}
startedFromSdcard = false;
currentPath = f.getAbsolutePath();
fileNames.clear();
fileNames.addAll(getSubFileNames(f));
((ArrayAdapter)listView.getAdapter()).notifyDataSetChanged();
}
private void moveToSdCard() {
String state = Environment.getExternalStorageState();
if(false == state.equals(Environment.MEDIA_MOUNTED)){
showToast("SD card is not mounted.");
return;
}
File f = Environment.getExternalStorageDirectory();
if(null == f || false == f.canRead()) {
showToast("Can't open SD card directory.");
return;
}
startedFromSdcard = true;
currentPath = f.getAbsolutePath();
fileNames.clear();
fileNames.addAll(getSubFileNames(f));
((ArrayAdapter)listView.getAdapter()).notifyDataSetChanged();
}
private List<String> getSubFileNames(File file) {
List<String> fileNameArr = new ArrayList<String>();
if(null == file) {
return fileNameArr;
}
File[] files = file.listFiles();
if(null == files) {
return fileNameArr;
}
String fileName = null;
for(int i=0; i<files.length; i++) {
fileName = files[i].getName();
if(true == files[i].isDirectory()) {
fileName += "/";
}
fileNameArr.add(fileName);
}
return fileNameArr;
}
private void showToast(String message) {
if(null != toast) {
toast.cancel();
toast = null;
}
toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
}
|
package com.web.common.config;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import com.web.common.config.GroupDTO;
import com.web.common.user.UserDTO;
import com.web.framework.data.DataSet;
import com.web.framework.persist.AbstractDAO;
import com.web.framework.persist.DAOException;
import com.web.framework.persist.ISqlStatement;
import com.web.framework.persist.ListDTO;
import com.web.framework.persist.ListStatement;
import com.web.framework.persist.QueryStatement;
import com.web.framework.util.StringUtil;
public class GroupDAO extends AbstractDAO {
/**
* 그룹 리스트 (일반 그룹 트리 리스트)
* @param groupDto 그룹정보
* @return arrlist ArrayList
* @throws DAOException
*/
public ArrayList groupTreeList(GroupDTO groupDto) throws DAOException {
ArrayList<GroupDTO> arrlist = new ArrayList<GroupDTO>();
String procedure = "{ CALL hp_mgGroupInquiry ( ? ,? ,? ,? ,? ) }";
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString(groupDto.getChUserID());
sql.setString(groupDto.getGroupID());
sql.setString(groupDto.getJobGb());
sql.setInteger(groupDto.getGroupStep());
sql.setString(groupDto.getUserID());
DataSet ds = null;
try{
ds = broker.executeProcedure(sql);
while(ds.next()){
groupDto = new GroupDTO();
groupDto.setGroupID(ds.getString("GroupID"));
groupDto.setUpGroupID(ds.getString("UpGroupID"));
groupDto.setGroupName(ds.getString("GroupName"));
groupDto.setUserID(ds.getString("UserID"));
groupDto.setGroupStep(ds.getInt("GroupStep"));
groupDto.setGroupSort(ds.getInt("GroupSort"));
arrlist.add(groupDto);
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return arrlist;
}
/**
* 그룹 상세정보
* @param groupDto 그룹정보
* @return groupDto
* @throws DAOException
*/
public GroupDTO groupView(GroupDTO groupDto) throws DAOException {
String GroupID=groupDto.getGroupID();
String procedure = "{ CALL hp_mgGroupSelect ( ? ,? ,? ,? ) }";
DataSet ds = null;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString("SELECT");
sql.setString(GroupID);
sql.setString("");
try{
ds = broker.executeProcedure(sql);
while(ds.next()){
groupDto = new GroupDTO();
groupDto.setGroupID(ds.getString("GroupID"));
groupDto.setUpGroupID(ds.getString("UpGroupID"));
groupDto.setGroupName(ds.getString("GroupName"));
groupDto.setGroupStep(ds.getInt("GroupStep"));
groupDto.setGroupSort(ds.getInt("GroupSort"));
groupDto.setFaxCnt(ds.getString("FaxCnt"));
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return groupDto;
}
/**
* 그룹 등록
* @param groupDto 그룹정보
* @return groupDto GroupDTO
* @throws DAOException
*/
public GroupDTO groupInsert(GroupDTO groupDto) throws DAOException {
String GroupID=groupDto.getGroupID();
String IGroupID=groupDto.getIGroupID();
String GroupName=groupDto.getGroupName();
int GroupStep=1;
String procedure = "{ CALL hp_mgGroupRegist (? , ? , ? , ?)} ";
DataSet ds = null;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString(GroupID);
sql.setString(GroupName);
sql.setString(IGroupID);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
groupDto = new GroupDTO();
groupDto.setGroupID(ds.getString("R_GroupID"));
groupDto.setGroupStep(ds.getInt("R_GroupStep"));
groupDto.setGroupName(ds.getString("R_GroupName"));
log.debug("getGroupID"+groupDto.getGroupID());
log.debug("getGroupStep"+groupDto.getGroupStep());
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return groupDto;
}
/**
* 그룹 수정
* @param groupDto 그룹정보
* @return groupDto GroupDTO
* @throws DAOException
*/
public GroupDTO groupUpdate(GroupDTO groupDto) throws DAOException {
String GroupID=groupDto.getGroupID();
String GroupName=groupDto.getGroupName();
int GroupStep=1;
String procedure = "{ CALL hp_mgGroupModify (? , ? , ? , ? , ? )} ";
DataSet ds = null;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString(GroupID);
sql.setString(GroupName);
sql.setString("UPDATE");
sql.setInteger(0);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
groupDto = new GroupDTO();
groupDto.setGroupID(ds.getString("R_GroupID"));
groupDto.setGroupStep(ds.getInt("R_GroupStep"));
groupDto.setGroupName(ds.getString("R_GroupName"));
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return groupDto;
}
/**
* 그룹 삭제
* @param groupDto 그룹정보
* @return groupDto GroupDTO
* @throws DAOException
*/
public GroupDTO groupDelete(GroupDTO groupDto) throws DAOException {
String GroupID=groupDto.getGroupID();
String GroupName=groupDto.getGroupName();
int GroupStep=1;
String procedure = "{ CALL hp_mgGroupDelete (? , ? )} ";
DataSet ds = null;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString(GroupID);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
groupDto = new GroupDTO();
groupDto.setGroupID(ds.getString("R_GroupID"));
groupDto.setGroupStep(ds.getInt("R_GroupStep"));
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return groupDto;
}
/**
* 그룹 순서정렬 (같은 뎁스의 순서를 변경한다)
* @param groupDto 그룹정보
* @return retVal int
* @throws DAOException
*/
public int groupOrderUpdate(GroupDTO groupDto) throws DAOException {
int GroupSort=groupDto.getGroupSort();
String GroupID=groupDto.getGroupID();
String procedure = "{ CALL hp_mgGroupModify (? , ? , ? , ? , ? )} ";
DataSet ds = null;
int retVal=-1;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString(GroupID);
sql.setString("");
sql.setString("SORT");
sql.setInteger(GroupSort);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
retVal=ds.getInt("ResultCode");
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return retVal;
}
/**
* 그룹명 중복체크
* @param groupDto 그룹정보
* @return groupDto GroupDTO
* @throws DAOException
*/
public GroupDTO groupNameDupCheck(GroupDTO groupDto) throws DAOException {
String GroupName=groupDto.getGroupName();
String procedure = "{ CALL hp_mgGroupSelect (? , ? , ? , ? )} ";
DataSet ds = null;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString("DUPLICATE");
sql.setString("1");
sql.setString(GroupName);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
groupDto = new GroupDTO();
groupDto.setResult(Integer.parseInt(ds.getString("Result")));
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return groupDto;
}
public int changeGroupSort(String[] groupID, GroupDTO groupDto) {
String procedure = "{ CALL hp_mgGroupSortChange (?, ?, ?, ? ) }";
int retVal = 0;
int[] resultVal=null;
QueryStatement sql = new QueryStatement();
sql.setBatchMode(true);
sql.setSql(procedure);
List batchList=new Vector();
try{
for(int i=0; groupID != null && i<groupID.length; i++){
List batch=new Vector();
String[] GroupID_R = groupID[i].split("\\|");
batch.add(GroupID_R[0]); //GroupID
batch.add(GroupID_R[1]); //GroupSort
batch.add(groupDto.getUpGroupID()); //UpGroupID
batch.add(groupDto.getGroupStep()); //GroupStep
batchList.add(batch);
}
sql.setBatch(batchList);
resultVal=broker.executeProcedureBatch(sql);
for(int i=0;i<resultVal.length;i++){
if(resultVal[i]==-1){
retVal=-1;
break;
}else{
retVal=resultVal[i];
}
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally{
return retVal;
}
}
public int changeGroupStep(String logid, String selectGroupID) throws DAOException {
String procedure = "{ CALL hp_mgGroupStepChange (? )} ";
DataSet ds = null;
int retVal=-1;
QueryStatement sql = new QueryStatement();
sql.setKey(logid);
sql.setSql(procedure);
sql.setString(selectGroupID);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
retVal=ds.getInt("ResultCode");
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return retVal;
}
public String selectGroupInfo(GroupDTO groupDto) throws DAOException {
String procedure = "{ CALL hp_mgGroupSelect ( ? ,?, ?, ? )} ";
DataSet ds = null;
String retVal = "";
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString("");
sql.setString("SELECT");
sql.setString(groupDto.getGroupID());
sql.setString(null);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
retVal=ds.getString("GroupStep");
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return retVal;
}
public int checkGroupName(GroupDTO groupDto) throws DAOException {
String procedure = "{ CALL hp_mgGroupSelect (?, ?, ? ,?)} ";
DataSet ds = null;
int retVal = 0;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString(null);
sql.setString("CHECK");
sql.setString(null);
sql.setString(groupDto.getGroupName());
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
retVal=ds.getInt("Result");
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return retVal;
}
public int checkGroupId(GroupDTO groupDto) throws DAOException {
String procedure = "{ CALL hp_mgGroupSelect (?, ?, ? ,?)} ";
DataSet ds = null;
int retVal = 0;
QueryStatement sql = new QueryStatement();
sql.setKey(groupDto.getLogid());
sql.setSql(procedure);
sql.setString(null);
sql.setString("CHECKID");
sql.setString(groupDto.getGroupID());
sql.setString(null);
try{
ds = broker.executeProcedure(sql);
if(ds.next()){
retVal=ds.getInt("Result");
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
throw new DAOException(e.getMessage());
}finally
{
try
{
if (ds != null) { ds.close(); ds = null; }
}
catch (Exception ignore)
{
log.error(ignore.getMessage());
}
}
return retVal;
}
}
|
package com.revolut.moneytransfer.exceptions;
import com.revolut.moneytransfer.config.Errors;
public class NameCanNotBeEmptyException extends RuntimeException {
public NameCanNotBeEmptyException() {
super(Errors.ACCOUNT_NAME_IS_REQUIRED);
}
}
|
package com.sap.als.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries({
@NamedQuery(name = "SpeechTestRecordingById", query = "select r from SpeechTestRecording r where r.id = :id")
})
public class SpeechTestRecording implements Serializable {
private static final long serialVersionUID = 1L;
public SpeechTestRecording() {
}
@Id
@GeneratedValue
private long id;
private int testId;
@Column(columnDefinition = "BLOB")
private byte[] recording;
private long length;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte[] getRecording() {
return recording;
}
public void setRecording(byte[] recording) {
this.recording = recording;
}
/*
* public void setRecording(byte [] recording) { try { this.recording = new
* SerialBlob(recording); } catch (SQLException e) { throw new
* ExceptionInInitializerError(e); } }
*/
public int getTestId() {
return testId;
}
public void setTestId(int answerId) {
this.testId = answerId;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
}
|
package com.pisen.ott.launcher.localplayer.video;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import com.pisen.ott.launcher.R;
import com.pisen.ott.launcher.widget.slide.MenuLayout;
/**
* @author mahuan
*
*/
public class VideoBottomMenuLayout extends MenuLayout {
private OnItemBottonClickListener mOnItemClickListener;
protected static final int DelayMillis = 5 *1000;
protected Handler handler = new Handler();
protected Runnable hideRun= new Runnable() {
public void run() {
hideMenu();
}
};
public VideoBottomMenuLayout(Context context) {
this(context, null);
}
public VideoBottomMenuLayout(Context context, AttributeSet attrs) {
super(context, attrs, R.anim.slide_footer_appear, R.anim.slide_footer_disappear);
}
/**
* 处理bottomLayout 触摸
*/
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
handler.removeCallbacks(hideRun);
handler.postDelayed(hideRun, DelayMillis);
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
handler.removeCallbacks(hideRun);
handler.postDelayed(hideRun, DelayMillis);
return super.dispatchTouchEvent(ev);
}
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemBottonClick(v);
}
}
public void setOnItemBottonClickListener(OnItemBottonClickListener l) {
this.mOnItemClickListener = l;
}
public interface OnItemBottonClickListener {
void onItemBottonClick(View v);
}
}
|
package com.example.mz.dialogprinter;
import android.widget.Toast;
import com.vk.sdk.api.VKRequest;
import java.util.ArrayDeque;
import static com.vk.sdk.VKUIHelper.getApplicationContext;
/**
* Created by mz on 10/31/17.
*/
public class VkQueue extends Thread {
private final Object runningLock = new Object();
private boolean running = false;
public boolean isRunning() {
synchronized (runningLock) {
return running;
}
}
private class Request {
VKRequest request;
VKRequest.VKRequestListener listener;
}
private final Object queueLock = new Object();
private ArrayDeque<Request> requestsQueue = new ArrayDeque<>();
public void addRequest(VKRequest request, VKRequest.VKRequestListener listener) {
Request requestEx = new Request();
requestEx.request = request;
requestEx.listener = listener;
synchronized (queueLock) {
requestsQueue.addLast(requestEx);
queueLock.notifyAll();
}
}
@Override
public void run() {
synchronized (runningLock) {
running = true;
}
while (isRunning()) {
Request request = null;
synchronized (queueLock) {
if (requestsQueue.isEmpty())
try {
queueLock.wait();
} catch (InterruptedException e) {
break;
}
}
request = requestsQueue.poll();
if(request == null)
continue;
request.request.executeWithListener(request.listener);
try {
Thread.sleep(340);
} catch (InterruptedException e) {
break;
}
}
synchronized (runningLock) {
running = false;
}
}
}
|
package com.mrc.oauth2Java.config;
import org.apache.catalina.filters.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.jaas.memory.InMemoryConfiguration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
class ServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Override
public void configure( WebSecurity web ) throws Exception {
web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/api-docs/**").permitAll()
.anyRequest().authenticated()
.and().anonymous().disable();
}
@Bean
@Deprecated
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
@Deprecated
public PasswordEncoder encoder(){
return NoOpPasswordEncoder.getInstance();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// - (3)
configuration.addAllowedOrigin("*");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return (CorsConfigurationSource) source;
}
}
|
package pl.coderslab.web.model.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import pl.coderslab.web.model.entity.League;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true) //elementy, które istnieją w JSON , ale nie istnieją w klasie, mają być ignorowane
public class CountryDto {
@JsonProperty("country_id") //Określamy nazwę parametru w JSON
private long apiCountryId;
@JsonProperty("country_name")
private String name;
public CountryDto() {
}
public CountryDto(long apiCountryId, String name, List<League> leagues) {
this.apiCountryId = apiCountryId;
this.name = name;
}
public long getApiCountryId() {
return apiCountryId;
}
public void setApiCountryId(long apiCountryId) {
this.apiCountryId = apiCountryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "CountryDto - id: "+apiCountryId+",name: "+name;
}
}
|
package com.hotel.model;
public class HPackage {
private int packageId;
private String packageName;
private double nightPrice;
private double monthPrice;
private int persons;
private String description;
private String features;
private String img;
public String getImg() {
return img;
}
public int getPackageId() {
return packageId;
}
public void setPackageId(int packageId) {
this.packageId = packageId;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public double getNightPrice() {
return nightPrice;
}
public void setNightPrice(double nightPrice) {
this.nightPrice = nightPrice;
}
public double getMonthPrice() {
return monthPrice;
}
public void setMonthPrice(double monthPrice) {
this.monthPrice = monthPrice;
}
public int getPersons() {
return persons;
}
public void setImg(String img) {
this.img = img;
}
public void setPersons(int persons) {
this.persons = persons;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFeatures() {
return features;
}
public void setFeatures(String features) {
this.features = features;
}
}
|
package com.imooc.mapper;
import com.imooc.pojo.OrderStatus;
import com.imooc.pojo.vo.MyOrdersVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface OrdersMapperCustom {
/**
* 获取用户中心我的订单信息
* @param map
* @return
*/
List<MyOrdersVO> getMyOrders(@Param("paramsMap") Map<String, Object> map);
/**
* 获取用户中心我的订单状态数量
* @param map
* @return
*/
int getMyOrderStatusCounts(@Param("paramsMap") Map<String,Object> map);
/**
* 获取用户中心我的订单动向
* @param map
* @return
*/
List<OrderStatus> getMyOrderTrend(@Param("paramsMap") Map<String,Object> map);
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class CollectionsDemo {
public static void main(String[] args) {
/*List l = new ArrayList();
l.add(0,"abc");
l.add(1,new Integer(1));
HashSet s= new HashSet();
s.add("String1");
s.add("String2");
System.out.println("Result"+l.toString());*/
System.out.println("Demonstration of removeIf");
List<String> l1 = createList();
// remove all items which contains an "x"
//l1.removeIf(s-> s.toLowerCase().contains("x"));
//l1.removeIf(s -> s.toLowerCase().contains("x"));
//l1.forEach(s->System.out.println(s));
Map<String, String> map = new HashMap<>();
fillData(map);
// write to command line
//map.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
map.forEach((k,v)-> System.out.println(k+""+v));
}
private static List<String> createList() {
return Arrays.asList("iPhone", "Ubuntu", "Android", "Mac OS X");
}
private static void fillData(Map<String, String> map) {
map.put("Android", "Mobile");
map.put("Eclipse IDE", "Java");
map.put("Eclipse RCP", "Java");
map.put("Git", "Version control system");
}
}
|
import javax.swing.*;
import java.awt.event.*;
public class UpdateMunicipi extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox municipiBox;
private JTextField municipiField;
public UpdateMunicipi(final JFrame parent) throws Exception{
super(parent);
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
final DefaultComboBoxModel dcm = new DefaultComboBoxModel();
municipiBox.setModel(dcm);
// Obtenim la llista de municipis.
for (Municipi m : Main.db.getMunicipis()) {
dcm.addElement(m);
}
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// El municipi a actualtizar
Municipi m = (Municipi) dcm.getSelectedItem();
int id = m.idMunicipi;
// El nom nou
String descripcio = municipiField.getText();
Main.db.updateMunicipi(id, descripcio);
JOptionPane.showMessageDialog(parent, "Update de municipi satisfactori.");
dispose();
} catch (Exception ex) {
// Pot ser que ja existeixi un municipi amb el nom nou.
JOptionPane.showMessageDialog(parent, "Ja existeix aquest municipi.");
}
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
// Quan seleccionem el municipi s'executa aquest codi.
municipiBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
Municipi m = (Municipi) dcm.getSelectedItem();
String municipiDesc = m.descripcioMunicipi;
// Posam el nom del municipi en el field.
municipiField.setText(municipiDesc);
}
});
}
}
|
package me.diyonn.renameSwordGUI;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
public class Damage implements Listener {
@EventHandler
public void HitDamage (EntityDamageByEntityEvent hit){
Player damager = (Player) hit.getDamager();
Player entity = (Player) hit.getEntity();
if (damager instanceof Player && entity instanceof Player && damager.getItemInHand().getItemMeta().getDisplayName().equals(ChatColor.RED+"Sharpened Sword")){
//send the attacker a message
damager.sendMessage(ChatColor.RED+"You hit "+ entity.getName());
//for the person who got hit
entity.sendMessage(ChatColor.RED+(damager.getName()+" wants to kill you!"));
//set sword damage to 0
hit.setDamage(0);
//if his life has fallen below 2 hearts, and is hit, he won't die. this fixes it
if (entity.getHealth()<4){
//plays it at his head
entity.getWorld().playEffect(entity.getLocation().add(0, 2, 0), Effect.VILLAGER_THUNDERCLOUD, 1);
entity.setHealth(0);
} else {
//-2 hearts, when the damager hits them
entity.setHealth(entity.getHealth() - 4);
//check health
damager.sendMessage(ChatColor.RED + entity.getName() + "'s" + ChatColor.GREEN + " health is " + entity.getHealth());
//plays it at his head
entity.getWorld().playEffect(entity.getLocation().add(0, 2, 0), Effect.VILLAGER_THUNDERCLOUD, 1);
}
}
}
}
|
package cn.iocoder.springboot.lab65.demo.client;
import cn.iocoder.springboot.lab65.demo.wsdl.UserGetRequest;
import cn.iocoder.springboot.lab65.demo.wsdl.UserGetResponse;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
public class UserClient extends WebServiceGatewaySupport {
public static final String WEB_SERVICES_URI = "http://127.0.0.1:8080/ws";
private static final String WE_SERVICES_NAMESPACE = "https://github.com/YunaiV/SpringBoot-Labs/tree/master/lab-65/lab-65-spring-ws-demo";
public UserGetResponse getUser(Integer id) {
UserGetRequest request = new UserGetRequest();
request.setId(id);
return (UserGetResponse) getWebServiceTemplate().marshalSendAndReceive(
request, new SoapActionCallback(WE_SERVICES_NAMESPACE + "/UserCreateRequest"));
}
}
|
package com.alibaba.druid.bvt.sql.transform.datatype.oracle2pg;
import com.alibaba.druid.sql.SQLTransformUtils;
import com.alibaba.druid.sql.ast.SQLDataType;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.util.JdbcConstants;
import junit.framework.TestCase;
public class Oracle2PG_DataTypeTest_datetime extends TestCase {
public void test_oracle2pg_timestamp() throws Exception {
String sql = "timestamp";
SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType();
SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType);
assertEquals("TIMESTAMP", pgDataType.toString());
}
public void test_oracle2pg_timestamp_arg() throws Exception {
String sql = "timestamp(2)";
SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType();
SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType);
assertEquals("TIMESTAMP(2)", pgDataType.toString());
}
public void test_oracle2pg_date() throws Exception {
String sql = "date";
SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType();
SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType);
assertEquals("TIMESTAMP(0)", pgDataType.toString());
}
public void test_oracle2pg_datetime() throws Exception {
String sql = "datetime";
SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType();
SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType);
assertEquals("TIMESTAMP", pgDataType.toString());
}
public void test_oracle2pg_timestamp2() throws Exception {
String sql = "TIMESTAMP WITH TIME ZONE";
SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType();
SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType);
assertEquals("TIMESTAMP WITH TIME ZONE", pgDataType.toString());
}
}
|
package com.lgbear.weixinplatform.message.domain;
import java.text.SimpleDateFormat;
import com.lgbear.weixinplatform.base.domain.BaseDomain;
public class Text extends BaseDomain {
private String msgId;
private String content;
private int createTime;
private String openId;
private String operatorId;
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getCreateTime() {
return createTime;
}
public void setCreateTime(int createTime) {
this.createTime = createTime;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getOperatorId() {
return operatorId;
}
public void setOperatorId(String operatorId) {
this.operatorId = operatorId;
}
public Text() {
super();
}
public Text(String msgId, String content, int createTime, String openId, String operatorId) {
super();
this.msgId = msgId;
this.content = content;
this.createTime = createTime;
this.openId = openId;
this.operatorId = operatorId;
}
public String getCreateTimeStr() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime*1000L);
}
}
|
package com.yang.cloud.payment.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yhy
*/
@RestController
public class PaymentController {
@GetMapping("/get")
public String get() {
return "SUCCESS";
}
}
|
package net.parim.system.repository;
import net.parim.common.persistence.CurdRepository;
import net.parim.common.persistence.annotation.MyBatisRepository;
import net.parim.system.entity.Menu;
@MyBatisRepository
public interface MenuRepository extends CurdRepository<Menu> {
}
|
package com.chain;
/**
* @author yuanqinglong
* @since 2020/10/30 16:01
*/
public class MuslimConsumeFilter implements FilterChain {
@Override
public boolean doFilter(ConsumeLimitFilterChain consumeLimitFilterChain, UserInfo userInfo, ConsumeConfigInfo configInfo) {
if (userInfo.getUserAge() < 18) {
return false;
}
System.out.println("MuslimConsumeFilter判断通过,向下传递。。。");
return consumeLimitFilterChain.doFilter(consumeLimitFilterChain, userInfo, configInfo);
}
}
|
package validator.form;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Created by wsit on 6/14/17.
*/
public class MailValidator {
private String body;
private String subject;
private String email;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.attr;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.types.basic.AttributeVisibility;
/**
* Helper class allowing to create jpeg attributes easily.
* @author K. Benedyczak
*/
public class JpegImageAttribute extends Attribute<BufferedImage>
{
public JpegImageAttribute(String name, String groupPath, AttributeVisibility visibility,
List<BufferedImage> values)
{
super(name, new JpegImageAttributeSyntax(), groupPath, visibility, values);
}
public JpegImageAttribute(String name, String groupPath, AttributeVisibility visibility,
BufferedImage value)
{
this(name, groupPath, visibility, Collections.singletonList(value));
}
public JpegImageAttribute()
{
}
}
|
package com.example.my_publish;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.firstprogram.R;
import org.json.JSONException;
import java.util.List;
public class CardsAdapter extends BaseAdapter {
public List<event> items;
private final Context context;
public CardsAdapter(Context context, List<event> items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public event getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_card, null);
holder = new ViewHolder();
holder.itemText = (TextView) convertView.findViewById(R.id.list_item_card_text);
holder.itemText2 = (TextView) convertView.findViewById(R.id.list_item_card_text2);
holder.itemText3 = (TextView) convertView.findViewById(R.id.list_item_card_time);
holder.itemText4 = (TextView) convertView.findViewById(R.id.list_item_card_state);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.itemText.setText(items.get(position).getLauncher());
//holder.itemText.setText("title");
holder.itemText2.setText(items.get(position).getContent());
holder.itemText3.setText(items.get(position).getTime());
if (items.get(position).getState() == 0) {
holder.itemText4.setText("进行中");
holder.itemText4.setTextColor(0xffd43d3d);
} else {
holder.itemText4.setText("已结束");
holder.itemText4.setTextColor(0xff707070);
}
} catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private static class ViewHolder {
private TextView itemText;//标题
private TextView itemText2;//内容
private TextView itemText3;//时间
private TextView itemText4;//状态
}
}
|
package com.stringfunction;
public class string {
public static void main(String[] args) {
String w="welcome Siran";
int length = w.length();
System.out.println(length);
boolean equals = w.equals("welcome Siran");
System.out.println(equals);
boolean equalsIgnoreCase = w.equalsIgnoreCase("WElcome siran");
System.out.println(equalsIgnoreCase);
String lowerCase = w.toLowerCase();
System.out.println(lowerCase);
String upperCase = w.toUpperCase();
System.out.println(upperCase);
boolean startsWith = w.startsWith("w");
System.out.println(startsWith);
boolean endsWith = w.endsWith("n");
System.out.println(endsWith);
boolean contains = w.contains("Siran");
System.out.println(contains);
int indexOf = w.indexOf("m");
System.out.println(indexOf);
int lastIndexOf = w.lastIndexOf("e");
System.out.println(lastIndexOf);
char charAt = w.charAt(0);
System.out.println(charAt);
String replace = w.replace("Siran", "civil");
System.out.println(replace);
String substring = w.substring(1,5);
System.out.println(substring);
boolean empty = w.isEmpty();
System.out.println(empty);
String[] split = w.split(" ");
for (String string : split) {
System.out.println(string);
}
String b=" siran ";
String trim = b.trim();
System.out.println(trim);
String concat = w.concat(b);
System.out.println(concat);
}
}
|
package com.esum.common.record;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.esum.framework.common.sql.Record;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.table.InfoRecord;
public abstract class InterfaceInfoRecord extends InfoRecord {
private static final long serialVersionUID = 20140925L;
private List<String> nodeList;
private String interfaceId;
private String parsingRule;
private String messageConverter;
public InterfaceInfoRecord(Record record) throws ComponentException {
super(record);
}
public InterfaceInfoRecord(String[] ids, Record record) throws ComponentException {
super(ids, record);
}
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getParsingRule() {
return parsingRule;
}
public void setParsingRule(String parsingRule){
this.parsingRule = parsingRule;
}
public List<String> getNodeList() {
return nodeList;
}
public void setNodeList(List<String> nodeList) {
this.nodeList = nodeList;
}
public static List<String> toArrayList(String s, String separatorChars) {
String str = StringUtils.trimToEmpty(s);
String[] tokens = StringUtils.split(str, separatorChars);
return new ArrayList<String>(Arrays.asList(tokens));
}
public boolean containsNodeId(String nodeId) {
if (nodeList == null || nodeList.isEmpty())
return true;
return nodeList.contains(nodeId);
}
public String getMessageConverter() {
return messageConverter;
}
public void setMessageConverter(String messageConverter) {
this.messageConverter = messageConverter;
}
}
|
package com.xwolf.eop.test.core;
import com.xwolf.eop.system.entity.User;
import org.junit.Test;
import java.util.Objects;
/**
* <p>
* </p>
*
* @author xwolf
* @date 2017-01-18 09:32
* @since V1.0.0
*/
public class TestEq {
@Test
public void te(){
User user =new User();
user.setUid(1);
User user2=new User();
user2.setUid(1);
System.out.println(Objects.equals(null,null));
}
}
|
package lb3;
import java.util.Scanner;
public class sp2 {
private String tenSP;
private double giaSP;
private double giamGia;
Scanner scanner = new Scanner(System.in);
public sp2() {
}
public sp2(String tenSP, double giaSP, double giamGia) {
super();
this.tenSP = tenSP;
this.giaSP = giaSP;
this.giamGia = giamGia;
}
public sp2(String tenSP, double giaSP) {
this(tenSP,giaSP,0);
}
public void nhap() {
System.out.println("Nhap ten san pham");
tenSP = scanner.nextLine();
System.out.println("Nhap gia san pham");
giaSP = Double.parseDouble(scanner.nextLine());
System.out.println("Nhap gia giam");
giamGia = Double.parseDouble(scanner.nextLine());
}
public void xuat() {
System.out.println("Ten san pham: "+tenSP);
System.out.println("Gia san pham: "+giaSP);
System.out.println("Gia giam san pham"+giamGia);
}
}
|
package com.example.exception;
import com.example.common.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;
//说明这是一个全局的异常处理类
@ControllerAdvice
@Slf4j
public class WebExceptionHandler {
//针对某种异常,处理之后返回
@ExceptionHandler(MyException.class)
@ResponseBody
public AjaxResponse myException(MyException e) {
log.error("自定义异常");
if (e.getCode() == MyExceptionType.USER_INPUT_ERROR.getCode()) {
//400不需要持久化,通知用户即可
//TODO 将500异常信息持久化,方便运维人员处理
}
return AjaxResponse.error(e);
}
//针对参数异常处理
@ExceptionHandler(BindException.class)
@ResponseBody
public AjaxResponse bindException(BindException e) {
log.error("参数检验异常", e);
List<String> defaultMsg = e.getBindingResult().getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toList());
log.warn(defaultMsg.toString());
return AjaxResponse.error(new MyException(MyExceptionType.USER_INPUT_ERROR, defaultMsg.toString()));
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public AjaxResponse constraintViolationException(ConstraintViolationException e) {
log.error("单个参数检验异常", e);
return AjaxResponse.error(new MyException(MyExceptionType.USER_INPUT_ERROR, e.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public AjaxResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("检验异常");
List<String> defaultMsg = e.getBindingResult().getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toList());
return AjaxResponse.error(new MyException(MyExceptionType.USER_INPUT_ERROR, defaultMsg.toString()));
}
//捕获未知异常
@ExceptionHandler(Exception.class)
@ResponseBody
public AjaxResponse exception(Exception e) {
//TODO 将异常信息持久化,方便运维人员处理
//没有被程序员发现,并转化为MyException的异常,都是其他异常或者未知异常
log.error(e.getMessage());
return AjaxResponse.error(new MyException(MyExceptionType.OTHER_ERROR, "未知异常"));
}
}
|
package com.beike.dao.trx;
import java.util.List;
import java.util.Map;
import com.beike.common.entity.trx.MenuGoodsOrder;
/**
* @desc 对MenuGoodsOrder表的DAO
* @author ljp
*
*/
public interface MenuGoodsOrderDao {
/**
* @desc 根据条件查询MenuGoodsOrder
* @param condition key "数据库字段",value 值
* @return List<Object>
* @throws Exception
*/
public List<Object> queryMenuGoodsOrderByCondition(Map<String, String> condition)throws Exception;
/**
* @desc 增加MenuGoodsMap
* @param menuGoodsMap
* @throws Exception
*/
public void addMenuGoodsOrder(MenuGoodsOrder menuGoodsOrder)throws Exception;
/**
* @desc 根据menuGoodsSn查询MenuGoodsMap
* @param menuGoodsSn
* @return List<MenuGoodsMap>
* @throws Exception
*/
public List<MenuGoodsOrder> queryMenuGoodsOrderByMenuIds(List<Long> menuIds)throws Exception;
/**
* @desc 根据活动id和分店id 查询orderguestmap 数据
* @param orderId
* @param guestId
* @return
* @throws Exception
*/
public List<Map<String, Object>> queryOrderGuestMapByOrderIdAndGuestId(Long orderId, Long guestId)throws Exception;
public List<MenuGoodsOrder> queryByOrderIdAndGuestId(Long orderId);
}
|
/*
* null pointer exception is unchecked exception.
*
* check it, before using it.
*/
package Ex;
import java.util.ArrayList;
/**
*
* @author YNZ
*/
public class NullPointerExceptionTest {
static private ArrayList<String> al;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if (al != null) {
al.add("ss");
}
}
NullPointerExceptionTest() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
// DefaultContextManager.java
package org.google.code.servant.net;
import java.util.Map;
import java.util.HashMap;
/**
* This is a default implementation of ContextManager interface.
*
* @version 1.0 08/14/2001
* @author Alexander Shvets
*/
public class DefaultContextManager implements ContextManager {
/** The map of contexts */
protected Map contexts = new HashMap();
/**
* Puts new context into management
*
* @param name the name of the context
* @param context the context
*/
public void put(String name, Context context) {
contexts.put(name, context);
}
/**
* Gets the context
*
* @param name the name of the context
* @return the context
*/
public Context get(String name) {
return (Context)contexts.get(name);
}
/**
* Removes the context from management
*
* @param name the name of the context
*/
public void remove(String name) {
contexts.remove(name);
}
/**
* Gets all contexts under management
*
* @return all contexts under management
*/
public Map getContexts() {
return contexts;
}
}
|
package com.citibank.ods.entity.pl.valueobject;
import java.math.BigInteger;
import java.util.Date;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
/**
* Classe que instancia os valores correspondente a um registro da tabela :
* BaseTplCustomerBroker
* @author Hamilton Matos
*/
public class BaseTplCustomerBrokerEntityVO extends BaseEntityVO
{
private String m_bkrNameText;
private String m_bkrAddrText;
private String m_bkrCnpjNbr;
private BigInteger m_bkrCustNbr;
private BigInteger m_custNbr;
private String m_custFullNameText;
private Date m_lastAuthDate;
private String m_lastAuthUserId;
private Date m_lastUpdDate;
private String m_lastUpdUserId;
private String m_recStatCode;
/**
* @return Returns bkrCnpjNbr.
*/
public String getBkrCnpjNbr()
{
return m_bkrCnpjNbr;
}
/**
* @param bkrCnpjNbr_ Field bkrCnpjNbr to be setted.
*/
public void setBkrCnpjNbr( String bkrCnpjNbr_ )
{
m_bkrCnpjNbr = bkrCnpjNbr_;
}
/**
* @return Returns bkrCustNbr.
*/
public BigInteger getBkrCustNbr()
{
return m_bkrCustNbr;
}
/**
* @param bkrCustNbr_ Field bkrCustNbr to be setted.
*/
public void setBkrCustNbr( BigInteger bkrCustNbr_ )
{
m_bkrCustNbr = bkrCustNbr_;
}
/**
* @return Returns custNbr.
*/
public BigInteger getCustNbr()
{
return m_custNbr;
}
/**
* @param custNbr_ Field custNbr to be setted.
*/
public void setCustNbr( BigInteger custNbr_ )
{
m_custNbr = custNbr_;
}
/**
* @return Returns lastAuthDate.
*/
public Date getLastAuthDate()
{
return m_lastAuthDate;
}
/**
* @param lastAuthDate_ Field lastAuthDate to be setted.
*/
public void setLastAuthDate( Date lastAuthDate_ )
{
m_lastAuthDate = lastAuthDate_;
}
/**
* @return Returns lastAuthUserId.
*/
public String getLastAuthUserId()
{
return m_lastAuthUserId;
}
/**
* @param lastAuthUserId_ Field lastAuthUserId to be setted.
*/
public void setLastAuthUserId( String lastAuthUserId_ )
{
m_lastAuthUserId = lastAuthUserId_;
}
/**
* @return Returns lastUpdDate.
*/
public Date getLastUpdDate()
{
return m_lastUpdDate;
}
/**
* @param lastUpdDate_ Field lastUpdDate to be setted.
*/
public void setLastUpdDate( Date lastUpdDate_ )
{
m_lastUpdDate = lastUpdDate_;
}
/**
* @return Returns lastUpdUserId.
*/
public String getLastUpdUserId()
{
return m_lastUpdUserId;
}
/**
* @param lastUpdUserId_ Field lastUpdUserId to be setted.
*/
public void setLastUpdUserId( String lastUpdUserId_ )
{
m_lastUpdUserId = lastUpdUserId_;
}
/**
* @return Returns recStatCode.
*/
public String getRecStatCode()
{
return m_recStatCode;
}
/**
* @param recStatCode_ Field recStatCode to be setted.
*/
public void setRecStatCode( String recStatCode_ )
{
m_recStatCode = recStatCode_;
}
/**
* @return Returns bkrAddrText.
*/
public String getBkrAddrText()
{
return m_bkrAddrText;
}
/**
* @param bkrAddrText_ Field bkrAddrText to be setted.
*/
public void setBkrAddrText( String bkrAddrText_ )
{
m_bkrAddrText = bkrAddrText_;
}
/**
* @return Returns bkrNameText.
*/
public String getBkrNameText()
{
return m_bkrNameText;
}
/**
* @param bkrNameText_ Field bkrNameText to be setted.
*/
public void setBkrNameText( String bkrNameText_ )
{
m_bkrNameText = bkrNameText_;
}
/**
* @return Returns custFullNameText.
*/
public String getCustFullNameText()
{
return m_custFullNameText;
}
/**
* @param custFullNameText_ Field custFullNameText to be setted.
*/
public void setCustFullNameText( String custFullNameText_ )
{
m_custFullNameText = custFullNameText_;
}
}
|
package com.corebaseit.advancedgridviewjson.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.corebaseit.advancedgridviewjson.models.FavoritesListModel;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vincent Bevia on 27/10/16. <br />
* vbevia@ieee.org
*/
public class FavoritesListFragmentHelper {
public static final String LOGTAG = "GRIDVIEW";
private SQLiteOpenHelper dbhelper;
public FavoritesListFragmentHelper(Context context) {
dbhelper = new SQLiteHelper(context);
}
public FavoritesListFragmentHelper open() throws SQLException {
Log.i(LOGTAG, "Database opened");
// database = dbhelper.getWritableDatabase();
return this;
}
public void close() throws SQLException {
Log.i(LOGTAG, "Database closed");
dbhelper.close();
}
public FavoritesListModel create(FavoritesListModel search)
{
ContentValues values = new ContentValues();
values.put(FavoritesListModel.Entry.COLUMN_TITLE, search.getTitle());
//now lets insert the row into the database:
SQLiteDatabase database = dbhelper.getWritableDatabase();;
long insertid = database.insert(FavoritesListModel.Entry.TABLE_NAME, null, values);
search.setId(insertid);
database.close();
return search;
}
//I'll create a list of search objects to retrive all of my columns and rows from the db:
public List<FavoritesListModel> findAll() {
List<FavoritesListModel> search = new ArrayList<>();
//next we'll query the db:
String[] allColumns = {
FavoritesListModel.Entry.COLUMN_ID,
FavoritesListModel.Entry.COLUMN_TITLE
};
SQLiteDatabase database = dbhelper.getReadableDatabase();
Cursor cursor = database.query(
FavoritesListModel.Entry.TABLE_NAME,
allColumns,
null,
null,
null,
null,
"_id DESC",
"10"
);
// Log.i(LOGTAG, "return" + cursor.getCount() + " rows");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
FavoritesListModel newSearch = new FavoritesListModel();
newSearch.setId(cursor.getLong(cursor.getColumnIndex(FavoritesListModel.Entry.COLUMN_ID)));
newSearch.setTitle(cursor.getString(cursor.getColumnIndex(FavoritesListModel.Entry.COLUMN_TITLE)));
search.add(newSearch);
}
}
database.close();
return search;
}
public void deleteRow(int id) {
String[] whereArgs = { String.valueOf(id) };
SQLiteDatabase database = dbhelper.getWritableDatabase();
database.delete(
FavoritesListModel.Entry.TABLE_NAME,
"_id=?",
whereArgs
);
database.close();
}
public void deleteRow(String name) {
String[] whereArgs = { name };
SQLiteDatabase database = dbhelper.getWritableDatabase();
database.delete(
FavoritesListModel.Entry.TABLE_NAME,
FavoritesListModel.Entry.COLUMN_TITLE + "=?",
whereArgs
);
database.close();
}
}
|
package com.xantrix.webapp.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.xantrix.webapp.dao.Utenti;
public class UtentiMapper implements RowMapper<Utenti>
{
public Utenti mapRow(ResultSet row, int rowNum) throws SQLException
{
Utenti utenti = new Utenti();
try
{
utenti.setUserId(row.getString("USERID"));
utenti.setPwd(row.getString("PASSWORD"));
utenti.setCodFidelity(row.getString("CODFIDELITY"));
utenti.setAbilitato(row.getString("ABILITATO"));
}
catch (Exception ex)
{
System.out.println("Errore in UtentiMapper.mapRow: " + ex);
}
return utenti;
}
}
|
package org.antran.saletax.internal;
import org.antran.saletax.api.IAmount;
import org.antran.saletax.api.ICart;
import org.antran.saletax.api.ICartCalculator;
import org.antran.saletax.api.IReceiptMaker;
import org.antran.saletax.api.Receipt;
public class TotalCartCalculator implements IReceiptMaker, ICartCalculator
{
public TotalCartCalculator(
ICartCalculator saleTaxCalculator,
ICartCalculator merchandiseTotalCalator)
{
this.saleTaxCalculator = saleTaxCalculator;
this.merchandiseTotalCalculator = merchandiseTotalCalator;
}
public Receipt makeReceipt(ICart cart)
{
IAmount saleTax = saleTaxCalculator.calculate(cart);
IAmount total = this.calculate(cart);
Receipt receipt = new Receipt(cart, saleTax, total);
return receipt;
}
ICartCalculator saleTaxCalculator;
ICartCalculator merchandiseTotalCalculator;
public IAmount calculate(ICart cart)
{
IAmount result = Amount.ZERO;
result = result.add(merchandiseTotalCalculator.calculate(cart));
result = result.add(saleTaxCalculator.calculate(cart));
return result;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common.boundededitors;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.webui.common.AttributeTypeUtils;
import pl.edu.icm.unity.webui.common.LongRangeValidator;
import pl.edu.icm.unity.webui.common.StringToLongConverter;
/**
* Shows a checkbox and a textfield to query for a limit number with optional unlimited setting.
* @author K. Benedyczak
*/
public class LongBoundEditor extends AbstractBoundEditor<Long>
{
public LongBoundEditor(UnityMessageSource msg, String labelUnlimited, String labelLimit,
Long bound)
{
super(msg, labelUnlimited, labelLimit, bound, new StringToLongConverter());
}
@Override
protected void updateValidators()
{
removeAllValidators();
String range = AttributeTypeUtils.getBoundsDesc(msg, min, max);
addValidator(new ConditionalRequiredValidator<Long>(msg, unlimited, Long.class));
addValidator(new LongRangeValidator(msg.getMessage("NumericAttributeHandler.rangeError", range),
min, max));
}
@Override
public Class<? extends Long> getType()
{
return Long.class;
}
}
|
package com.masters.service;
import com.masters.dao.CategoryRepository;
import com.masters.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
@Service
public class CategoryService {
@Autowired
private CategoryRepository categoryRepository;
public List<String> getAllCategoriesNames() {
//List<String> categoryNames = new ArrayList<>();
List<Category> categories = new ArrayList<>();
categoryRepository.findAll().forEach(categories::add);
return categories.stream().map(s -> s.getCategoryName()).collect(Collectors.toList());
}
public List<Category> getAllCategories() {
List<Category> categories = new ArrayList<>();
categoryRepository.findAll().forEach(categories::add);
return categories;
}
public Category createCategory(Category category) {
if(categoryRepository.findByCategoryName(category.getCategoryName()) != null) {
throw new RuntimeException("Category exist!");
}
categoryRepository.save(category);
return category;
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.examples.resources.client.model;
import java.io.Serializable;
import java.util.List;
import com.sencha.gxt.data.shared.TreeStore;
import com.sencha.gxt.data.shared.TreeStore.TreeNode;
public class BaseDto implements Serializable, TreeStore.TreeNode<BaseDto> {
private Integer id;
private String name;
protected BaseDto() {
}
public BaseDto(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public BaseDto getData() {
return this;
}
@Override
public List<? extends TreeNode<BaseDto>> getChildren() {
return null;
}
@Override
public String toString() {
return name != null ? name : super.toString();
}
}
|
package files;
import java.util.Map;
import exceptions.DirectoryDoesNotExistException;
import exceptions.InvalidArgumentException;
import java.util.HashMap;
public class File {
private String name;
private Map<Integer,String> content;
public File(){
name = "";
content = new HashMap<Integer, String>();
}
public File(String name){
this.name = name;
content = new HashMap<Integer, String>();
}
public String getName(){
return name;
}
public String getContentOnSpecificLine(int line){
return content.get(line);
}
public void write(boolean toOverwrite, int line, String text) throws InvalidArgumentException{
isPositiveLineNumber(line);
if(countLines() >= line){
if(!toOverwrite){
append(line,text);
}else{
content.put(line,text);
}
}else{
for(int i = content.size(); i<line; i++){
content.put(i,"");
}
content.put(line,text);
}
}
public long getCalculatedSize(){
long sizeOfFile = countLines() + countSymbols();
return sizeOfFile;
}
public String getContent(){
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < getNumberOfLastRow()+1;i++){
if(content.containsKey(i)){
stringBuilder.append(content.get(i));
stringBuilder.append("\n");
}
}
return new String(stringBuilder);
}
public long countWords(){
String allContent = getContent();
String[] words = allContent.trim().split("\\s+");
return words.length;
}
public int countLines(){
return content.size();
}
public void removeLines(int firstLineNumber, int secondLineNumber) throws InvalidArgumentException{
isPositiveLineNumber(firstLineNumber);
for(int i = 0;i < secondLineNumber; i++){
content.remove(i);
}
}
public long getSizeAfterWriting(boolean toOverwrite,String text, int line) throws InvalidArgumentException{
isPositiveLineNumber(line);
long size =getCalculatedSize();
if(content.size() <= line){
long numberNewLines = line - content.size();
size += numberNewLines;
size += text.length();
}else{
if(toOverwrite){
size+=text.length();
int newLineContentSize = getContentOnSpecificLine(line).length();
size-= newLineContentSize;
}else{
size+= text.length();
}
}
return size;
}
private long countSymbols(){
String currentLine;
long countSymbols = 0;
for (int i = 0 ; i < content.size(); i++){
currentLine = content.get(i);
countSymbols+= currentLine.length();
}
return countSymbols;
}
private void append(int index, String text){
String newLine = content.get(index) + text;
content.replace(index, newLine);
}
private int getNumberOfLastRow(){
Map.Entry<Integer,String> entry = content.entrySet().iterator().next();
int lastRow = entry.getKey();
for(Map.Entry<Integer,String> map:content.entrySet()){
int currentRow = map.getKey();
if(currentRow > lastRow){
lastRow = currentRow;
}
}
return lastRow;
}
private void isPositiveLineNumber(int line) throws InvalidArgumentException{
if(line < 0){
throw new InvalidArgumentException("Invalid arguments!");
}
}
}
|
package org.xtext.tortoiseshell.scoping;
import com.google.common.base.Objects;
import org.eclipse.xtext.common.types.JvmIdentifiableElement;
import org.eclipse.xtext.xbase.featurecalls.IdentifiableSimpleNameProvider;
import org.xtext.tortoiseshell.jvmmodel.TortoiseShellJvmModelInferrer;
@SuppressWarnings("all")
public class TortoiseShellIdentifiableSimpleNameProvider extends IdentifiableSimpleNameProvider {
public String getSimpleName(final JvmIdentifiableElement element) {
String _xifexpression = null;
String _simpleName = element.getSimpleName();
boolean _equals = Objects.equal(_simpleName, TortoiseShellJvmModelInferrer.INFERRED_CLASS_NAME);
if (_equals) {
_xifexpression = "this";
} else {
String _simpleName_1 = super.getSimpleName(element);
_xifexpression = _simpleName_1;
}
return _xifexpression;
}
}
|
/*
* Copyright 2002-2019 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.document;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.web.servlet.View;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for AbstractXlsView and its subclasses.
*
* @author Juergen Hoeller
* @since 4.2
*/
public class XlsViewTests {
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test
@SuppressWarnings("resource")
public void testXls() throws Exception {
View excelView = new AbstractXlsView() {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Sheet sheet = workbook.createSheet("Test Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Test Value");
}
};
excelView.render(new HashMap<>(), request, response);
Workbook wb = new HSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
assertThat(wb.getSheetName(0)).isEqualTo("Test Sheet");
Sheet sheet = wb.getSheet("Test Sheet");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
assertThat(cell.getStringCellValue()).isEqualTo("Test Value");
}
@Test
@SuppressWarnings("resource")
public void testXlsxView() throws Exception {
View excelView = new AbstractXlsxView() {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Sheet sheet = workbook.createSheet("Test Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Test Value");
}
};
excelView.render(new HashMap<>(), request, response);
Workbook wb = new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
assertThat(wb.getSheetName(0)).isEqualTo("Test Sheet");
Sheet sheet = wb.getSheet("Test Sheet");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
assertThat(cell.getStringCellValue()).isEqualTo("Test Value");
}
@Test
@SuppressWarnings("resource")
public void testXlsxStreamingView() throws Exception {
View excelView = new AbstractXlsxStreamingView() {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Sheet sheet = workbook.createSheet("Test Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Test Value");
}
};
excelView.render(new HashMap<>(), request, response);
Workbook wb = new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
assertThat(wb.getSheetName(0)).isEqualTo("Test Sheet");
Sheet sheet = wb.getSheet("Test Sheet");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
assertThat(cell.getStringCellValue()).isEqualTo("Test Value");
}
}
|
package sampleproject.gui;
import java.io.Serializable;
/**
* Value object used to transfer information about changes to our
* <code>ConfigOptions</code> panel to any interested observers.<p>
*
* Even though we don't currently intend for this value object to be sent over
* the wire, it might be desirable in the future. Therefore this object
* implements Serializable. It should be noted that just because it implements
* Serializable does not imply that serialization takes place - we are safe to
* do this without contravening any assignment instructions.
*/
public class OptionUpdate implements Serializable {
/**
* The enumerated list of possible updates that can be sent from the
* ConfigOptions panel. Only one of the following options can possibly be
* passed with this value object.
*/
public enum Updates {
/** The user has swapped between RMI and Sockets network options. */
NETWORK_CHOICE_MADE,
/**
* The user has specified the location of the data file or the address
* of the server.
*/
DB_LOCATION_CHANGED,
/**
* The user has changed the port number the server is expected to be
* listening on.
*/
PORT_CHANGED;
}
/**
* A version number for this class so that serialization can occur
* without worrying about the underlying class changing between
* serialization and deserialization.
*/
private static final long serialVersionUID = 5165L;
/*
* The values that will be transfered.
*/
private Updates updateType = null;
private Object payload = null;
/**
* Empty constructor to conform with JavaBean requirements.
*/
public OptionUpdate() {
}
/**
* A far more useful constructor - one that allows us to specify the
* update type and any relevant information.<p>
*
* @param updateType the tyepe of update that has occurred.
* @param payload any relevant information that we would like to pass at
* the same time.
*/
public OptionUpdate(Updates updateType, Object payload) {
this.updateType = updateType;
this.payload = payload;
}
/**
* Sets the type of update that has occurred.
*
* @param updateType the tyepe of update that has occurred.
*/
public void setUpdateType(Updates updateType) {
this.updateType = updateType;
}
/**
* Gets the type of update that has occurred.
*
* @return the tyepe of update that has occurred.
*/
public Updates getUpdateType() {
return this.updateType;
}
/**
* Sets any information considered relevant to this update.
*
* @param payload any relevant information that we would like to pass at
* the same time.
*/
public void getPayload(Object payload) {
this.payload = payload;
}
/**
* Gets any information considered relevant to this update.
*
* @return any relevant information that we would like to pass at
* the same time.
*/
public Object getPayload() {
return payload;
}
}
|
package a;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.lang3.SystemUtils;
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = null;
try {
es = Executors.newSingleThreadExecutor();
Future<Integer> future = es.submit(() -> {
int j = 0;
for(int i=0; i<=1000000000; i++) {
j = i;
}
return j;
});
System.out.println("Begin");
int i = future.get();
System.out.println(i);
System.out.println("End");
es.submit(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
} finally {
if(es != null) es.shutdown();
}
}
}
|
package br.com.senior.furb.basico;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import br.com.senior.furb.basico.BasicoValidator;
import br.com.senior.furb.basico.*;
public class ChangeGamePlayerMapInput {
/**
* login credential
*/
public String login;
/**
* password credential
*/
public String password;
/**
* Map name
*/
public String mapId;
public ChangeGamePlayerMapInput() {
}
/**
* This constructor allows initialization of all fields, required and optional.
*/
public ChangeGamePlayerMapInput(String login, String password, String mapId) {
this.login = login;
this.password = password;
this.mapId = mapId;
}
public void validate() {
validate(true);
}
public void validate(boolean required) {
validate(null, required);
}
public void validate(Map<String, Object> headers, boolean required) {
validate(headers, required, new ArrayList<>());
}
void validate(Map<String, Object> headers, boolean required, List<Object> validated) {
BasicoValidator.validate(this, headers, required, validated);
}
@Override
public int hashCode() {
int ret = 1;
if (login != null) {
ret = 31 * ret + login.hashCode();
}
if (password != null) {
ret = 31 * ret + password.hashCode();
}
if (mapId != null) {
ret = 31 * ret + mapId.hashCode();
}
return ret;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ChangeGamePlayerMapInput)) {
return false;
}
ChangeGamePlayerMapInput other = (ChangeGamePlayerMapInput) obj;
if ((login == null) != (other.login == null)) {
return false;
}
if ((login != null) && !login.equals(other.login)) {
return false;
}
if ((password == null) != (other.password == null)) {
return false;
}
if ((password != null) && !password.equals(other.password)) {
return false;
}
if ((mapId == null) != (other.mapId == null)) {
return false;
}
if ((mapId != null) && !mapId.equals(other.mapId)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
toString(sb, new ArrayList<>());
return sb.toString();
}
void toString(StringBuilder sb, List<Object> appended) {
sb.append(getClass().getSimpleName()).append(" [");
if (appended.contains(this)) {
sb.append("<Previously appended object>").append(']');
return;
}
appended.add(this);
sb.append("login=").append(login == null ? "null" : login).append(", ");
sb.append("password=").append(password == null ? "null" : password).append(", ");
sb.append("mapId=").append(mapId == null ? "null" : mapId);
sb.append(']');
}
}
|
package com.thewizardbeards.getcultured;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.ImageView;
import android.widget.TextView;
public class DescriptionActivity extends Activity {
/**
* Locates the views on the Main Description activity and assigns values.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description);
//central Image is set
ImageView centralImageView = (ImageView) findViewById(R.id.centralImageView);
centralImageView.setImageResource(R.drawable.wizard_square);
// address
TextView textView3 = (TextView) findViewById(R.id.textView3);
textView3.setText(R.string.add_zero);
//email
TextView textView4 = (TextView) findViewById(R.id.textView4);
textView4.setText(Html.fromHtml("<a href=\"mailto:" + getString(R.string.email) + "?subject=" + getString(R.string.email_subject) + "\">" + getString(R.string.email) + "</a>"));
textView4.setMovementMethod(LinkMovementMethod.getInstance());
//link
TextView textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText(R.string.link_zero);
}
@Override
protected void onStop() {
super.onStop();
DescriptionActivity.this.finish();
}
}
|
package com.lal.android.out;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public int score = 0;
int over = 0;
int balls = 0;
public int fallOfWickets = 0;
int previousOver;
int previousBalls;
int previousScore;
int previousFallOfWicket;
String previousAnnouncement;
String allOutAnnouncement = "Oh No, All Out !";
String allOutToastMessage = "All Out, Game Over !";
SQLiteHandler db;
TextView outView, overView, ballsView, scoreAnnounceView, scoreView;
String TAG = "ActivityOne";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new SQLiteHandler(this);
outView = (TextView) findViewById(R.id.wicketsTextView);
overView = (TextView) findViewById(R.id.overTextView);
ballsView = (TextView) findViewById(R.id.ballsInOverTextView);
scoreAnnounceView = (TextView) findViewById(R.id.scoreAnnounceTextView);
scoreView = (TextView) findViewById(R.id.scoreTextView);
Log.i(TAG, "----------ON CREATE-------------");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "----------ON START-------------");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "----------ON RESUME-------------");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "----------ON PAUSE-------------");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "----------ON STOP-------------");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "----------ON DESTROY-------------");
}
/**
* Perform when SIX button is Clicked
* add six runs to Score
*
* @param V view
*/
public void addSixRuns(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "What a SIX !", fallOfWickets);
score = score + 6;
balls = balls + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("What a SIX !");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when FOUR button is Clicked
* add four runs to Score
*
* @param V view
*/
public void addFourRuns(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "That is a FOUR !", fallOfWickets);
score = score + 4;
balls = balls + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("That is a FOUR !");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when TRIPLE button is Clicked
* add 3 runs to Score
*
* @param V view
*/
public void addThreeRuns(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Good Running Between wickets !", fallOfWickets);
score = score + 3;
balls = balls + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("Good Running Between wickets !");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when TWO button is Clicked
* add 2 runs to Score
*
* @param V view
*/
public void addTwoRuns(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Nice Double !", fallOfWickets);
score = score + 2;
balls = balls + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("Nice Double !");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when ONE button is Clicked
* add 1 runs to Score
*
* @param V view
*/
public void addOneRuns(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Just a Single !", fallOfWickets);
score = score + 1;
balls = balls + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("Just a Single !");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when WIDE/NO BALL button is Clicked
* add 1 runs to Score
*
* @param V view
*/
public void addOneRunsExtra(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Got an Extra Run !", fallOfWickets);
score = score + 1;
displayScore(score);
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("Got an Extra Run !");
}
/**
* perform when OUT Button is clicked
*
* @param V view the out text view
*/
public void addOneToOutTextView(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Oh No, " + fallOfWickets + " Wicket is gone", fallOfWickets);
fallOfWickets = fallOfWickets + 1;
balls = balls + 1;
displayOut(fallOfWickets);
displayBalls(balls);
displayScoreAnnounce("Oh No, " + fallOfWickets + " Wicket is gone");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* Perform when DEAD BALL / BACK is Clicked
* go back to previous Scoreboard
*
* @param V view
*/
public void goToPreviousValues(View V){
displayPreviousValues(previousScore, previousBalls, previousOver, previousAnnouncement, previousFallOfWicket);
}
/**
* Perform when DOT BALL button is Clicked
* add 1 runs to Score without add balls
*
* @param V view
*/
public void addDotBall(View V) {
if (fallOfWickets == 10) {
displayScoreAnnounce(allOutAnnouncement);
Toast.makeText(MainActivity.this, allOutToastMessage, Toast.LENGTH_SHORT).show();
return;
}
updatePreviousValues(score, balls, over, "Dot Ball !!", fallOfWickets);
balls = balls + 1;
displayBalls(balls);
displayOver(over);
displayScoreAnnounce("Dot Ball !!");
if (balls == 6) {
balls = 0;
displayBalls(balls);
over = over + 1;
displayOver(over);
}
}
/**
* when the RESET Button is pressed
* Reset the whole game
*
* @param V Reset all the Views
*/
public void resetGame(View V) {
new AlertDialog.Builder(this)
.setTitle("Reset")
.setMessage("Are you sure want to Reset score?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
score = 0;
over = 0;
balls = 0;
fallOfWickets = 0;
displayScore(score);
displayOver(over);
displayBalls(balls);
displayOut(fallOfWickets);
displayScoreAnnounce("Come, Lets Start The Game !!");
Toast.makeText(MainActivity.this, "Score Reseted", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", null).show();
}
/**
* Display Out
*
* @param out main score
*/
public void displayOut(int out) {
outView.setText(String.valueOf(out));
}
/**
* Display the Overs
*
* @param over main score
*/
public void displayOver(int over) {
overView.setText(String.valueOf(over));
}
/**
* Display the Balls
*
* @param balls main score
*/
public void displayBalls(int balls) {
ballsView.setText(String.valueOf(balls));
}
/**
* Display the Score Announcement
*
* @param scoreAnnounce main score Announcement
*/
public void displayScoreAnnounce(String scoreAnnounce) {
scoreAnnounceView.setText(scoreAnnounce);
}
/**
* Display the Score
*
* @param score main score
*/
public void displayScore(int score) {
scoreView.setText(String.valueOf(score));
}
/**
* Display the Values
*
* @param score main score
* @param balls balls
* @param over over
* @param announcement announcement
* @param fallOfWickets fallOfWickets
*/
private void displayPreviousValues(int score, int balls, int over, String announcement, int fallOfWickets) {
this.score = score;
this.balls = balls;
this.over = over;
this.fallOfWickets = fallOfWickets;
scoreView.setText(String.valueOf(score));
ballsView.setText(String.valueOf(balls));
overView.setText(String.valueOf(over));
scoreAnnounceView.setText(announcement);
outView.setText(String.valueOf(fallOfWickets));
}
/**
* Update previous Scoreboard values
*
*/
public void updatePreviousValues(int score, int balls, int over, String announcement, int fallOfWickets){
previousScore = score;
previousBalls = balls;
previousOver = over;
previousAnnouncement = announcement;
previousFallOfWicket = fallOfWickets;
}
public void saveScore(View view){
// Log.d("SaveScore", "Inside saveScore");
String oversStr = over + "." + balls;
Float overs = Float.parseFloat(oversStr);
Score s = new Score(this.score, overs, this.fallOfWickets,System.currentTimeMillis());
db.addMatch(s);
Toast.makeText(MainActivity.this, "Match Saved", Toast.LENGTH_LONG).show();
}
public void openSavedScoreList(View view) {
// Start the activity connect to the saved score list activity
// specified class
String oversStr = over + "." + balls;
Float overs = Float.parseFloat(oversStr);
Score s = new Score(this.score, overs, this.fallOfWickets, System.currentTimeMillis());
db.addMatch(s);
Intent ScoreListActivity = new Intent(this, ScoreListActivity.class);
startActivity(ScoreListActivity);
}
}
|
import java.util.*;
public class ManySquares {
public int howManySquares(int[] sticks) {
Arrays.sort(sticks);
int count = 1;
int result = 0;
for(int i = 1; i < sticks.length; ++i) {
if(sticks[i] != sticks[i - 1]) {
count = 0;
}
++count;
if(count%4 == 0) {
++result;
}
}
return result;
}
}
|
package org.deeplearning4j.eval;
import org.deeplearning4j.berkeley.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by endy on 16/8/25.
*/
public class Evaluation implements Serializable {
protected Counter<Integer> truePositives = new Counter<>();
protected Counter<Integer> falsePositives = new Counter<>();
protected Counter<Integer> trueNegatives = new Counter<>();
protected Counter<Integer> falseNegatives = new Counter<>();
protected ConfusionMatrix<Integer> confusion;
protected int numRowCounter = 0;
protected List<String> labelsList = new ArrayList<>();
protected static Logger log = LoggerFactory.getLogger(Evaluation.class);
protected static final double DEFAULT_EDGE_VALUE = 0.0;
public Evaluation(){
}
public Evaluation(int numClasses){
this(createLabels(numClasses));
}
public Evaluation(List<String> labels){
this.labelsList = labels;
if(labels != null){
createConfusion(labels.size());
}
}
public Evaluation(Map<Integer,String> labels){
this(createLabelsFromMap(labels));
}
private static List<String> createLabels(int numClasses){
if(numClasses == 1) numClasses = 2;
List<String> list = new ArrayList<>(numClasses);
for(int i =0;i<numClasses;i++){
list.add(String.valueOf(i));
}
return list;
}
private static List<String> createLabelsFromMap(Map<Integer,String> labels){
int size = labels.size();
List<String> list = new ArrayList<>(size);
for(int i = 0;i<size;i++){
String str = labels.get(i);
if(str == null)
throw new IllegalArgumentException("Invalid labels map: missing key for class "+i+
" (expect integer 0 to " + (size-1)+")");
list.add(str);
}
return list;
}
private void createConfusion(int nClasses){
List<Integer> classes = new ArrayList<>();
for(int i = 0;i<nClasses;i++){
classes.add(i);
}
confusion = new ConfusionMatrix<>(classes);
}
}
|
package PA165.language_school_manager.Facade;
import PA165.language_school_manager.DTO.CourseCreateDTO;
import PA165.language_school_manager.DTO.CourseDTO;
import PA165.language_school_manager.DTO.LectureDTO;
import PA165.language_school_manager.Enums.Language;
import java.util.Collection;
import java.util.List;
/**
* @author Viktor Slany
*/
public interface CourseFacade {
/**
* Method used to find course by given id
*
* @param id - id of the searched course
* @return course with given id
*/
CourseDTO findCourseById(Long id);
/**
* Method used to get course with a given name (every course has a unique name)
*
* @param name - name of the searched course
* @return course with the given name
*/
CourseDTO findCourseByName(String name);
/**
* Method used to get all courses with language given in the methods parameter
*
* @param language - language of the searched courses
* @return List of courses with given language
*/
List<CourseDTO> findCourseByLanguage(Language language);
/**
* Method used to retrieve all courses from database
*
* @return List of courses stored in database
*/
List<CourseDTO> findAllCourses();
/**
* Method used to store course given as a parameter
*
* @param course - course to be stored in database
* @return Long - Id of course
*/
Long createCourse(CourseCreateDTO course);
/**
* method used to update the course information
*
* @param course - course which should be updated
*/
void updateCourse(CourseDTO course);
/**
* Method used to delete course
*
* @param course - course which should be deleted
*/
void deleteCourse(CourseDTO course);
/**
* Assign lecture to course
*
* @param course course
* @param lecture lecture
*/
void assignNewLecture(CourseDTO course, LectureDTO lecture);
}
|
package com.example.lionel.broadcastreceivertest;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.destroyActivity(this);
}
}
|
package dk.webbies.tscreate.paser.AST;
import com.google.javascript.jscomp.parsing.parser.util.SourceRange;
import dk.webbies.tscreate.paser.StatementVisitor;
/**
* Created by Erik Krogh Kristensen on 07-09-2015.
*/
public class TryStatement extends Statement {
private final Statement tryBlock;
private final CatchStatement catchBlock;
private final Statement finallyBlock;
public TryStatement(SourceRange loc, Statement tryBlock, CatchStatement catchBlock, Statement finallyBlock) {
super(loc);
this.tryBlock = tryBlock;
this.catchBlock = catchBlock;
this.finallyBlock = finallyBlock;
}
public Statement getTryBlock() {
return tryBlock;
}
public Statement getCatchBlock() {
return catchBlock;
}
public Statement getFinallyBlock() {
return finallyBlock;
}
@Override
public <T> T accept(StatementVisitor<T> visitor) {
return visitor.visit(this);
}
}
|
package com.vicutu.batchdownload.dao.impl.simple;
import org.springframework.stereotype.Repository;
import com.vicutu.batchdownload.dao.SearchStatusDao;
import com.vicutu.batchdownload.domain.SearchStatus;
@Repository
public class SearchStatusDaoSimpleImpl implements SearchStatusDao {
@Override
public SearchStatus findSearchStatusByUrl(String url) {
return null;
}
@Override
public void saveOrUpdateSearchStatus(SearchStatus searchStatus) {
}
@Override
public boolean urlExists(String url) {
return false;
}
}
|
package com.dsoft.myrestaurant;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Created by Marco Barrios on 31/10/2014.
*/
public class ActivityProduccion extends Activity {
private ArrayAdapter<Productos> adapter;
private ListView productsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produccion);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
inicializarComponentes();
inicializarListView();
agregarProductos(1, "Tomate");
agregarProductos(2, "Queso");
agregarProductos(3, "Cebolla");
agregarProductos(4, "Jamon");
agregarProductos(5, "Pepinillos");
agregarProductos(6, "Carne de res");
agregarProductos(7, "Ketchup");
agregarProductos(8, "Mayonesa");
agregarProductos(9, "Limon");
agregarProductos(10, "Papalinas");
}
private void agregarProductos(int id, String nombre) {
Productos nuevo = new Productos(id, nombre);
adapter.add(nuevo);
}
private void inicializarListView() {
adapter = new ProductoListAdapter(this, new ArrayList<Productos>());
productsListView.setAdapter(adapter);
productsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(ActivityProduccion.this, ActivityProduccionDatos.class);
startActivity(intent);
}
});
}
private void inicializarComponentes() {
productsListView = (ListView)findViewById(R.id.listViewProductos);
}
}
|
package com.zjy.dao;
public interface EntityDao<o> {
public void add(o entity);
public void delete(o entity);
public o load(Object id);
public void update(o entity);
}
|
/**
Copyright Oracle..
**/
/**
* The HelloWorldApp class implements an application that simply prints "Hello World" to standard output.
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World, my name is LuisNog y soy de Portugal");
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.util;
import java.util.Stack;
/**
* HTML工具类.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
public class HtmlUtils {
/**
* 将标准的HTML转化为Unity能识别HTML.
* <p>
* 其实只处理加粗、斜体、大小、颜色4个标签,其他标签默认删除
*
* @param html 标准HTML文本
* @return Unity能识别HTML
*/
public static String toUnityHtml(final String html) {
final Stack<HtmlTag> stack = new Stack<>();
final StringBuilder sb = new StringBuilder(html.length());
for (int i = 0, len = html.length(); i < len; i++) {
char cur = html.charAt(i);
if (cur == '<' && len > i + 1) {
HtmlTag tag = readTag(html, i);
i = tag.getLength();
// 结束标签
if (tag.isEnd()) {
if (!stack.isEmpty() && stack.peek().getName().equals(tag.getName())) {
tag = stack.pop();
}
tag.html(sb, true);
}
// 开始标签
else {
stack.push(tag);
tag.html(sb, false);
}
} else {
sb.append(cur);
}
}
return sb.toString();
}
private static HtmlTag readTag(final String html, int index) {
final HtmlTag tag = new HtmlTag();
StringBuilder sb = new StringBuilder(16);
boolean color = false;
boolean size = false;
for (int i = index + 1, len = html.length(); i < len; i++) {
char cur = html.charAt(i);
if (cur == '/') {
tag.setEnd(true);
continue;
} else if (cur == ' ') {
tag.setName(sb.toString());
sb.setLength(0);
} else if (cur == '>') {
if (tag.getName() == null) {
tag.setName(sb.toString());
}
tag.setLength(i);
break;
} else if (cur == '"') {
if (color) {
tag.setColor(sb.toString());
color = false;
} else if (size) {
tag.setSize(sb.toString().replace("px", ""));
size = false;
}
sb.setLength(0);
} else if (cur == ':') {
if ("color".equals(sb.toString())) {
color = true;
} else if ("font-size".equals(sb.toString())) {
size = true;
}
sb.setLength(0);
} else if (cur == ';') {
if (color) {
tag.setColor(sb.toString());
color = false;
} else if (size) {
tag.setSize(sb.toString().replace("px", ""));
size = false;
}
sb.setLength(0);
} else {
sb.append(cur);
}
}
return tag;
}
/**
* HTML标签.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
static class HtmlTag {
private String name;
private boolean end;
private int length;
private String color;
private String size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnd() {
return end;
}
public void setEnd(boolean end) {
this.end = end;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public void setColor(String color) {
this.color = color;
}
public void setSize(String size) {
this.size = size;
}
public void html(StringBuilder sb, boolean isEnd) {
switch (name) {
case "b":
case "strong":
sb.append(isEnd ? "</b>" : "<b>");
break;
case "i":
case "em":
// 斜体
// <i>usually</i>
sb.append(isEnd ? "</i>" : "<i>");
break;
case "span":
// 大小
// <size=50>largely</size>
if (size != null) {
sb.append(isEnd ? "</size>" : "<size=" + size + ">");
}
// 颜色
// <color=#00ffffff>cccc</color>
if (color != null) {
sb.append(isEnd ? "</color>" : "<color=" + color + ">");
}
break;
case "br":
sb.append(isEnd ? "<br>" : "");
break;
default:
break;
}
}
@Override
public String toString() {
return "HtmlTag [name=" + name + ", end=" + end + ", length=" + length + ", color=" + color + ", size=" + size + "]";
}
}
}
|
package api;
import api.algorithm.condition.EndCondition;
import api.algorithm.crossover.CrossoverAlgorithm;
import api.algorithm.mutation.MutationAlgorithm;
import api.algorithm.replacement.ReplacementAlgorithm;
import api.algorithm.selection.SelectionAlgorithm;
import api.configuration.Configuration;
import api.model.gen.Gen;
import api.model.gen.GenFactory;
import api.model.individual.Individual;
import java.util.LinkedList;
import java.util.List;
public class GeneticAlgorithm {
private List<GeneticAlgorithmObserver> subscribers = new LinkedList<>();
public void run(Configuration configuration) {
List<Individual> poblation = configuration.getPoblation();
notifyInitialPoblation(poblation);
SelectionAlgorithm selectionAlgorithmForCrossover = configuration.getSelectionAlgorithmForCrossover();
CrossoverAlgorithm crossoverAlgorithm = configuration.getCrossoverAlgorithm();
MutationAlgorithm mutationAlgorithm = configuration.getMutationAlgorithm();
SelectionAlgorithm selectionAlgorithmForReplacement = configuration.getSelectionAlgorithmForReplacement();
ReplacementAlgorithm replacementAlgorithm = configuration.getReplacementAlgorithm();
GenFactory genFactory = configuration.getGenFactory();
while (!algorithmEnded(configuration, poblation)) {
List<Individual> selectedIndividualsForCrossover = selectionAlgorithmForCrossover.select(poblation);
List<Individual> crossoveredIndividuals = crossoverAlgorithm.crossover(selectedIndividualsForCrossover);
mutationAlgorithm.mutate(crossoveredIndividuals, genFactory);
replacementAlgorithm.replace(crossoveredIndividuals, poblation, selectionAlgorithmForReplacement);
notifyNewPoblation(poblation);
}
}
private static boolean algorithmEnded(Configuration configuration, List<Individual> poblation) {
List<EndCondition> endConditions = configuration.getEndConditions();
for (EndCondition endCondition : endConditions) {
if (endCondition.hasAlgorithmEnded(poblation)) {
return true;
}
}
return false;
}
public void notifyNewPoblation(List<Individual> poblation) {
for (GeneticAlgorithmObserver subscriber : subscribers) {
subscriber.newPoblation(poblation);
}
}
public void notifyInitialPoblation(List<Individual> poblation) {
for (GeneticAlgorithmObserver subscriber : subscribers) {
subscriber.initialPoblation(poblation);
}
}
public void subscribe(GeneticAlgorithmObserver geneticAlgorithmObserver){
subscribers.add(geneticAlgorithmObserver);
}
private void print(List<Individual> poblation){
System.out.println("-------------PASO----------------");
StringBuilder sb = new StringBuilder();
for(Individual individual : poblation){
for(Gen gen : individual.getGens()){
sb.append(gen.getCurrentValue());
}
sb.append(" ").append(individual.getFitness());
System.out.println(sb.toString());
sb = new StringBuilder();
}
System.out.print("-----------------------------");
}
}
|
package com.example.daikiiriguchi.trainingday.realm;
import io.realm.RealmObject;
/**
* Created by daikiiriguchi on 1/24/16.
*/
public class RlmInitialLaunch extends RealmObject {
private boolean isInitial;
public boolean isInitial() {
return isInitial;
}
public void setIsInitial(boolean isInitial) {
this.isInitial = isInitial;
}
}
|
package com.xiangxue.safeend;
/**
* @Author: lijunlei
* @Date: 2019/1/26 18:01
* @Description: 中断Runnable线程
*/
public class EndRunnable {
private static class UseRunnable implements Runnable{
@Override
public void run() {
String threadName=Thread.currentThread().getName();
while(!Thread.currentThread().isInterrupted()){
System.out.println(threadName+"is run!");
}
System.out.println(threadName+" interrput flag is "+Thread.currentThread().isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
UseRunnable useRunnable=new UseRunnable();
Thread endThread=new Thread(useRunnable,"endThread");
endThread.start();
Thread.sleep(20);
endThread.interrupt();
}
}
|
package ar.gob.ambiente.servicios.especiesforestales.entidades.util;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Categorias {
private List<ParItemValor> lPares;
public List<ParItemValor> getlPares() {
return lPares;
}
@XmlElement
public void setlPares(List<ParItemValor> lPares) {
this.lPares = lPares;
}
}
|
/*
* Class that defines the agent function.
*
* Written by James P. Biagioni (jbiagi1@uic.edu)
* for CS511 Artificial Intelligence II
* at The University of Illinois at Chicago
*
* Last modified 2/19/07
*
* DISCLAIMER:
* Elements of this application were borrowed from
* the client-server implementation of the Wumpus
* World Simulator written by Kruti Mehta at
* The University of Texas at Arlington.
*
*/
import java.util.HashMap;
import java.util.Random;
class AgentFunction {
// string to store the agent's name
// do not remove this variable
private String agentName = "Agent Smith";
private Random rand;
private HashMap<String, ProbabilisticAction[]> conditionActionRules;
public AgentFunction()
{
conditionActionRules = new HashMap();
// Initialize the condition action rules
Utils.createCARules(conditionActionRules);
// new random number generator, for
// randomly picking actions to execute
rand = new Random();
}
/*
Percepts tuple - <glitter, stench, scream, bump, breeze>
*/
public int process(TransferPercept tp)
{
// read in the current percepts
// if it's glitter then grab right away
if(tp.getGlitter()){
return Action.GRAB;
}
//Code to convert the percepts into a binary string for comparison with the condition action rules
StringBuilder binaryPercept = new StringBuilder();
binaryPercept.append(tp.getGlitter() ? 1 : 0);
binaryPercept.append(tp.getStench() ? 1 : 0);
binaryPercept.append(tp.getScream() ? 1 : 0);
binaryPercept.append(tp.getBump() ? 1 : 0);
binaryPercept.append(tp.getBreeze() ? 1 : 0);
//Get the set of probable actions for the percept
ProbabilisticAction[] probableActions = conditionActionRules.get(binaryPercept.toString());
// random number for selecting a probable action
float randomProbability = (rand.nextInt(10) + 1)/10f;
float totalProbability = 0f;
// this loop selects the action that matches the random probability
for(ProbabilisticAction action: probableActions){
if(action.probability + totalProbability > randomProbability){
return action.action;
}
totalProbability += action.probability;
}
// return NO_OP if none of the actions were selected
return Action.NO_OP;
}
// public method to return the agent's name
// do not remove this method
public String getAgentName() {
return agentName;
}
}
|
import java.util.*;
class Question_2
{
static int palindrome_check(int arr[], int s, int e)
{
if (s >= e) {
return 1;
}
if (arr[s] == arr[e]) {
return palindrome_check(arr, s +1, e -1);
}
else {
return 0;
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the length of the array : ");
int len = sc.nextInt();
int arr[] = new int[len];
for(int i=0;i<len;i++)
{
System.out.print("Enter the element no."+(i+1)+" : ");
arr[i] = sc.nextInt();
}
if (palindrome_check(arr, 0, len - 1) == 1)
System.out.print("Palindrome.");
else
System.out.println("Not Palindrome.");
}
}
|
package com.Constructor_concepts;
class Parent
{
public Parent()
{
System.out.println("Parent class no-args constructor called");
}
public Parent(String name)
{
System.out.println("Parent class Parameterized constructor called by "+name);
}
}
public class Constructor_chaining extends Parent {
public Constructor_chaining()
{
this("Hello");
System.out.println("Child class no-args constructor called");
}
public Constructor_chaining(String name)
{
super("World");
System.out.println("Child class Parameterized constructor called by "+name);
}
public static void main(String[] args) {
Constructor_chaining cc = new Constructor_chaining();
}
}
|
package cloud.fmunozse.mdclogging.web;
import cloud.fmunozse.mdclogging.config.annotations.MDCEnable;
import cloud.fmunozse.mdclogging.config.annotations.MDCParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.atomic.AtomicLong;
@Slf4j
@Controller
public class HelloWorldController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@MDCEnable
@GetMapping("/hello-world-noTag")
@ResponseBody
public ResponseEntity<Greeting> sayHelloNoTag(
@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "test1", required = false) String test1
) {
log.info("testing get hello-world-noTag");
return ResponseEntity.ok(new Greeting(counter.incrementAndGet(), String.format(template, name)));
}
@MDCEnable
@GetMapping("/hello-world-1tag")
@ResponseBody
public ResponseEntity<Greeting> sayHelloOneTag(
@RequestParam(name = "name", required = false) @MDCParam(key = "testKey") String name,
@RequestParam(name = "test1", required = false) String test1
) {
log.info("testing get hello-world-1tag with input name:{} ", name);
return ResponseEntity.ok(new Greeting(counter.incrementAndGet(), String.format(template, name)));
}
@MDCEnable
@GetMapping("/hello-world-2tag")
@ResponseBody
public ResponseEntity<Greeting> sayHelloTwoTag(
@RequestParam(name = "name", required = false) @MDCParam(key = "testKey") String name,
@RequestParam(name = "title", required = false) @MDCParam(key = "AnotherKey") String title) {
log.info("testing get hello-world-2tag with inputs name:{} and title:{}", name, title);
return ResponseEntity.ok(new Greeting(counter.incrementAndGet(), String.format(template, name)));
}
@MDCEnable
@PostMapping("/helloworld")
@ResponseBody
public ResponseEntity<Greeting> sayHelloPost(@RequestBody @MDCParam(key = "testKey", jsonPathValue = "$.id") Greeting greeting) {
log.info("testing post helloworld with input greeting:{}", greeting);
return ResponseEntity.ok(new Greeting(counter.incrementAndGet(), String.format(template, greeting.getContent())));
}
}
|
package defaultImpl;
import aTPeopleCOS730.DateInvalidException;
import aTPeopleCOS730.Group;
import aTPeopleCOS730.GroupSuspendedException;
import aTPeopleCOS730.NonMemberExeption;
import aTPeopleCOS730.UnauthorizedUserExeption;
import aTPeopleCOS730.InvalidEmailException;
import aTPeopleCOS730.Person;
import aTPeopleCOS730.ResearchCategoryState;
import aTPeopleCOS730.ResearchGroupAssociation;
import aTPeopleCOS730.ResearchGroupAssociationType;
import aTPeopleCOS730.ResearcherCategory;
import javax.persistence.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* PersonImplementation type, an entity defined as being a record of a human being
*/
@Entity
@Table
public class PersonImplementation implements Person
{
//---------------------------CONSTRUCTORS---------------------------------------
/**
* Defines the no-args constructor for a PersonImplementation
* Protected, as it should not be used
* (especially not outside of the people package)
*/
protected PersonImplementation() {}
/**
* Defines the interface of the standard constructor for
* a basic PersonImplementation.
* @param firstName The name(s) of the PersonImplementation
* @param surname The surname of the PersonImplementation
* @param primaryEmail The primary email address of the PersonImplementation
* @throws InvalidEmailException Throws when given an invalid email format
*/
public PersonImplementation(String firstName, String surname, String primaryEmail, boolean isAdmin) throws InvalidEmailException
{
this.categoryAssociations = new ArrayList<ResearcherCategoryAssociationImplementation>();
this.groupAssociations = new ArrayList<ResearchGroupAssociation>();
this.auxiliaryEmails = new ArrayList<String>();
this.firstName = firstName;
this.surname = surname;
String EMAIL_REGEX = "^[-\\w_\\.+]*[-\\w_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if(primaryEmail.matches(EMAIL_REGEX))
this.primaryEmail = primaryEmail;
else throw new InvalidEmailException(primaryEmail + " is not a valid email address.");
this.primaryEmail = primaryEmail;
this.userID = null;
this.isAdmin = isAdmin;
}
/**
* Defines the interface of a constructor for a PersonImplementation
* who has a user object already defined
* @param firstName The name(s) of the PersonImplementation
* @param surname The surname of the PersonImplementation
* @param primaryEmail The primary email address of the PersonImplementation
* @param userID The id of the user object associated with the person
* @throws InvalidEmailException Throws if the given email does not match standard email format
*/
public PersonImplementation(String firstName, String surname, String primaryEmail, BigInteger userID, boolean isAdmin) throws InvalidEmailException
{
this.categoryAssociations = new ArrayList<ResearcherCategoryAssociationImplementation>();
this.groupAssociations = new ArrayList<ResearchGroupAssociation>();
this.auxiliaryEmails = new ArrayList<String>();
this.firstName = firstName;
this.surname = surname;
String EMAIL_REGEX = "^[-\\w_\\.+]*[-\\w_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if(primaryEmail.matches(EMAIL_REGEX))
this.primaryEmail = primaryEmail;
else throw new InvalidEmailException(primaryEmail + " is not a valid email address.");
this.primaryEmail = primaryEmail;
this.userID = userID;
this.isAdmin = isAdmin;
}
//------------------------------------------------------------------
//-------------------------------ADMIN USER STUFF------------------------------------------------
public void addResearcherCategory(ResearchCategoryState researchState)
{
ResearcherCategoryImplementation rs = new ResearcherCategoryImplementation(researchState);
}
public void addResearcherCategoryState(ResearcherCategory researcherCategory, ResearchCategoryState state)
throws UnauthorizedUserExeption
{
if(this.isAdmin)
researcherCategory.addState(state);
else
throw new UnauthorizedUserExeption("This user is not an admin");
}
public void removeResearcherCategoryState(ResearcherCategory researcherCategory, ResearchCategoryState state)
throws UnauthorizedUserExeption
{
if(this.isAdmin)
researcherCategory.removeState(state);
else
throw new UnauthorizedUserExeption("This user is not an admin");
}
public void addCategory(ResearcherCategory category)
{
categoryAssociations.add(new ResearcherCategoryAssociationImplementation(category));
}
public void addCategory(ResearcherCategory category, Date effectiveDate)
throws DateInvalidException
{
categoryAssociations.add(new ResearcherCategoryAssociationImplementation(category, effectiveDate));
}
public void removeCategory(ResearcherCategoryImplementation category)
{
categoryAssociations.remove(category);
}
//-----------------------------------------------------------------------------------------------
//---------------------------MEMBERSHIP MANAGEMENT(Admin and group leader)---------------------------------------
//Admin/leader adds person to group
public void addMemberToGroup(Person member, Group group, ResearchGroupAssociationType type)
throws GroupSuspendedException, UnauthorizedUserExeption, NonMemberExeption
{
int index = -1;
ResearchGroupAssociationType association;
if(this.isAdmin)
member.addGroupAssociation(group, type);
else
{
for(int i = 0; i < this.groupAssociations.size(); i++)
{
if(this.groupAssociations.get(i).getGroup().equals(group))
index = i;
}
if(index == -1)
throw new NonMemberExeption("This user is not a member of this group");
association = this.groupAssociations.get(index).getType();
if(association.equals(ResearchGroupAssociationType.GROUPLEADER))
member.addGroupAssociation(group, type);
else
throw new UnauthorizedUserExeption("This user is not the group leader of this group");
}
}
//Admin/leader adds person to group
public void addMemberToGroup(Person member, Group group, ResearchGroupAssociationType type, Date startDate)
throws DateInvalidException, GroupSuspendedException, UnauthorizedUserExeption, NonMemberExeption
{
int index = -1;
ResearchGroupAssociationType association;
if(this.isAdmin)
member.addGroupAssociation(group, type, startDate);
else
{
for(int i = 0; i < this.groupAssociations.size(); i++)
{
if(this.groupAssociations.get(i).getGroup().equals(group))
index = i;
}
if(index == -1)
throw new NonMemberExeption("This user is not a member of this group");
association = this.groupAssociations.get(index).getType();
if(association.equals(ResearchGroupAssociationType.GROUPLEADER))
member.addGroupAssociation(group, type, startDate);
else
throw new UnauthorizedUserExeption("This user is not the group leader of this group");
}
}
//Admin/leader adds person to group
public void addMemberToGroup(Person member, Group group, ResearchGroupAssociationType type, Date startDate, Date endDate)
throws DateInvalidException, GroupSuspendedException, UnauthorizedUserExeption, NonMemberExeption
{
int index = -1;
ResearchGroupAssociationType association;
if(this.isAdmin)
member.addGroupAssociation(group, type, startDate, endDate);
else
{
for(int i = 0; i < this.groupAssociations.size(); i++)
{
if(this.groupAssociations.get(i).getGroup().equals(group))
index = i;
}
if(index == -1)
throw new NonMemberExeption("This user is not a member of this group");
association = this.groupAssociations.get(index).getType();
if(association.equals(ResearchGroupAssociationType.GROUPLEADER))
member.addGroupAssociation(group, type, startDate);
else
throw new UnauthorizedUserExeption("This user is not the group leader of this group");
}
}
//Admin/leader removes person from group
public void removeMemberFromGroup(Person member, Group group)
throws DateInvalidException, GroupSuspendedException, UnauthorizedUserExeption, NonMemberExeption
{
int index = -1;
ResearchGroupAssociationType association;
if(this.isAdmin)
{
group.removeMember(member);
member.endGroupAssociation(group);
}
else
{
for(int i = 0; i < this.groupAssociations.size(); i++)
{
if(this.groupAssociations.get(i).getGroup().equals(group))
index = i;
}
if(index == -1)
throw new NonMemberExeption("This user is not a member of this group");
association = this.groupAssociations.get(index).getType();
if(association.equals(ResearchGroupAssociationType.GROUPLEADER))
{
group.removeMember(member);
member.endGroupAssociation(group);
}
else
throw new UnauthorizedUserExeption("This user is not the group leader of this group");
}
}
//Admin/leader adds group to super group
public void addGroupToGroup(Group subGroup, Group superGroup, ResearchGroupAssociationType type)
throws GroupSuspendedException, UnauthorizedUserExeption
{
if(this.isAdmin())
superGroup.addMember(subGroup);
else
throw new UnauthorizedUserExeption("This user is not an admin");
}
//function we had before
public void addGroupAssociation(Group group, ResearchGroupAssociationType type)
throws GroupSuspendedException
{
groupAssociations.add(new ResearchGroupAssociationImplementation(group, type));
group.addMember(this);
}
//function we had before
public void addGroupAssociation(Group group, ResearchGroupAssociationType type, Date startDate)
throws DateInvalidException,GroupSuspendedException
{
groupAssociations.add(new ResearchGroupAssociationImplementation(group, type, startDate));
group.addMember(this);
}
//function we had before
public void addGroupAssociation(Group group, ResearchGroupAssociationType type, Date startDate, Date endDate)
throws DateInvalidException, GroupSuspendedException
{
groupAssociations.add(new ResearchGroupAssociationImplementation(group, type, startDate, endDate));
group.addMember(this);
}
//function we had before
public void endGroupAssociation(Group group)
throws GroupSuspendedException
{
groupAssociations.remove(group);
}
//------------------------------------------------------------------
public void suspendGroup(Group group)
throws UnauthorizedUserExeption
{
if(this.isAdmin)
group.suspendGroup();
else
throw new UnauthorizedUserExeption("This user is not an admin");
}
public void activateGroup(Group group)
throws UnauthorizedUserExeption
{
if(this.isAdmin)
group.suspendGroup();
else
throw new UnauthorizedUserExeption("This user is not an admin");
}
//---------------------------GETTERS AND SETTERS---------------------------------------
/**
* Defines a function that returns the firstName of the PersonImplementation
* @return The first name(s) of the PersonImplementation
*/
public String getFirstName() { return this.firstName; }
/**
* Defines a function that returns the surname of the PersonImplementation
* @return The surname of the PersonImplementation
*/
public String getSurmame() { return this.surname; }
/**
* Defines a function that returns the primary email address of the PersonImplementation
* @return The primary email address of the PersonImplementation
*/
public String getPrimaryEmail() { return this.primaryEmail; }
/**
* Defines a function that returns the list of auxiliary email addresses of the PersonImplementation
* @return The primary email address of the PersonImplementation
*/
public List<String> getAuxiliaryEmails() { return this.auxiliaryEmails; }
/**
* Defines a function that returns the user object
* associated with this PersonImplementation
* @return The user object associated with this person
*/
public BigInteger getUserID() { return this.userID; }
public void setFirstName(String firstName){ this.firstName = firstName; }
public void setSurname(String surname){ this.surname = surname;};
public void setPrimaryEmail(String primaryEmail) throws InvalidEmailException
{
String EMAIL_REGEX = "^[-\\w_\\.+]*[-\\w_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if(primaryEmail.matches(EMAIL_REGEX))
this.primaryEmail = primaryEmail;
else throw new InvalidEmailException(primaryEmail + " is not a valid email address.");
this.primaryEmail = primaryEmail;
};
public void setUser(BigInteger userID){ this.userID = userID;};
public void addAuxiliaryEmails(String newEmail){
this.auxiliaryEmails.add(newEmail);
};
public void removeAuxiliaryEmails(String email)
{
this.auxiliaryEmails.remove(email);
};
public void clearAuxiliaryEmails()
{
this.auxiliaryEmails.clear();
};
//------------------------------------------------------------------
public void setAsAdmin()
{
this.isAdmin = true;
};
public boolean isAdmin()
{
return this.isAdmin;
};
/*
* Member variables
*/
/**
* Primary key of the person
*/
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private BigInteger id;
/**
* The person's first name(s)
*/
@Basic
private String firstName;
/**
* The person's surname
*/
@Basic
private String surname;
/**
* The person's primary email address
*/
@Basic
private String primaryEmail;
/**
* A list of secondary email addresses,
* to be added only after person's creation
*/
@ElementCollection
private List<String> auxiliaryEmails;
/**
* An object that contains this person's User
* If it is NULL, this person is just a normal researcher
*/
@Basic
private BigInteger userID;
/**
* A list of this person's research groups (holds ID of the association)
*/
@OneToMany(targetEntity = ResearchGroupAssociationImplementation.class)
private List<ResearchGroupAssociation> groupAssociations;
/**
* A list of this person's research categories
*/
@OneToMany(targetEntity = ResearcherCategoryAssociationImplementation.class)
private List<ResearcherCategoryAssociationImplementation> categoryAssociations;
@Basic
private boolean isAdmin;
}
|
package Models;
public class Discount {
private double discountValue;
private boolean isDeliveryFree = false;
public Discount() {
}
public double getDiscountValue() {
return discountValue;
}
public boolean getIsDeliveryFree() {
return isDeliveryFree;
}
public void setDiscountValue(double value) {
this.discountValue = value;
}
public void setIsDeliveryFree(boolean isFree) {
isDeliveryFree = isFree;
}
}
|
package com.sunny.netty.chat.attribute;
import com.sunny.netty.chat.Session.Session;
import io.netty.util.AttributeKey;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2018/10/25 23:36 <br>
* @see com.sunny.netty.chat.attribute <br>
*/
public interface Attributes {
AttributeKey<Boolean> LOGIN = AttributeKey.newInstance("login");
AttributeKey<Session> SESSION = AttributeKey.newInstance("session");
}
|
/**
* Copyright (C) 2015-2016, Zhichun Wu
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.cassandra.jdbc;
import org.testng.annotations.Test;
import java.util.Properties;
import static com.github.cassandra.jdbc.CassandraConfiguration.*;
import static org.testng.Assert.*;
public class CassandraConfigurationTest {
@Test(groups = {"unit", "base"})
public void testextractDriverConfig() {
Properties props = new Properties();
props.setProperty("hosts", "host1.test.com,host2.test.com,host3.test.com");
props.setProperty("port", "999");
props.setProperty("tracing", "true");
props.setProperty("consistencyLevel", "QUORUM");
CassandraConfiguration.DriverConfig config = generateDriverConfig(props);
assertEquals(config.hosts, "host1.test.com,host2.test.com,host3.test.com");
assertEquals(config.port, 999);
assertEquals(config.tracing, true);
assertEquals(config.consistencyLevel, CassandraEnums.ConsistencyLevel.QUORUM);
}
@Test(groups = {"unit", "base"})
public void testParseConnectionURL() {
String url = "jdbc:c*:mine://host1.a.com:9160,host2.a.com:9170/keyspace1?consistencyLevel=ONE";
try {
Properties props = CassandraConfiguration.parseConnectionURL(url);
assertEquals("mine", props.getProperty(KEY_PROVIDER));
assertEquals("host1.a.com:9160,host2.a.com:9170",
props.getProperty(KEY_HOSTS));
assertEquals("keyspace1", props.getProperty(KEY_KEYSPACE));
assertEquals("ONE", props.getProperty(KEY_CONSISTENCY_LEVEL));
url = "jdbc:c*://host1";
props = CassandraConfiguration.parseConnectionURL(url);
assertNull(props.getProperty(KEY_PROVIDER));
assertEquals("host1", props.getProperty(KEY_HOSTS));
assertNull(props.getProperty(KEY_KEYSPACE));
url = "jdbc:c*://host2/?cc=1";
props = CassandraConfiguration.parseConnectionURL(url);
assertNull(props.getProperty(KEY_PROVIDER));
assertEquals("host2", props.getProperty(KEY_HOSTS));
assertNull(props.getProperty(KEY_KEYSPACE));
assertEquals("1", props.getProperty("cc"));
url = "jdbc:c*://host3/system_auth";
props = CassandraConfiguration.parseConnectionURL(url);
assertNull(props.getProperty(KEY_PROVIDER));
assertEquals("host3", props.getProperty(KEY_HOSTS));
assertEquals("system_auth", props.getProperty(KEY_KEYSPACE));
url = "jdbc:c*://host4?a=b&c=1&consistencyLevel=ANY&compression=lz4&connectionTimeout=10&readTimeout=50&localDc=DD";
props = CassandraConfiguration.parseConnectionURL(url);
assertNull(props.getProperty(KEY_PROVIDER));
assertEquals("host4", props.getProperty(KEY_HOSTS));
assertNull(props.getProperty(KEY_KEYSPACE));
assertEquals("b", props.getProperty("a"));
assertEquals("1", props.getProperty("c"));
assertEquals("ANY", props.getProperty(KEY_CONSISTENCY_LEVEL));
assertEquals("lz4", props.getProperty(KEY_COMPRESSION));
assertEquals("10", props.getProperty(KEY_CONNECTION_TIMEOUT));
assertEquals("50", props.getProperty(KEY_READ_TIMEOUT));
assertEquals("DD", props.getProperty(KEY_LOCAL_DC));
} catch (Exception e) {
e.printStackTrace();
fail("Exception happened during test: " + e.getMessage());
}
}
}
|
package com.player;
public class FXPlayer {
}
|
package com.cloudinte.modules.xingzhengguanli.web;
import com.thinkgem.jeesite.common.config.Global;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.cloudinte.modules.xingzhengguanli.entity.EducationProjectInfo;
import com.cloudinte.modules.xingzhengguanli.service.EducationProjectInfoService;
/**
* 教育教学项目基本信息Controller
* @author dcl
* @version 2019-12-12
*/
@Controller
@RequestMapping(value = "${adminPath}/xingzhengguanli/educationProjectInfo")
public class EducationProjectInfoController extends BaseController {
private static final String FUNCTION_NAME_SIMPLE = "教育教学项目基本信息";
@Autowired
private EducationProjectInfoService educationProjectInfoService;
@ModelAttribute
public EducationProjectInfo get(@RequestParam(required=false) String id) {
EducationProjectInfo entity = null;
if (StringUtils.isNotBlank(id)){
entity = educationProjectInfoService.get(id);
}
if (entity == null){
entity = new EducationProjectInfo();
}
return entity;
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:view")
@RequestMapping(value = {"list", ""})
public String list(EducationProjectInfo educationProjectInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<EducationProjectInfo> page = educationProjectInfoService.findPage(new Page<EducationProjectInfo>(request, response), educationProjectInfo);
model.addAttribute("page", page);
model.addAttribute("ename", "educationProjectInfo");
setBase64EncodedQueryStringToEntity(request, educationProjectInfo);
return "modules/xingzhengguanli/educationProjectInfo/educationProjectInfoList";
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:view")
@RequestMapping(value = "form")
public String form(EducationProjectInfo educationProjectInfo, Model model) {
model.addAttribute("educationProjectInfo", educationProjectInfo);
model.addAttribute("ename", "educationProjectInfo");
return "modules/xingzhengguanli/educationProjectInfo/educationProjectInfoForm";
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "save")
public String save(EducationProjectInfo educationProjectInfo, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, educationProjectInfo)){
return form(educationProjectInfo, model);
}
addMessage(redirectAttributes, StringUtils.isBlank(educationProjectInfo.getId()) ? "保存"+FUNCTION_NAME_SIMPLE+"成功" : "修改"+FUNCTION_NAME_SIMPLE+"成功");
educationProjectInfoService.save(educationProjectInfo);
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "disable")
public String disable(EducationProjectInfo educationProjectInfo, RedirectAttributes redirectAttributes) {
educationProjectInfoService.disable(educationProjectInfo);
addMessage(redirectAttributes, "禁用"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "delete")
public String delete(EducationProjectInfo educationProjectInfo, RedirectAttributes redirectAttributes) {
educationProjectInfoService.delete(educationProjectInfo);
addMessage(redirectAttributes, "删除"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "deleteBatch")
public String deleteBatch(EducationProjectInfo educationProjectInfo, RedirectAttributes redirectAttributes) {
educationProjectInfoService.deleteByIds(educationProjectInfo);
addMessage(redirectAttributes, "批量删除"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
/**
* 导出数据
*/
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "export", method = RequestMethod.POST)
public String exportFile(EducationProjectInfo educationProjectInfo, HttpServletRequest request,
HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = FUNCTION_NAME_SIMPLE + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
educationProjectInfo.setPage(new Page<EducationProjectInfo>(request, response, -1));
new ExportExcel(FUNCTION_NAME_SIMPLE, EducationProjectInfo.class).setDataList(educationProjectInfoService.findList(educationProjectInfo)).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导出" + FUNCTION_NAME_SIMPLE + "失败!失败信息:" + e.getMessage());
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
}
/**
* 下载导入数据模板
*/
@RequiresPermissions("xingzhengguanli:educationProjectInfo:view")
@RequestMapping(value = "import/template")
public String importFileTemplate(EducationProjectInfo educationProjectInfo, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = FUNCTION_NAME_SIMPLE + "导入模板.xlsx";
List<EducationProjectInfo> list = educationProjectInfoService.findPage(new Page<EducationProjectInfo>(1, 5), new EducationProjectInfo()).getList();
if (list == null) {
list = Lists.newArrayList();
}
if (list.size() < 1) {
list.add(new EducationProjectInfo());
}
new ExportExcel(FUNCTION_NAME_SIMPLE, EducationProjectInfo.class).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导入模板下载失败!失败信息:" + e.getMessage());
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
}
/**
* 导入数据<br>
*/
@RequiresPermissions("xingzhengguanli:educationProjectInfo:edit")
@RequestMapping(value = "import", method = RequestMethod.POST)
public String importFile(EducationProjectInfo educationProjectInfo, MultipartFile file, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
try {
long beginTime = System.currentTimeMillis();//1、开始时间
StringBuilder failureMsg = new StringBuilder();
ImportExcel ei = new ImportExcel(file, 1, 0);
List<EducationProjectInfo> list = ei.getDataList(EducationProjectInfo.class);
List<EducationProjectInfo> insertList=new ArrayList<EducationProjectInfo>();
List<EducationProjectInfo> subList=new ArrayList<EducationProjectInfo>();
int batchinsertSize=500;
int batchinsertCount=list.size()/batchinsertSize+(list.size()%batchinsertSize==0?0:1);
int addNum=0;
int updateNum=0;
int toIndex=0;
for(int i=0;i<batchinsertCount;i++)
{
insertList=new ArrayList<EducationProjectInfo>();
toIndex=(i+1)*batchinsertSize;
if(toIndex>list.size())
toIndex=list.size();
subList=list.subList(i*batchinsertSize, toIndex);
for(EducationProjectInfo zsJh : subList)
{
zsJh.preInsert();
insertList.add(zsJh);
}
if(insertList!=null&&insertList.size()>0)
{
System.out.println("insertList size is :"+insertList.size());
educationProjectInfoService.batchInsertUpdate(insertList);
addNum+=insertList.size();
}
}
long endTime = System.currentTimeMillis(); //2、结束时间
addMessage(redirectAttributes, "执行时间"+DateUtils.formatDateTime(endTime - beginTime)+",导入 "+addNum+"条"+FUNCTION_NAME_SIMPLE+"信息,"+failureMsg);
System.out.println("执行时间:"+DateUtils.formatDateTime(endTime - beginTime));
} catch (Exception e) {
addMessage(redirectAttributes, "导入"+FUNCTION_NAME_SIMPLE+"信息失败!失败信息:"+e.getMessage());
}
return "redirect:"+adminPath+"/xingzhengguanli/educationProjectInfo/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(educationProjectInfo));
}
}
|
package com.mhg.weixin.service.impl.msg;
import com.alibaba.fastjson.JSON;
import com.mhg.weixin.bean.enums.MsgTypeEnum;
import com.mhg.weixin.bean.msg.MessageReceiveDO;
import com.mhg.weixin.bean.msg.TextReturnMsgDO;
import com.mhg.weixin.dao.msg.MessageReceiveDOMapper;
import com.mhg.weixin.service.msg.BaseMsgService;
import com.mhg.weixin.utils.WeixinMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import static com.mhg.weixin.bean.enums.MsgTypeEnum.TXET;
/**
* @Classname BaseMsgServiceImpl
* @Description TODO
* @Date 2020/1/29 14:52
* @Created by pwt
*/
@Service
public class BaseMsgServiceImpl implements BaseMsgService {
private static final Logger logger = LoggerFactory.getLogger(BaseMsgServiceImpl.class);
@Autowired
private MessageReceiveDOMapper messageReceiveDOMapper;
@Override
public String msgProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("------------微信消息开始处理-------------");
String respMessage = null;
Map<String, String> map = WeixinMessageUtil.parseXml(request);
MessageReceiveDO messageReceiveDO = new MessageReceiveDO();
messageReceiveDO.setCreateTime(new Date(Integer.parseInt(map.get("CreateTime"))));
messageReceiveDO.setFromUserName(map.get("FromUserName"));
messageReceiveDO.setToUserName(map.get("ToUserName"));
String msgType = map.get("MsgType");
messageReceiveDO.setMsgType(msgType);
messageReceiveDO.setMsgId(Integer.getInteger(map.get("MsgId")));
messageReceiveDO.setMsgContent(JSON.toJSONString(map));
messageReceiveDOMapper.insertSelective(messageReceiveDO);
switch(MsgTypeEnum.getByCode(msgType))
{
case TXET:
logger.info(map.get("Content"));
return null;
default:
break;
}
return null;
}
}
|
package com.gsccs.sme.plat.auth.service;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gsccs.sme.plat.auth.dao.DictGroupTMapper;
import com.gsccs.sme.plat.auth.dao.DictItemTMapper;
import com.gsccs.sme.plat.auth.model.DictGroupT;
import com.gsccs.sme.plat.auth.model.DictGroupTExample;
import com.gsccs.sme.plat.auth.model.DictItemT;
import com.gsccs.sme.plat.auth.model.DictItemExample;
@Service
public class DictServiceImpl implements DictService {
@Autowired
private DictGroupTMapper dictGroupTMapper;
@Autowired
private DictItemTMapper dictItemTMapper;
@Override
public void createDictGroupT(DictGroupT groupT) {
if (null != groupT) {
String code = groupT.getCode();
DictGroupT t = getGroupByCode(code);
if (null != t) { // 已存在
} else {
groupT.setId(UUID.randomUUID().toString());
dictGroupTMapper.insert(groupT);
}
}
}
@Override
public void updateDictGroupT(DictGroupT groupT) {
if (null != groupT) {
dictGroupTMapper.updateByPrimaryKey(groupT);
}
}
@Override
public void deleteDictGroupT(String groupid) {
dictGroupTMapper.deleteByPrimaryKey(groupid);
}
@Override
public DictGroupT getGroupById(String id) {
return dictGroupTMapper.selectByPrimaryKey(id);
}
@Override
public DictGroupT getGroupByTitle(String title) {
return dictGroupTMapper.selectByTitle(title);
}
@Override
public DictGroupT getGroupByCode(String code) {
DictGroupTExample example = new DictGroupTExample();
DictGroupTExample.Criteria c = example.createCriteria();
c.andCodeEqualTo(code);
List<DictGroupT> list = dictGroupTMapper.selectByExample(example);
if (null != list && list.size() > 0) {
return list.get(0);
}
return null;
}
@Override
public List<DictGroupT> findGroupList(DictGroupT param, int page,
int pagesize) {
DictGroupTExample example = new DictGroupTExample();
DictGroupTExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictGroupTMapper.selectByExample(example);
}
@Override
public void createDictItemT(DictItemT dictItem) {
if (null != dictItem) {
dictItem.setId(UUID.randomUUID().toString());
dictItemTMapper.insert(dictItem);
}
}
@Override
public void updateDictItemT(DictItemT dictItem) {
dictItemTMapper.updateByPrimaryKey(dictItem);
}
@Override
public void deleteDictItemT(String id) {
dictItemTMapper.deleteByPrimaryKey(id);
}
@Override
public DictItemT getDictById(String id) {
return dictItemTMapper.selectByPrimaryKey(id);
}
@Override
public List<DictItemT> findItemList(DictItemT param, int page, int pagesize) {
DictItemExample example = new DictItemExample();
DictItemExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictItemTMapper.selectByExample(example);
}
public void proSearchParam(DictGroupT dictGroupT,
DictGroupTExample.Criteria criteria) {
if (null != dictGroupT) {
if (StringUtils.isNotEmpty(dictGroupT.getCode())) {
criteria.andCodeEqualTo(dictGroupT.getCode());
}
if (StringUtils.isNotEmpty(dictGroupT.getStatus())) {
criteria.andStatusEqualTo(dictGroupT.getStatus());
}
}
}
public void proSearchParam(DictItemT dictItemT,
DictItemExample.Criteria criteria) {
if (null != dictItemT) {
if (StringUtils.isNotEmpty(dictItemT.getCode())) {
criteria.andCodeEqualTo(dictItemT.getCode());
}
if (StringUtils.isNotEmpty(dictItemT.getGroupid())) {
criteria.andGroupidEqualTo(dictItemT.getGroupid());
}
}
}
@Override
public Integer countDictGroup(DictGroupT param) {
DictGroupTExample example = new DictGroupTExample();
DictGroupTExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictGroupTMapper.countByExample(example);
}
@Override
public Integer countDictItem(DictItemT param) {
DictItemExample example = new DictItemExample();
DictItemExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictItemTMapper.countByExample(example);
}
@Override
public List<DictItemT> getDictItems(String code) {
DictGroupTExample example = new DictGroupTExample();
DictGroupTExample.Criteria c = example.createCriteria();
c.andCodeEqualTo(code);
List<DictGroupT> list = dictGroupTMapper.selectByExample(example);
if (null != list && list.size() > 0) {
DictItemExample example2 = new DictItemExample();
DictItemExample.Criteria c2 = example2.createCriteria();
c2.andGroupidEqualTo(list.get(0).getId());
return dictItemTMapper.selectByExample(example2);
}
return null;
}
@Override
public List<DictGroupT> findGroupList(DictGroupT param) {
DictGroupTExample example = new DictGroupTExample();
DictGroupTExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictGroupTMapper.selectByExample(example);
}
@Override
public List<DictItemT> findItemList(DictItemT param) {
DictItemExample example = new DictItemExample();
DictItemExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictItemTMapper.selectByExample(example);
}
@Override
public List<DictItemT> findGroupAndItemList(DictItemT param) {
DictItemExample example = new DictItemExample();
DictItemExample.Criteria c = example.createCriteria();
proSearchParam(param, c);
return dictItemTMapper.selectGroupAndItemList(example);
}
@Override
public List<DictItemT> findDictlist(String ids) {
if (StringUtils.isNotEmpty(ids)) {
String[] idArray = ids.split(",");
if (null != idArray && idArray.length > 0) {
List<String> idlist = Arrays.asList(idArray);
for (String id : idlist) {
if (StringUtils.isEmpty(id)) {
idlist.remove(id);
}
}
if (null != idlist && idlist.size() > 0) {
DictItemExample example = new DictItemExample();
DictItemExample.Criteria c = example.createCriteria();
c.andIdIn(idlist);
return dictItemTMapper.selectByExample(example);
}
}
}
return null;
}
@Override
public List<DictItemT> getDictItemsByCode(String code,DictItemT dictItem) {
DictGroupT dictGroup=dictGroupTMapper.selectByCode(code);
dictItem.setGroupid(dictGroup.getId());
return findItemList(dictItem);
}
}
|
package in.ponram.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import in.ponram.dao.UserRepository;
import in.ponram.model.User;
import in.ponram.validator.UserManagerValidation;
@Service
public class UserManager {
@Autowired
UserRepository userRepository;
/**
* This method is used to call user validation class Then the validation is
* success call addUser method to store the details
*
* @param user
* @return true or false
*/
public User registration(User user) {
User save = null;
if (UserManagerValidation.isValideUserDetails(user)) {
save = userRepository.save(user);
}
return save;
}
/**
* This method is used to call the call login validation to verify the user
*
* @param userName
* @param password
* @return true if the user exists
* @throws Exception
*/
public User login(String userName, String password) {
User user = userRepository.findByUsername(userName).orElse(null);
return user != null && UserManagerValidation.isValidLogin(user, password) ? user : null;
}
/**
* This method is used to call the call Admin login validation to verify the
* user is admin
*
* @param userName
* @param password
* @return true if the user exists
* @throws Exception
*/
public User adminLogin(String userName, String password) {
User admin = userRepository.findByUsername(userName).orElse(null);
return admin != null && UserManagerValidation.isAdminUser(admin, password) ? admin : null;
}
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
}
|
/**
* Package for junior.pack1.p5.ch3.task3.1 Организовать сортировку User.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-05-12
*/
package ru.job4j.sorting;
|
/**
* Array bound operations : Queue
* Ver 1.0: added multiplication: 2016/09/19.
* @author : Panchami Rudrakshi
*/
public class Queue<T> {
int front,rear,max;
T[] arr;
//Constructor to create array with size of 16
public Queue()
{
max=16;
arr = (T[]) new Object[max];
front=-1;
rear=-1;
}
public boolean isEmpty()
{
//returns true if array size is less than 20% of its size
int j=(int) (0.2*(max-1));
if(rear == j)
{
return true;}
else return false;
}
public boolean IsFull()
{
//returns true if array size is 90% of its size
int j=(int) (0.9*(max-1));
if(rear == j)
{
return true;}
else return false;
}
public void offer(T i)
{
//adding an element
if (front==-1&&rear==-1)
{
System.out.println("element added front:" + i);
front = rear = 0;
arr[rear] = i;
return;
}
//Invariant : if array is 90% full, resize the array
if(IsFull())
{
resize(max*2);
System.out.println("element added resizing:" + i);
arr[++rear] = i;
}
else {
//Invariant : adding the element to the queue
System.out.println("element added normal:" + i);
rear = (rear+1)%max;
arr[rear] = i;
}
}
public T poll()
{
//Invariant : if array is just 20% full, shrink the array
if(isEmpty()){
shrink();
return null;
}
//Invariant : if array is empty set front and rear to -1
else if(front == rear )
{
rear = front = -1;
return null;
}
//Invariant : pop the top element from the queue
else {
front = (front)%max;
T x= (T) arr[front];
front++;
System.out.println("Popped element:" + x);
return x;}
}
public void resize(int i)
{
//Invariant : create an object of size i
T[] arr1 = (T[]) new Object[i];
//Invariant : copy elements from array
for (int j = 0; j <=rear; j++)
{
arr1[j] = arr[j];
}
arr = arr1;
max=i;
//pointing array to null such that array memory is free
arr1=null;
System.out.println("size resized to :" +max);
}
public void shrink()
{
int i=max/2;
//Invariant : maintaining minimum array size of 16
if(i<=16) i=16;
else i=max/2;
//Invariant : create an object of size i
T[] arr1 = (T[]) new Object[i];
//Invariant : copy elements from array
for (int j = 0; j <=rear; j++)
{
arr1[j] = arr[j];
}
arr = arr1;
max=i;
//pointing array to null such that array memory is free
arr1=null;
System.out.println("size shrinked to :" +max);
}
public void printlist()
{
//printing the queue elements
for (int j = 0; j <=rear; j++)
{
System.out.println("check : "+ arr[j]);
}
}
public static void main(String[] args) {
Queue<Integer> lst = new Queue<>();
lst.offer(10);
lst.poll();
lst.printlist();
lst.offer(20);
lst.offer(30);
lst.offer(40);
}
}
|
/*
* ServiceBus inter-component communication bus
*
* Copyright (c) 2021- Rob Ruchte, rob@thirdpartylabs.com
*
* Licensed under the License specified in file LICENSE, included with the source code.
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thirdpartylabs.servicebus.threadtest;
import com.thirdpartylabs.servicebus.ServiceBus;
import com.thirdpartylabs.servicebus.requests.AdditionServiceBusRequest;
import com.thirdpartylabs.servicebus.reqres.RequestSubscription;
import java.util.ArrayList;
import java.util.List;
/**
* Manager for the pooled responder threaded bus test
* <p>
* The specified number of responders and generators will be created, and the generators will perform
* the specified number of iterations.
* <p>
* The responders will all operate on the set of channels provided by a subscription, each working in its own thread.
* Results from the operations will be stored for analysis. The unit test should compare the expected results to the
* actual results produced.
*/
public class ResponderPoolTestController
{
private final EventObserver eventObserver;
private final EventListenerWorker eventListenerWorker;
private final GeneratorWorker[] generators;
private final ArrayList<RequestResponderChannelWorker> requestResponderWorkers;
// Number of generators to spawn
private final int generatorCount;
// Number of responders to spawn
private final int responderCount;
// Number of times the generators should perform their operations
private final int iterations;
private final RequestSubscription<AdditionServiceBusRequest> subscription;
/**
* @param generatorCount Number of generators to spawn
* @param responderCount Number of responders to spawn
* @param iterations Number of times the generator should perform its operations
*/
public ResponderPoolTestController(int generatorCount, int responderCount, int iterations)
{
this.generatorCount = generatorCount;
this.responderCount = responderCount;
this.iterations = iterations;
// The event observer stays in this thread and listens to all of the events
eventObserver = new EventObserver();
// The event listener worker is essentially identical to the observer, but its listener runs in a worker thread
eventListenerWorker = new EventListenerWorker();
// These worker runs a generate requests on the bus
requestResponderWorkers = new ArrayList<>(responderCount);
subscription = ServiceBus.getInstance().reqRes.subscribe(AdditionServiceBusRequest.class);
for (int i = 0; i < responderCount; i++)
{
requestResponderWorkers.add(new RequestResponderChannelWorker(subscription));
}
// These workers generate traffic on the bus - configure them to send requests only for this test
generators = new GeneratorWorker[generatorCount];
for (int i = 0; i < generatorCount; i++)
{
generators[i] = new GeneratorWorker(iterations, false, true, false);
}
}
/**
* Run the workers
*/
public void run()
{
/*
* First start the workers that run listeners/handlers on the bus. Since those facilities are registered
* when the thread starts running, they require a brief period of time to initialize. They will set ready
* flags when their initialization is complete.
*/
eventListenerWorker.start();
// Wait until our workers set up their listeners on the bus, then start the generator
while (!eventListenerWorker.isReady())
{
try
{
Thread.sleep(10);
Thread.yield();
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Start up the responders
for (RequestResponderChannelWorker currWorker : requestResponderWorkers)
{
currWorker.start();
}
// Fire it up!
for (GeneratorWorker currGenerator : generators)
{
currGenerator.start();
}
// Block this thead until the generators set their complete flag and the workers finish their queues
boolean generatorsComplete = false;
while (!generatorsComplete || eventListenerWorker.isWorking())
{
try
{
// Iterate through the generators, if any are still working, set the complete flag false
generatorsComplete = true;
for (GeneratorWorker currWorker : generators)
{
if (!currWorker.isComplete())
{
generatorsComplete = false;
break;
}
}
/*
If the generators are still working, scale the worker pool size then sleep a while
*/
if (!generatorsComplete)
{
int freeWorkers = 0;
for(RequestResponderChannelWorker currWorker : requestResponderWorkers)
{
if(!currWorker.isWorking())
{
// Kill ~.5 idle workers
if(Math.random() < .5)
{
requestResponderWorkers.remove(currWorker);
currWorker.stop();
}
else
{
freeWorkers++;
}
}
}
if(freeWorkers < 2)
{
RequestResponderChannelWorker newWorker = new RequestResponderChannelWorker(subscription);
newWorker.start();
requestResponderWorkers.add(newWorker);
}
Thread.sleep(100);
}
Thread.yield();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Stop the event listener worker
eventListenerWorker.stop();
}
/**
* @return The number of iterations specified for the generator
*/
public int getIterations()
{
return iterations;
}
public int getGeneratorCount()
{
return generatorCount;
}
/**
* @return The expected number of items generated for each type
*/
public int getExpectedItemCount()
{
return iterations * generatorCount;
}
/**
* @return The expected number of generated events
*/
public int getExpectedEventCount()
{
return iterations * generatorCount;
}
/**
* @return The number of events that the observer received
*/
public int getObserverEventCount()
{
return eventObserver.getReceivedEvents().size();
}
/**
* @return The number of events that the log worker received
*/
public int getLogWorkerEventCount()
{
return eventListenerWorker.getReceivedEvents().size();
}
/**
* @return The collection of expected to actual request-response calculations
*/
public List<int[]> getCalculatorWorkerCalculations()
{
List<int[]> output = new ArrayList<>();
for (RequestResponderChannelWorker currWorker : requestResponderWorkers)
{
output.addAll(currWorker.getCalculations());
}
return output;
}
/**
* @return The collection of expected to actual request-response calculations
*/
public List<int[]> getGeneratorCalculations()
{
List<int[]> output = new ArrayList<>();
for (GeneratorWorker currGenerator : generators)
{
output.addAll(currGenerator.getCalculations());
}
return output;
}
}
|
package steps;
import cucumber.api.DataTable;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class ScenarioSteps {
MainPageSteps mainPageSteps = new MainPageSteps();
TravelInsurancePageSteps travelInsuranceSteps = new TravelInsurancePageSteps();
TravelInsuranceSendFormSteps travelInsuranceSendFormSteps = new TravelInsuranceSendFormSteps();
@When("^выбран пункт меню \"(.+)\"$")
public void selectMenuItem(String menuName) {
mainPageSteps.selectMenuItem(menuName);
}
@When("^выбран вид страхования \"(.+)\"$")
public void selectMenuInsurance(String menuName) {
mainPageSteps.selectMenuInsurance(menuName);
}
@When("^закрыто информационное окно$")
public void closeCookieWindow() {
mainPageSteps.closeCookieWindow();
}
@Then("^заголовок страницы - Страхование путешественников равен \"(.+)\"$")
public void checkTitleDMSPage(String title) {
travelInsuranceSteps.checkPageTitle(title);
}
@When("^выполнено нажатие на кнопку \"(.+)\"$")
public void clickBtnSendApp(String name) {
travelInsuranceSteps.clickButton(name);
}
@Then("^заголовок страницы - Заявка на Страхование путешественников равен \"(.+)\"$")
public void checkTitleSendAppPage(String title) {
travelInsuranceSendFormSteps.checkPageTitle(title);
}
@When("^выбрана сумма страховой защиты – Минимальная$")
public void selectMinimal() {
travelInsuranceSendFormSteps.selectMinimal();
}
@When("^заполняются поля:$")
public void fillForm(DataTable fields) {
fields.asMap(String.class, String.class)
.forEach((field, value) -> travelInsuranceSendFormSteps.fillField(field, value));
}
@Then("^значения полей равны:$")
public void checkFillForm(DataTable fields) {
fields.asMap(String.class, String.class)
.forEach((field, value) -> travelInsuranceSendFormSteps.checkFillField(field, value));
}
@Then("^присутствует сообщение об ошибке \"(.+)\"$")
public void checkErrorMessage(String errorMessage) {
travelInsuranceSendFormSteps.checkErrorMessage(errorMessage);
}
@Then("^в полях присутствуют сообщения об ошибке:$")
public void checkFieldsErrorMessage(DataTable fields) {
fields.asMap(String.class, String.class)
.forEach((field, errorMessage) -> {
travelInsuranceSendFormSteps.checkFieldErrorMessage(field, errorMessage);
});
}
@When("^выбран пол \"(.+)\"$")
public void selectGender(String sex) {
travelInsuranceSendFormSteps.selectGender(sex);
}
}
|
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.client.v8.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
/**
* TimeSeriesMetadata
*/
public class TimeSeriesMetadata {
@SerializedName("metricName")
private String metricName = null;
@SerializedName("entityName")
private String entityName = null;
@SerializedName("startTime")
private DateTime startTime = null;
@SerializedName("endTime")
private DateTime endTime = null;
@SerializedName("attributes")
private Map<String, String> attributes = null;
@SerializedName("unitNumerators")
private List<String> unitNumerators = null;
@SerializedName("unitDenominators")
private List<String> unitDenominators = null;
@SerializedName("expression")
private String expression = null;
@SerializedName("alias")
private String alias = null;
@SerializedName("metricCollectionFrequencyMs")
private Long metricCollectionFrequencyMs = null;
@SerializedName("rollupUsed")
private String rollupUsed = null;
public TimeSeriesMetadata() {
// Do nothing
}
private TimeSeriesMetadata(TimeSeriesMetadataBuilder builder) {
this.metricName = builder.metricName;
this.entityName = builder.entityName;
this.startTime = builder.startTime;
this.endTime = builder.endTime;
this.attributes = builder.attributes;
this.unitNumerators = builder.unitNumerators;
this.unitDenominators = builder.unitDenominators;
this.expression = builder.expression;
this.alias = builder.alias;
this.metricCollectionFrequencyMs = builder.metricCollectionFrequencyMs;
this.rollupUsed = builder.rollupUsed;
}
public static TimeSeriesMetadataBuilder builder() {
return new TimeSeriesMetadataBuilder();
}
public static class TimeSeriesMetadataBuilder {
private String metricName = null;
private String entityName = null;
private DateTime startTime = null;
private DateTime endTime = null;
private Map<String, String> attributes = new HashMap<String, String>();
private List<String> unitNumerators = new ArrayList<String>();
private List<String> unitDenominators = new ArrayList<String>();
private String expression = null;
private String alias = null;
private Long metricCollectionFrequencyMs = null;
private String rollupUsed = null;
public TimeSeriesMetadataBuilder metricName(String metricName) {
this.metricName = metricName;
return this;
}
public TimeSeriesMetadataBuilder entityName(String entityName) {
this.entityName = entityName;
return this;
}
public TimeSeriesMetadataBuilder startTime(DateTime startTime) {
this.startTime = startTime;
return this;
}
public TimeSeriesMetadataBuilder endTime(DateTime endTime) {
this.endTime = endTime;
return this;
}
public TimeSeriesMetadataBuilder attributes(Map<String, String> attributes) {
this.attributes = attributes;
return this;
}
public TimeSeriesMetadataBuilder unitNumerators(List<String> unitNumerators) {
this.unitNumerators = unitNumerators;
return this;
}
public TimeSeriesMetadataBuilder unitDenominators(List<String> unitDenominators) {
this.unitDenominators = unitDenominators;
return this;
}
public TimeSeriesMetadataBuilder expression(String expression) {
this.expression = expression;
return this;
}
public TimeSeriesMetadataBuilder alias(String alias) {
this.alias = alias;
return this;
}
public TimeSeriesMetadataBuilder metricCollectionFrequencyMs(Long metricCollectionFrequencyMs) {
this.metricCollectionFrequencyMs = metricCollectionFrequencyMs;
return this;
}
public TimeSeriesMetadataBuilder rollupUsed(String rollupUsed) {
this.rollupUsed = rollupUsed;
return this;
}
public TimeSeriesMetadata build() {
return new TimeSeriesMetadata(this);
}
}
public TimeSeriesMetadataBuilder toBuilder() {
return builder()
.metricName(metricName)
.entityName(entityName)
.startTime(startTime)
.endTime(endTime)
.attributes(attributes)
.unitNumerators(unitNumerators)
.unitDenominators(unitDenominators)
.expression(expression)
.alias(alias)
.metricCollectionFrequencyMs(metricCollectionFrequencyMs)
.rollupUsed(rollupUsed)
;
}
public TimeSeriesMetadata metricName(String metricName) {
this.metricName = metricName;
return this;
}
/**
* Metric name
* @return metricName
**/
@ApiModelProperty(required = true, value = "Metric name")
public String getMetricName() {
return metricName;
}
public void setMetricName(String metricName) {
this.metricName = metricName;
}
public TimeSeriesMetadata entityName(String entityName) {
this.entityName = entityName;
return this;
}
/**
* Entity name
* @return entityName
**/
@ApiModelProperty(required = true, value = "Entity name")
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public TimeSeriesMetadata startTime(DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Start time
* @return startTime
**/
@ApiModelProperty(required = true, value = "Start time")
public DateTime getStartTime() {
return startTime;
}
public void setStartTime(DateTime startTime) {
this.startTime = startTime;
}
public TimeSeriesMetadata endTime(DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* End time
* @return endTime
**/
@ApiModelProperty(required = true, value = "End time")
public DateTime getEndTime() {
return endTime;
}
public void setEndTime(DateTime endTime) {
this.endTime = endTime;
}
public TimeSeriesMetadata attributes(Map<String, String> attributes) {
this.attributes = attributes;
return this;
}
public TimeSeriesMetadata putAttributesItem(String key, String attributesItem) {
if (this.attributes == null) {
this.attributes = new HashMap<String, String>();
}
this.attributes.put(key, attributesItem);
return this;
}
/**
* Attributes
* @return attributes
**/
@ApiModelProperty(value = "Attributes")
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public TimeSeriesMetadata unitNumerators(List<String> unitNumerators) {
this.unitNumerators = unitNumerators;
return this;
}
public TimeSeriesMetadata addUnitNumeratorsItem(String unitNumeratorsItem) {
if (this.unitNumerators == null) {
this.unitNumerators = new ArrayList<String>();
}
this.unitNumerators.add(unitNumeratorsItem);
return this;
}
/**
* Unit numerators
* @return unitNumerators
**/
@ApiModelProperty(value = "Unit numerators")
public List<String> getUnitNumerators() {
return unitNumerators;
}
public void setUnitNumerators(List<String> unitNumerators) {
this.unitNumerators = unitNumerators;
}
public TimeSeriesMetadata unitDenominators(List<String> unitDenominators) {
this.unitDenominators = unitDenominators;
return this;
}
public TimeSeriesMetadata addUnitDenominatorsItem(String unitDenominatorsItem) {
if (this.unitDenominators == null) {
this.unitDenominators = new ArrayList<String>();
}
this.unitDenominators.add(unitDenominatorsItem);
return this;
}
/**
* Unit denominators
* @return unitDenominators
**/
@ApiModelProperty(value = "Unit denominators")
public List<String> getUnitDenominators() {
return unitDenominators;
}
public void setUnitDenominators(List<String> unitDenominators) {
this.unitDenominators = unitDenominators;
}
public TimeSeriesMetadata expression(String expression) {
this.expression = expression;
return this;
}
/**
* Expression
* @return expression
**/
@ApiModelProperty(required = true, value = "Expression")
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public TimeSeriesMetadata alias(String alias) {
this.alias = alias;
return this;
}
/**
* Alias
* @return alias
**/
@ApiModelProperty(value = "Alias")
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public TimeSeriesMetadata metricCollectionFrequencyMs(Long metricCollectionFrequencyMs) {
this.metricCollectionFrequencyMs = metricCollectionFrequencyMs;
return this;
}
/**
* Metric collection frequency in milliseconds
* @return metricCollectionFrequencyMs
**/
@ApiModelProperty(value = "Metric collection frequency in milliseconds")
public Long getMetricCollectionFrequencyMs() {
return metricCollectionFrequencyMs;
}
public void setMetricCollectionFrequencyMs(Long metricCollectionFrequencyMs) {
this.metricCollectionFrequencyMs = metricCollectionFrequencyMs;
}
public TimeSeriesMetadata rollupUsed(String rollupUsed) {
this.rollupUsed = rollupUsed;
return this;
}
/**
* Rollup used
* @return rollupUsed
**/
@ApiModelProperty(required = true, value = "Rollup used")
public String getRollupUsed() {
return rollupUsed;
}
public void setRollupUsed(String rollupUsed) {
this.rollupUsed = rollupUsed;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimeSeriesMetadata timeSeriesMetadata = (TimeSeriesMetadata) o;
return Objects.equals(this.metricName, timeSeriesMetadata.metricName) &&
Objects.equals(this.entityName, timeSeriesMetadata.entityName) &&
Objects.equals(this.startTime, timeSeriesMetadata.startTime) &&
Objects.equals(this.endTime, timeSeriesMetadata.endTime) &&
Objects.equals(this.attributes, timeSeriesMetadata.attributes) &&
Objects.equals(this.unitNumerators, timeSeriesMetadata.unitNumerators) &&
Objects.equals(this.unitDenominators, timeSeriesMetadata.unitDenominators) &&
Objects.equals(this.expression, timeSeriesMetadata.expression) &&
Objects.equals(this.alias, timeSeriesMetadata.alias) &&
Objects.equals(this.metricCollectionFrequencyMs, timeSeriesMetadata.metricCollectionFrequencyMs) &&
Objects.equals(this.rollupUsed, timeSeriesMetadata.rollupUsed);
}
@Override
public int hashCode() {
return Objects.hash(metricName, entityName, startTime, endTime, attributes, unitNumerators, unitDenominators, expression, alias, metricCollectionFrequencyMs, rollupUsed);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TimeSeriesMetadata {\n");
sb.append(" metricName: ").append(toIndentedString(metricName)).append("\n");
sb.append(" entityName: ").append(toIndentedString(entityName)).append("\n");
sb.append(" startTime: ").append(toIndentedString(startTime)).append("\n");
sb.append(" endTime: ").append(toIndentedString(endTime)).append("\n");
sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n");
sb.append(" unitNumerators: ").append(toIndentedString(unitNumerators)).append("\n");
sb.append(" unitDenominators: ").append(toIndentedString(unitDenominators)).append("\n");
sb.append(" expression: ").append(toIndentedString(expression)).append("\n");
sb.append(" alias: ").append(toIndentedString(alias)).append("\n");
sb.append(" metricCollectionFrequencyMs: ").append(toIndentedString(metricCollectionFrequencyMs)).append("\n");
sb.append(" rollupUsed: ").append(toIndentedString(rollupUsed)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.newlec.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginController implements Controller {
@Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("LoginController");
return "dispatcher:/joinus/login.jsp";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.