blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a18d9d081fa89d20e6c58befc6207685b60fc07 | 33,827,162,437,054 | ba2b9f1077d7261a6550e3ca37bb89450ddd104b | /covetools-android/src/main/java/com/cyphercove/gdx/covetools/android/LiveWallpaperInfoActivity.java | da6bdedc6ab68ebf68940defcd28be3b5059b555 | [
"Apache-2.0"
]
| permissive | CypherCove/gdx-cclibs | https://github.com/CypherCove/gdx-cclibs | 012f8cc5abc824af97b3ff8a8c592dd2114a14cc | 5af681453c88af0907ff28afa8998451f97051d2 | refs/heads/master | 2021-01-11T19:49:58.943000 | 2019-05-28T01:43:50 | 2019-05-28T01:43:50 | 79,408,436 | 11 | 6 | Apache-2.0 | false | 2019-05-21T22:45:12 | 2017-01-19T02:48:08 | 2019-05-11T09:20:49 | 2019-05-21T22:45:11 | 2,209 | 9 | 4 | 3 | Java | false | false | /*******************************************************************************
* Copyright 2017 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.cyphercove.gdx.covetools.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
/** An activity that opens the live wallpaper chooser list, or a specific live wallpaper's preview on Jelly Bean and later.
* Intended to be used as the application's {@code android.intent.category.INFO} Activity if the application does not have
* a launcher Activity, which a typical situation for a primarily live wallpaper application. If the device does not
* support live wallpapers, a Toast will inform the user. If on an API before Jelly Bean, a toast will instruct the user
* to select the live wallpaper from the list. The messages for these toasts are provided by the abstract methods.
*/
public abstract class LiveWallpaperInfoActivity extends Activity {
/** @return The resource ID for the message that is shown if the user is brought to the live wallpaper chooser list. */
protected abstract int getWallpaperChooserToastStringResource();
/** @return The class representing the live wallpaper. */
protected abstract Class getWallpaperServiceClass();
/** @return The resource ID for the message that is shown if the device does not support live wallpapers. */
protected abstract int getNoLiveWallpapersToastStringResource();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkForWallpaperChooser()){
Toast.makeText(getApplicationContext(),
getNoLiveWallpapersToastStringResource(),
Toast.LENGTH_LONG)
.show();
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
openWallpaperChooser();
} else {
openWallpaperPreview();
}
finish();
}
private boolean checkForWallpaperChooser() {
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
return intent.resolveActivity(getPackageManager()) != null;
}
private void openWallpaperChooser() {
Toast.makeText(getApplicationContext(),
getWallpaperChooserToastStringResource(),
Toast.LENGTH_LONG)
.show();
Intent i = new Intent();
i.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
startActivity(i);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void openWallpaperPreview() {
String packageName = getPackageName();
ComponentName componentName = new ComponentName(packageName,
getWallpaperServiceClass().getCanonicalName());
Intent i = new Intent();
i.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
i.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, componentName);
startActivity(i);
}
}
| UTF-8 | Java | 3,624 | java | LiveWallpaperInfoActivity.java | Java | []
| null | []
| /*******************************************************************************
* Copyright 2017 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.cyphercove.gdx.covetools.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
/** An activity that opens the live wallpaper chooser list, or a specific live wallpaper's preview on Jelly Bean and later.
* Intended to be used as the application's {@code android.intent.category.INFO} Activity if the application does not have
* a launcher Activity, which a typical situation for a primarily live wallpaper application. If the device does not
* support live wallpapers, a Toast will inform the user. If on an API before Jelly Bean, a toast will instruct the user
* to select the live wallpaper from the list. The messages for these toasts are provided by the abstract methods.
*/
public abstract class LiveWallpaperInfoActivity extends Activity {
/** @return The resource ID for the message that is shown if the user is brought to the live wallpaper chooser list. */
protected abstract int getWallpaperChooserToastStringResource();
/** @return The class representing the live wallpaper. */
protected abstract Class getWallpaperServiceClass();
/** @return The resource ID for the message that is shown if the device does not support live wallpapers. */
protected abstract int getNoLiveWallpapersToastStringResource();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkForWallpaperChooser()){
Toast.makeText(getApplicationContext(),
getNoLiveWallpapersToastStringResource(),
Toast.LENGTH_LONG)
.show();
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
openWallpaperChooser();
} else {
openWallpaperPreview();
}
finish();
}
private boolean checkForWallpaperChooser() {
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
return intent.resolveActivity(getPackageManager()) != null;
}
private void openWallpaperChooser() {
Toast.makeText(getApplicationContext(),
getWallpaperChooserToastStringResource(),
Toast.LENGTH_LONG)
.show();
Intent i = new Intent();
i.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
startActivity(i);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void openWallpaperPreview() {
String packageName = getPackageName();
ComponentName componentName = new ComponentName(packageName,
getWallpaperServiceClass().getCanonicalName());
Intent i = new Intent();
i.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
i.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, componentName);
startActivity(i);
}
}
| 3,624 | 0.714128 | 0.711921 | 87 | 40.655174 | 33.338329 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.356322 | false | false | 15 |
c76737bd01f063f01a9f74e314c644cedcafb355 | 34,918,084,128,803 | fdab15ab269976a647e5c6d61ca773d67cc89685 | /dygl/src/main/java/com/goldgov/dygl/module/partyorganization/partybranch/web/PartyBranchController_AA_A_B.java | a8dbf2053af106fd7935ee6e93731ac034ef531d | []
| no_license | monkmonk/sh | https://github.com/monkmonk/sh | f3dcc5fec608b2cdae48c493a6c48bb2908b78d9 | d84a29960dc8d721d00d8bf707b35fe2c83219ff | refs/heads/master | 2018-03-21T11:31:23.114000 | 2016-08-19T09:08:54 | 2016-08-19T09:08:54 | 66,069,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.goldgov.dygl.module.partyorganization.partybranch.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AA_A;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AD_B_A;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AE;
import com.goldgov.dygl.module.partyorganization.partybranch.service.MeetingMemberBean;
import com.goldgov.dygl.module.partyorganization.partybranch.service.PartyBranchQuery;
import com.goldgov.dygl.module.partyorganization.web.BasePartyOrganizationController;
import com.goldgov.gtiles.core.service.SortField.SortDirection;
import com.goldgov.gtiles.core.web.GoTo;
import com.goldgov.gtiles.core.web.OperatingType;
import com.goldgov.gtiles.core.web.annotation.ModelQuery;
import com.goldgov.gtiles.core.web.annotation.ModuleOperating;
import com.goldgov.gtiles.core.web.annotation.ModuleResource;
import com.goldgov.gtiles.module.businessfield.service.BusinessField;
@SuppressWarnings("unchecked")
@RequestMapping("/module/partyBranch/baaab")
@Controller("partyBranchController_AA_A_B")
@ModuleResource(name="三会一课_专题会议")
public class PartyBranchController_AA_A_B extends BasePartyOrganizationController {
public static final String PAGE_BASE_PATH = "partyorganization/partybranch/web/pages/";
private String infoType = "AA_A_B";
@Autowired
@Qualifier("partyBranchService_AA_A")
private IPartyBranchService_AA_A partyBranchService_AA_A;
@Autowired
@Qualifier("partyBranchServiceImpl_AE")
private IPartyBranchService_AE partyBranchSearvice_AE;
@Autowired
@Qualifier("partyBranchServiceImpl_AD_B_A")
private IPartyBranchService_AD_B_A partyBranchSearvice_AD_B_A;
@RequestMapping("/addInfo")
@ModuleOperating(name="信息添加",type=OperatingType.Save)
public String addInfo(Model model,HttpServletRequest request,MeetingMemberBean bean) throws NoAuthorizedFieldException{
Map<String,Object> paramsMap = buildAttachmentParamsMap(request);
if(bean.getABSENT_MEMBER()!=null && bean.getABSENT_MEMBER().length>0){
String [] absenceTypeStr = request.getParameterValues("absenceTypeStr");
int i = 0;
String absentMember = "";
String absenceType = ""; //缺席类型
String businessIdStr = ""; //因公缺席
String privateaffIdStr = ""; //因私缺席
for(String str:bean.getABSENT_MEMBER()){
absentMember += str+"##&##";
absenceType+=absenceTypeStr[i]+",";
if(absenceTypeStr[i].equals("1")){
businessIdStr += str+",";
}else if(absenceTypeStr[i].equals("2")){
privateaffIdStr += str+",";
}
i++;
}
bean.setAbsenceType(absenceType.substring(0, absenceType.length()-1));
bean.setBusinessId(businessIdStr!=""?businessIdStr.substring(0,businessIdStr.length()-1):null);
bean.setPrivateaffId(privateaffIdStr!=""?privateaffIdStr.substring(0,privateaffIdStr.length()-1):null);
bean.setABSENT_MEMBER_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_MEMBER_TEXT()!=null && bean.getABSENT_MEMBER_TEXT().length>0){
String absentMember = "";
for(String str:bean.getABSENT_MEMBER_TEXT()){
absentMember += str+"##&##";
}
bean.setABSENT_MEMBER_TEXT_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_REASON()!=null && bean.getABSENT_REASON().length>0){
String absentMember = "";
for(String str:bean.getABSENT_REASON()){
absentMember += str+"##&##";
}
bean.setABSENT_REASON_STR(absentMember.substring(0, absentMember.length()-5));
}
paramsMap = isOrganizationalLife(paramsMap,bean);
partyBranchService_AA_A.addInfo(paramsMap,bean);
return new GoTo(this).sendForward("findInfoList");
}
@RequestMapping("/findInfo")
@ModuleOperating(name="信息查看",type=OperatingType.Find)
public String preUpdate(@ModelQuery("query") PartyBranchQuery partyBranchQuery, String id, Model model, HttpServletRequest request) throws NoAuthorizedFieldException{
String partyOrganizationID = request.getParameter("partyOrganizationID");
List<BusinessField> fields = null;
String uuid = "";
if(id != null && !id.isEmpty()){
fields = partyBranchService_AA_A.findInfoById(id);
model.addAttribute("entityID",id);
for (BusinessField businessField : fields) {
if(businessField.getFieldName().equals("MEETING_UUID")){
uuid=businessField.getFieldValue()!=null?businessField.getFieldValue().toString():"";
}
}
MeetingMemberBean bean = partyBranchService_AA_A.fingMeetingMember(id);
if(bean!=null && bean.getABSENT_MEMBER_STR()!=null && !"".equals(bean.getABSENT_MEMBER_STR())){
bean.setABSENT_MEMBER(bean.getABSENT_MEMBER_STR().split("##&##"));
bean.setABSENT_MEMBER_TEXT(bean.getABSENT_MEMBER_TEXT_STR().split("##&##"));
if(bean.getABSENT_REASON_STR()!=null && !"".equals(bean.getABSENT_REASON_STR())){
bean.setABSENT_REASON(bean.getABSENT_REASON_STR().split("##&##"));
}
String[] type =bean.getAbsenceType()!=null? bean.getAbsenceType().split(","):null;
List<MeetingMemberBean> list = new ArrayList<MeetingMemberBean>();
for(int i=0;i<bean.getABSENT_MEMBER().length;i++){
MeetingMemberBean meeting = new MeetingMemberBean();
if(type!=null){
meeting.setAbsenceType(type[i]);
}
meeting.setAbsentUser(bean.getABSENT_MEMBER()[i]);
meeting.setAbsentUserName(bean.getABSENT_MEMBER_TEXT()[i]);
if(bean.getABSENT_REASON()!=null && !(bean.getABSENT_REASON().length<i+1)){
meeting.setAbsentReason(bean.getABSENT_REASON()[i]);
}
list.add(meeting);
}
bean.setBeanList(list);
}
if(bean!=null){
model.addAttribute("meetingMemberBean", bean);
}
}else{
fields = partyBranchService_AA_A.preAddInfo();
}
partyBranchSearvice_AE.setBusinessFieldPurview(id, partyOrganizationID, fields);
model.addAttribute("fields",fields);
if(uuid.isEmpty()){
uuid=UUID.randomUUID().toString().replace("-", "");
}
model.addAttribute("uuid", uuid);
return new GoTo(this).sendPage("partyBranchForm_" + infoType + ".ftl");
}
@RequestMapping("/findInfoDetail")
@ModuleOperating(name="信息查看",type=OperatingType.Find)
public String findInfoDetail(String id, Model model, HttpServletRequest request) throws NoAuthorizedFieldException{
List<BusinessField> fields = partyBranchService_AA_A.preAddInfo();
request.setAttribute("searchType", request.getParameter("searchType"));
if(id != null && !id.isEmpty()){
fields = partyBranchService_AA_A.findInfoById(id);
model.addAttribute("entityID",id);
MeetingMemberBean bean = partyBranchService_AA_A.fingMeetingMember(id);
if(bean!=null && bean.getABSENT_MEMBER_STR()!=null && !"".equals(bean.getABSENT_MEMBER_STR())){
bean.setABSENT_MEMBER(bean.getABSENT_MEMBER_STR().split("##&##"));
bean.setABSENT_MEMBER_TEXT(bean.getABSENT_MEMBER_TEXT_STR().split("##&##"));
if(bean.getABSENT_REASON_STR()!=null && !"".equals(bean.getABSENT_REASON_STR())){
bean.setABSENT_REASON(bean.getABSENT_REASON_STR().split("##&##"));
}
String[] type =bean.getAbsenceType()!=null? bean.getAbsenceType().split(","):null;
List<MeetingMemberBean> list = new ArrayList<MeetingMemberBean>();
for(int i=0;i<bean.getABSENT_MEMBER().length;i++){
MeetingMemberBean meeting = new MeetingMemberBean();
if(type!=null){
meeting.setAbsenceType(type[i]);
}
meeting.setAbsentUser(bean.getABSENT_MEMBER()[i]);
meeting.setAbsentUserName(bean.getABSENT_MEMBER_TEXT()[i]);
// if(bean.getABSENT_REASON()!=null&&!(bean.getABSENT_REASON().length<i+1)){
// meeting.setAbsentReason(bean.getABSENT_REASON()[i]);
// }
list.add(meeting);
}
bean.setBeanList(list);
}
if(bean!=null){
model.addAttribute("meetingMemberBean", bean);
}
}
model.addAttribute("readOnly","readOnly");//会议页面只读
for (BusinessField businessField : fields) {
businessField.setReadOnly(true);
}
String partyOrganizationID = request.getParameter("partyOrganizationID");
partyBranchSearvice_AE.setBusinessFieldPurview(id, partyOrganizationID, fields);
model.addAttribute("fields",fields);
return new GoTo(this).sendPage("partyBranchDetail_AA_A.ftl");
}
@RequestMapping("/findInfoList")
public String findInfoList(@ModelQuery("query") PartyBranchQuery partyBranchQuery, HttpServletRequest request) throws NoAuthorizedFieldException{
partyBranchQuery.setPageSize(5);
if(partyBranchQuery.getSortFields() != null){
if(partyBranchQuery.getSortFields()[0].getDirection() == SortDirection.DESC)
request.setAttribute("direction", "desc");
else
request.setAttribute("direction", "asc");
}
List<Map<String, Object>> resultList = partyBranchService_AA_A.findInfoList(partyBranchQuery, request.getParameterMap());
partyBranchQuery.setResultList(resultList);
if(resultList != null && !resultList.isEmpty())
request.setAttribute("entityID", resultList.get(0).get("entityID"));
return new GoTo(this).sendPage("partyBranchList_" + infoType + ".ftl");
}
@RequestMapping("/updateInfo")
@ModuleOperating(name="信息修改",type=OperatingType.Update)
public String updateInfo(Model model,@RequestParam("entityID") String id,HttpServletRequest request,MeetingMemberBean bean) throws NoAuthorizedFieldException{
Map<String,Object> paramsMap = buildAttachmentParamsMap(request);
if(bean.getABSENT_MEMBER()!=null && bean.getABSENT_MEMBER().length>0){
String [] absenceTypeStr = request.getParameterValues("absenceTypeStr");
int i = 0;
String absentMember = "";
String absenceType = ""; //缺席类型
String businessIdStr = ""; //因公缺席
String privateaffIdStr = ""; //因私缺席
for(String str:bean.getABSENT_MEMBER()){
absentMember += str+"##&##";
absenceType+=absenceTypeStr[i]+",";
if(absenceTypeStr[i].equals("1")){
businessIdStr += str+",";
}else if(absenceTypeStr[i].equals("2")){
privateaffIdStr += str+",";
}
i++;
}
bean.setAbsenceType(absenceType.substring(0, absenceType.length()-1));
bean.setBusinessId(businessIdStr!=""?businessIdStr.substring(0,businessIdStr.length()-1):null);
bean.setPrivateaffId(privateaffIdStr!=""?privateaffIdStr.substring(0,privateaffIdStr.length()-1):null);
bean.setABSENT_MEMBER_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_MEMBER_TEXT()!=null && bean.getABSENT_MEMBER_TEXT().length>0){
String absentMember = "";
for(String str:bean.getABSENT_MEMBER_TEXT()){
absentMember += str+"##&##";
}
bean.setABSENT_MEMBER_TEXT_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_REASON()!=null && bean.getABSENT_REASON().length>0){
String absentMember = "";
for(String str:bean.getABSENT_REASON()){
absentMember += str+"##&##";
}
bean.setABSENT_REASON_STR(absentMember.substring(0, absentMember.length()-5));
}
paramsMap = isOrganizationalLife(paramsMap,bean);
partyBranchService_AA_A.updateInfo(id, paramsMap,bean);
return new GoTo(this).sendForward("findInfoList");
}
@RequestMapping("/deleteInfo")
@ModuleOperating(name="信息删除",type=OperatingType.Delete)
public String deleteBusinessTable(String ids, HttpServletRequest request) throws NoAuthorizedFieldException{
if(ids!=null&&!ids.equals("")){
partyBranchService_AA_A.deleteInfo(ids.split(","));
}
return new GoTo(this).sendForward("findInfoList");
}
}
| UTF-8 | Java | 12,278 | java | PartyBranchController_AA_A_B.java | Java | []
| null | []
| package com.goldgov.dygl.module.partyorganization.partybranch.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AA_A;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AD_B_A;
import com.goldgov.dygl.module.partyorganization.partybranch.service.IPartyBranchService_AE;
import com.goldgov.dygl.module.partyorganization.partybranch.service.MeetingMemberBean;
import com.goldgov.dygl.module.partyorganization.partybranch.service.PartyBranchQuery;
import com.goldgov.dygl.module.partyorganization.web.BasePartyOrganizationController;
import com.goldgov.gtiles.core.service.SortField.SortDirection;
import com.goldgov.gtiles.core.web.GoTo;
import com.goldgov.gtiles.core.web.OperatingType;
import com.goldgov.gtiles.core.web.annotation.ModelQuery;
import com.goldgov.gtiles.core.web.annotation.ModuleOperating;
import com.goldgov.gtiles.core.web.annotation.ModuleResource;
import com.goldgov.gtiles.module.businessfield.service.BusinessField;
@SuppressWarnings("unchecked")
@RequestMapping("/module/partyBranch/baaab")
@Controller("partyBranchController_AA_A_B")
@ModuleResource(name="三会一课_专题会议")
public class PartyBranchController_AA_A_B extends BasePartyOrganizationController {
public static final String PAGE_BASE_PATH = "partyorganization/partybranch/web/pages/";
private String infoType = "AA_A_B";
@Autowired
@Qualifier("partyBranchService_AA_A")
private IPartyBranchService_AA_A partyBranchService_AA_A;
@Autowired
@Qualifier("partyBranchServiceImpl_AE")
private IPartyBranchService_AE partyBranchSearvice_AE;
@Autowired
@Qualifier("partyBranchServiceImpl_AD_B_A")
private IPartyBranchService_AD_B_A partyBranchSearvice_AD_B_A;
@RequestMapping("/addInfo")
@ModuleOperating(name="信息添加",type=OperatingType.Save)
public String addInfo(Model model,HttpServletRequest request,MeetingMemberBean bean) throws NoAuthorizedFieldException{
Map<String,Object> paramsMap = buildAttachmentParamsMap(request);
if(bean.getABSENT_MEMBER()!=null && bean.getABSENT_MEMBER().length>0){
String [] absenceTypeStr = request.getParameterValues("absenceTypeStr");
int i = 0;
String absentMember = "";
String absenceType = ""; //缺席类型
String businessIdStr = ""; //因公缺席
String privateaffIdStr = ""; //因私缺席
for(String str:bean.getABSENT_MEMBER()){
absentMember += str+"##&##";
absenceType+=absenceTypeStr[i]+",";
if(absenceTypeStr[i].equals("1")){
businessIdStr += str+",";
}else if(absenceTypeStr[i].equals("2")){
privateaffIdStr += str+",";
}
i++;
}
bean.setAbsenceType(absenceType.substring(0, absenceType.length()-1));
bean.setBusinessId(businessIdStr!=""?businessIdStr.substring(0,businessIdStr.length()-1):null);
bean.setPrivateaffId(privateaffIdStr!=""?privateaffIdStr.substring(0,privateaffIdStr.length()-1):null);
bean.setABSENT_MEMBER_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_MEMBER_TEXT()!=null && bean.getABSENT_MEMBER_TEXT().length>0){
String absentMember = "";
for(String str:bean.getABSENT_MEMBER_TEXT()){
absentMember += str+"##&##";
}
bean.setABSENT_MEMBER_TEXT_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_REASON()!=null && bean.getABSENT_REASON().length>0){
String absentMember = "";
for(String str:bean.getABSENT_REASON()){
absentMember += str+"##&##";
}
bean.setABSENT_REASON_STR(absentMember.substring(0, absentMember.length()-5));
}
paramsMap = isOrganizationalLife(paramsMap,bean);
partyBranchService_AA_A.addInfo(paramsMap,bean);
return new GoTo(this).sendForward("findInfoList");
}
@RequestMapping("/findInfo")
@ModuleOperating(name="信息查看",type=OperatingType.Find)
public String preUpdate(@ModelQuery("query") PartyBranchQuery partyBranchQuery, String id, Model model, HttpServletRequest request) throws NoAuthorizedFieldException{
String partyOrganizationID = request.getParameter("partyOrganizationID");
List<BusinessField> fields = null;
String uuid = "";
if(id != null && !id.isEmpty()){
fields = partyBranchService_AA_A.findInfoById(id);
model.addAttribute("entityID",id);
for (BusinessField businessField : fields) {
if(businessField.getFieldName().equals("MEETING_UUID")){
uuid=businessField.getFieldValue()!=null?businessField.getFieldValue().toString():"";
}
}
MeetingMemberBean bean = partyBranchService_AA_A.fingMeetingMember(id);
if(bean!=null && bean.getABSENT_MEMBER_STR()!=null && !"".equals(bean.getABSENT_MEMBER_STR())){
bean.setABSENT_MEMBER(bean.getABSENT_MEMBER_STR().split("##&##"));
bean.setABSENT_MEMBER_TEXT(bean.getABSENT_MEMBER_TEXT_STR().split("##&##"));
if(bean.getABSENT_REASON_STR()!=null && !"".equals(bean.getABSENT_REASON_STR())){
bean.setABSENT_REASON(bean.getABSENT_REASON_STR().split("##&##"));
}
String[] type =bean.getAbsenceType()!=null? bean.getAbsenceType().split(","):null;
List<MeetingMemberBean> list = new ArrayList<MeetingMemberBean>();
for(int i=0;i<bean.getABSENT_MEMBER().length;i++){
MeetingMemberBean meeting = new MeetingMemberBean();
if(type!=null){
meeting.setAbsenceType(type[i]);
}
meeting.setAbsentUser(bean.getABSENT_MEMBER()[i]);
meeting.setAbsentUserName(bean.getABSENT_MEMBER_TEXT()[i]);
if(bean.getABSENT_REASON()!=null && !(bean.getABSENT_REASON().length<i+1)){
meeting.setAbsentReason(bean.getABSENT_REASON()[i]);
}
list.add(meeting);
}
bean.setBeanList(list);
}
if(bean!=null){
model.addAttribute("meetingMemberBean", bean);
}
}else{
fields = partyBranchService_AA_A.preAddInfo();
}
partyBranchSearvice_AE.setBusinessFieldPurview(id, partyOrganizationID, fields);
model.addAttribute("fields",fields);
if(uuid.isEmpty()){
uuid=UUID.randomUUID().toString().replace("-", "");
}
model.addAttribute("uuid", uuid);
return new GoTo(this).sendPage("partyBranchForm_" + infoType + ".ftl");
}
@RequestMapping("/findInfoDetail")
@ModuleOperating(name="信息查看",type=OperatingType.Find)
public String findInfoDetail(String id, Model model, HttpServletRequest request) throws NoAuthorizedFieldException{
List<BusinessField> fields = partyBranchService_AA_A.preAddInfo();
request.setAttribute("searchType", request.getParameter("searchType"));
if(id != null && !id.isEmpty()){
fields = partyBranchService_AA_A.findInfoById(id);
model.addAttribute("entityID",id);
MeetingMemberBean bean = partyBranchService_AA_A.fingMeetingMember(id);
if(bean!=null && bean.getABSENT_MEMBER_STR()!=null && !"".equals(bean.getABSENT_MEMBER_STR())){
bean.setABSENT_MEMBER(bean.getABSENT_MEMBER_STR().split("##&##"));
bean.setABSENT_MEMBER_TEXT(bean.getABSENT_MEMBER_TEXT_STR().split("##&##"));
if(bean.getABSENT_REASON_STR()!=null && !"".equals(bean.getABSENT_REASON_STR())){
bean.setABSENT_REASON(bean.getABSENT_REASON_STR().split("##&##"));
}
String[] type =bean.getAbsenceType()!=null? bean.getAbsenceType().split(","):null;
List<MeetingMemberBean> list = new ArrayList<MeetingMemberBean>();
for(int i=0;i<bean.getABSENT_MEMBER().length;i++){
MeetingMemberBean meeting = new MeetingMemberBean();
if(type!=null){
meeting.setAbsenceType(type[i]);
}
meeting.setAbsentUser(bean.getABSENT_MEMBER()[i]);
meeting.setAbsentUserName(bean.getABSENT_MEMBER_TEXT()[i]);
// if(bean.getABSENT_REASON()!=null&&!(bean.getABSENT_REASON().length<i+1)){
// meeting.setAbsentReason(bean.getABSENT_REASON()[i]);
// }
list.add(meeting);
}
bean.setBeanList(list);
}
if(bean!=null){
model.addAttribute("meetingMemberBean", bean);
}
}
model.addAttribute("readOnly","readOnly");//会议页面只读
for (BusinessField businessField : fields) {
businessField.setReadOnly(true);
}
String partyOrganizationID = request.getParameter("partyOrganizationID");
partyBranchSearvice_AE.setBusinessFieldPurview(id, partyOrganizationID, fields);
model.addAttribute("fields",fields);
return new GoTo(this).sendPage("partyBranchDetail_AA_A.ftl");
}
@RequestMapping("/findInfoList")
public String findInfoList(@ModelQuery("query") PartyBranchQuery partyBranchQuery, HttpServletRequest request) throws NoAuthorizedFieldException{
partyBranchQuery.setPageSize(5);
if(partyBranchQuery.getSortFields() != null){
if(partyBranchQuery.getSortFields()[0].getDirection() == SortDirection.DESC)
request.setAttribute("direction", "desc");
else
request.setAttribute("direction", "asc");
}
List<Map<String, Object>> resultList = partyBranchService_AA_A.findInfoList(partyBranchQuery, request.getParameterMap());
partyBranchQuery.setResultList(resultList);
if(resultList != null && !resultList.isEmpty())
request.setAttribute("entityID", resultList.get(0).get("entityID"));
return new GoTo(this).sendPage("partyBranchList_" + infoType + ".ftl");
}
@RequestMapping("/updateInfo")
@ModuleOperating(name="信息修改",type=OperatingType.Update)
public String updateInfo(Model model,@RequestParam("entityID") String id,HttpServletRequest request,MeetingMemberBean bean) throws NoAuthorizedFieldException{
Map<String,Object> paramsMap = buildAttachmentParamsMap(request);
if(bean.getABSENT_MEMBER()!=null && bean.getABSENT_MEMBER().length>0){
String [] absenceTypeStr = request.getParameterValues("absenceTypeStr");
int i = 0;
String absentMember = "";
String absenceType = ""; //缺席类型
String businessIdStr = ""; //因公缺席
String privateaffIdStr = ""; //因私缺席
for(String str:bean.getABSENT_MEMBER()){
absentMember += str+"##&##";
absenceType+=absenceTypeStr[i]+",";
if(absenceTypeStr[i].equals("1")){
businessIdStr += str+",";
}else if(absenceTypeStr[i].equals("2")){
privateaffIdStr += str+",";
}
i++;
}
bean.setAbsenceType(absenceType.substring(0, absenceType.length()-1));
bean.setBusinessId(businessIdStr!=""?businessIdStr.substring(0,businessIdStr.length()-1):null);
bean.setPrivateaffId(privateaffIdStr!=""?privateaffIdStr.substring(0,privateaffIdStr.length()-1):null);
bean.setABSENT_MEMBER_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_MEMBER_TEXT()!=null && bean.getABSENT_MEMBER_TEXT().length>0){
String absentMember = "";
for(String str:bean.getABSENT_MEMBER_TEXT()){
absentMember += str+"##&##";
}
bean.setABSENT_MEMBER_TEXT_STR(absentMember.substring(0, absentMember.length()-5));
}
if(bean.getABSENT_REASON()!=null && bean.getABSENT_REASON().length>0){
String absentMember = "";
for(String str:bean.getABSENT_REASON()){
absentMember += str+"##&##";
}
bean.setABSENT_REASON_STR(absentMember.substring(0, absentMember.length()-5));
}
paramsMap = isOrganizationalLife(paramsMap,bean);
partyBranchService_AA_A.updateInfo(id, paramsMap,bean);
return new GoTo(this).sendForward("findInfoList");
}
@RequestMapping("/deleteInfo")
@ModuleOperating(name="信息删除",type=OperatingType.Delete)
public String deleteBusinessTable(String ids, HttpServletRequest request) throws NoAuthorizedFieldException{
if(ids!=null&&!ids.equals("")){
partyBranchService_AA_A.deleteInfo(ids.split(","));
}
return new GoTo(this).sendForward("findInfoList");
}
}
| 12,278 | 0.716494 | 0.712958 | 267 | 43.55056 | 32.320496 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.172285 | false | false | 15 |
aeb1115cf783b4f864c40f627b11eb87cbe31ace | 16,346,645,589,283 | 66d3955099848949e3581d018c67e2c290aa434e | /stu_reg_sys/src/main/java/com/curtisnewbie/model/Course.java | 7366f2942c16da5650b9c609204e60c644ba45f0 | [
"Apache-2.0"
]
| permissive | CurtisNewbie/student_registration_system | https://github.com/CurtisNewbie/student_registration_system | 92e642764a08312684ae0d3f4ef4950d9e9e5cf8 | 546418da2af82d8878901ddbc5ac53f1f98823e8 | refs/heads/master | 2021-05-17T13:55:27.395000 | 2020-04-17T07:05:06 | 2020-04-17T07:05:06 | 250,808,399 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.curtisnewbie.model;
/**
* ------------------------------------
*
* Author: Yongjie Zhuang
*
* ------------------------------------
* <p>
* Course representation
* </p>
*/
public class Course {
private int id;
private String name;
private int credit;
/** Foreign key that references to a {@code School} */
private int schoolFk;
/** Foreign key that references to a {@code Lecturer} */
private int lecturerFk;
/**
*
* @param id set to {@link Dao#GENERATED_ID} if it needs to be
* auto-generated
* @param name
* @param credit
* @param schoolId id of {@link com.curtisnewbie.model.School}
* @param lecturerId id of {@link com.curtisnewbie.model.Lecturer}
*/
public Course(int id, String name, int credit, int schoolId, int lecturerId) {
this.id = id;
this.name = name;
this.credit = credit;
this.schoolFk = schoolId;
this.lecturerFk = lecturerId;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the credit
*/
public int getCredit() {
return credit;
}
/**
* @param credit the credit to set
*/
public void setCredit(int credit) {
this.credit = credit;
}
/**
* @return the schoolFk
*/
public int getSchoolFk() {
return schoolFk;
}
/**
* @param schoolFk the schoolFk to set
*/
public void setSchoolFk(int schoolFk) {
this.schoolFk = schoolFk;
}
/**
* @return the lecturerFk
*/
public int getLecturerFk() {
return lecturerFk;
}
/**
* @param lecturerFk the lecturerFk to set
*/
public void setLecturerFk(int lecturerFk) {
this.lecturerFk = lecturerFk;
}
@Override
public String toString() {
return String.format("Id: %d, Name: %s, Credit: %d", getId(), getName(), getCredit());
}
} | UTF-8 | Java | 2,340 | java | Course.java | Java | [
{
"context": "-----------------------------------\n * \n * Author: Yongjie Zhuang\n * \n * ------------------------------------\n * <p",
"end": 106,
"score": 0.9998152852058411,
"start": 92,
"tag": "NAME",
"value": "Yongjie Zhuang"
}
]
| null | []
| package com.curtisnewbie.model;
/**
* ------------------------------------
*
* Author: <NAME>
*
* ------------------------------------
* <p>
* Course representation
* </p>
*/
public class Course {
private int id;
private String name;
private int credit;
/** Foreign key that references to a {@code School} */
private int schoolFk;
/** Foreign key that references to a {@code Lecturer} */
private int lecturerFk;
/**
*
* @param id set to {@link Dao#GENERATED_ID} if it needs to be
* auto-generated
* @param name
* @param credit
* @param schoolId id of {@link com.curtisnewbie.model.School}
* @param lecturerId id of {@link com.curtisnewbie.model.Lecturer}
*/
public Course(int id, String name, int credit, int schoolId, int lecturerId) {
this.id = id;
this.name = name;
this.credit = credit;
this.schoolFk = schoolId;
this.lecturerFk = lecturerId;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the credit
*/
public int getCredit() {
return credit;
}
/**
* @param credit the credit to set
*/
public void setCredit(int credit) {
this.credit = credit;
}
/**
* @return the schoolFk
*/
public int getSchoolFk() {
return schoolFk;
}
/**
* @param schoolFk the schoolFk to set
*/
public void setSchoolFk(int schoolFk) {
this.schoolFk = schoolFk;
}
/**
* @return the lecturerFk
*/
public int getLecturerFk() {
return lecturerFk;
}
/**
* @param lecturerFk the lecturerFk to set
*/
public void setLecturerFk(int lecturerFk) {
this.lecturerFk = lecturerFk;
}
@Override
public String toString() {
return String.format("Id: %d, Name: %s, Credit: %d", getId(), getName(), getCredit());
}
} | 2,332 | 0.519658 | 0.519658 | 115 | 19.356522 | 19.021357 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269565 | false | false | 15 |
c33ef93bae78bfe5ec56e62a245ce221db16004b | 29,532,195,134,787 | 8cc9dd33296e34dfb00f4fa6829706afc92d03b2 | /src/main/java/com/softserve/edu/Resources/controller/LookUpController.java | 02f45fd88c463a9200337a993eba2c521dffabf0 | []
| no_license | rkhom/Resources | https://github.com/rkhom/Resources | ec2e9f2c0d37f0e8f5d4fea080debb1bf0736178 | 30864e2a6d74af9d13dd2bb8f151e37015705ca2 | refs/heads/master | 2021-08-14T13:44:55.414000 | 2017-11-15T21:48:46 | 2017-11-15T21:48:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.softserve.edu.Resources.controller;
import com.softserve.edu.Resources.dto.ExceptionJSONInfo;
import com.softserve.edu.Resources.dto.GenericResourceDTO;
import com.softserve.edu.Resources.dto.GroupedResourceCount;
import com.softserve.edu.Resources.entity.ConstrainedProperty;
import com.softserve.edu.Resources.entity.GenericResource;
import com.softserve.edu.Resources.entity.ResourceProperty;
import com.softserve.edu.Resources.entity.ResourceType;
import com.softserve.edu.Resources.exception.ResourceNotFoundException;
import com.softserve.edu.Resources.service.ResourceService;
import com.softserve.edu.Resources.service.ResourceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping(value = "/api/resources/lookup", method = RequestMethod.GET)
public class LookUpController {
@Autowired
ResourceTypeService resourceTypeService;
@Autowired
ResourceService resourceService;
@RequestMapping(value = "/resourcetypes/{resourceTypeId}", method = RequestMethod.GET)
public List<ResourceProperty> loadSpecResourceProperty(@PathVariable String resourceTypeId) {
ResourceType resourceType = resourceTypeService.findWithPropertiesByID(Long.parseLong(resourceTypeId));
if (resourceType == null) {
throw new ResourceNotFoundException("No resourece type was found by your request");
}
List<ConstrainedProperty> constraintProperties = resourceTypeService.getSearchableProperties(resourceType);
List<ResourceProperty> resourceProperties = new ArrayList<>();
for (ConstrainedProperty constraint : constraintProperties) {
resourceProperties.add(constraint.getProperty());
}
if (resourceProperties.isEmpty()) {
throw new ResourceNotFoundException("No resource properties were found by your request");
}
Collections.sort(resourceProperties);
return resourceProperties;
}
@RequestMapping(value = "/inputedvalues/foundresources", method = RequestMethod.POST)
public List<GenericResource> getValuesFromForm(@RequestBody GenericResourceDTO resourceDTO) {
List<GenericResource> genResList = resourceService.findResourcesByResourceType(resourceDTO);
if (genResList.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return genResList;
}
@RequestMapping(value = "/owners/{ownerId}/groupedresources", method = RequestMethod.GET)
public List<GroupedResourceCount> findAllOwnerResourcesGroupedByResourceType(@PathVariable String ownerId) {
List<GroupedResourceCount> groupedResources = resourceService
.findResourcesCountGroupedByResourceTypeForOwner(ownerId);
if (groupedResources.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return groupedResources;
}
@RequestMapping(value = "/owners/{ownerId}/resourcetypes/{resourceTypeName}/foundresources", method = RequestMethod.GET)
public List<GenericResource> lookUpByOwner(@PathVariable long ownerId, @PathVariable String resourceTypeName) {
List<GenericResource> genericResources = resourceService.findResourcesByOwnerAndType(ownerId, resourceTypeName);
if (genericResources.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return genericResources;
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ExceptionJSONInfo noInfoFound(ResourceNotFoundException e) {
String message = e.getMessage();
ExceptionJSONInfo exceptionJson = new ExceptionJSONInfo();
exceptionJson.setMessage(message);
return exceptionJson;
}
}
| UTF-8 | Java | 4,182 | java | LookUpController.java | Java | []
| null | []
| package com.softserve.edu.Resources.controller;
import com.softserve.edu.Resources.dto.ExceptionJSONInfo;
import com.softserve.edu.Resources.dto.GenericResourceDTO;
import com.softserve.edu.Resources.dto.GroupedResourceCount;
import com.softserve.edu.Resources.entity.ConstrainedProperty;
import com.softserve.edu.Resources.entity.GenericResource;
import com.softserve.edu.Resources.entity.ResourceProperty;
import com.softserve.edu.Resources.entity.ResourceType;
import com.softserve.edu.Resources.exception.ResourceNotFoundException;
import com.softserve.edu.Resources.service.ResourceService;
import com.softserve.edu.Resources.service.ResourceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping(value = "/api/resources/lookup", method = RequestMethod.GET)
public class LookUpController {
@Autowired
ResourceTypeService resourceTypeService;
@Autowired
ResourceService resourceService;
@RequestMapping(value = "/resourcetypes/{resourceTypeId}", method = RequestMethod.GET)
public List<ResourceProperty> loadSpecResourceProperty(@PathVariable String resourceTypeId) {
ResourceType resourceType = resourceTypeService.findWithPropertiesByID(Long.parseLong(resourceTypeId));
if (resourceType == null) {
throw new ResourceNotFoundException("No resourece type was found by your request");
}
List<ConstrainedProperty> constraintProperties = resourceTypeService.getSearchableProperties(resourceType);
List<ResourceProperty> resourceProperties = new ArrayList<>();
for (ConstrainedProperty constraint : constraintProperties) {
resourceProperties.add(constraint.getProperty());
}
if (resourceProperties.isEmpty()) {
throw new ResourceNotFoundException("No resource properties were found by your request");
}
Collections.sort(resourceProperties);
return resourceProperties;
}
@RequestMapping(value = "/inputedvalues/foundresources", method = RequestMethod.POST)
public List<GenericResource> getValuesFromForm(@RequestBody GenericResourceDTO resourceDTO) {
List<GenericResource> genResList = resourceService.findResourcesByResourceType(resourceDTO);
if (genResList.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return genResList;
}
@RequestMapping(value = "/owners/{ownerId}/groupedresources", method = RequestMethod.GET)
public List<GroupedResourceCount> findAllOwnerResourcesGroupedByResourceType(@PathVariable String ownerId) {
List<GroupedResourceCount> groupedResources = resourceService
.findResourcesCountGroupedByResourceTypeForOwner(ownerId);
if (groupedResources.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return groupedResources;
}
@RequestMapping(value = "/owners/{ownerId}/resourcetypes/{resourceTypeName}/foundresources", method = RequestMethod.GET)
public List<GenericResource> lookUpByOwner(@PathVariable long ownerId, @PathVariable String resourceTypeName) {
List<GenericResource> genericResources = resourceService.findResourcesByOwnerAndType(ownerId, resourceTypeName);
if (genericResources.isEmpty()) {
throw new ResourceNotFoundException("No infromation was found by your request");
}
return genericResources;
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ExceptionJSONInfo noInfoFound(ResourceNotFoundException e) {
String message = e.getMessage();
ExceptionJSONInfo exceptionJson = new ExceptionJSONInfo();
exceptionJson.setMessage(message);
return exceptionJson;
}
}
| 4,182 | 0.73649 | 0.73649 | 103 | 38.60194 | 37.008617 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456311 | false | false | 15 |
977a0eff4c2eea2b6c8030d292014564df26f630 | 26,362,509,275,044 | 2062b5b845fb965ee1cecb2c25db9adfaf323937 | /app/src/main/java/man/animalize/ngdaypic/DayPicItemFragment.java | 5d578e5ca56f3edecb1305bf45c31a3663cce4df | []
| no_license | QuietClickCode/NGDayPic | https://github.com/QuietClickCode/NGDayPic | a5b9daf07c3981decf5dc39e931d0e4b5cd9a6c5 | fe8f0fc051afb18167400c6e2d230a11f46fce5a | refs/heads/master | 2020-08-20T02:09:54.057000 | 2019-10-02T13:57:15 | 2019-10-02T13:57:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package man.animalize.ngdaypic;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import java.util.HashMap;
import java.util.Locale;
import man.animalize.ngdaypic.Base.DayPicItem;
import man.animalize.ngdaypic.Utility.FileReadWrite;
import static android.speech.tts.TextToSpeech.OnInitListener;
import static android.speech.tts.TextToSpeech.QUEUE_FLUSH;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class DayPicItemFragment
extends Fragment
implements OnInitListener {
private static final String TAG = "DayPicItemFragment";
private static final int TTSCHECKSUM = 1234;
private TextView mTextView;
private DayPicItem mItem;
private byte[] mJpg;
private Bitmap mBmp;
private ImageView mImageView;
private TextToSpeech mTts;
// tts的事件处理
private UtteranceProgressListener ttslistener = new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
getActivity().invalidateOptionsMenu();
}
@Override
public void onError(String utteranceId) {
}
};
public DayPicItemFragment() {
// Required empty public constructor
}
// 供DayPicItemActivity调用
public static DayPicItemFragment newInstance(DayPicItem item) {
Bundle arg = new Bundle();
arg.putSerializable("item", item);
DayPicItemFragment f = new DayPicItemFragment();
f.setArguments(arg);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// 得到参数item
Bundle arg = getArguments();
mItem = (DayPicItem) arg.getSerializable("item");
// 图片
if (mItem.getIcon() != null)
mJpg = FileReadWrite.readFile(mItem.get_id() + ".jpg");
// tts
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTSCHECKSUM);
}
// 创建tts实例
protected void instanceTTS() {
mTts = new TextToSpeech(getActivity(), this);
mTts.setOnUtteranceProgressListener(ttslistener);
}
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == TTSCHECKSUM) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
instanceTTS();
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onPause() {
if (mTts != null && mTts.isSpeaking())
mTts.stop();
super.onPause();
}
// TextToSpeech.OnInitListener的接口
@Override
public void onDestroy() {
if (mTts != null)
mTts.shutdown();
super.onDestroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the main_menu for this fragment
View v = inflater.inflate(R.layout.fragment_day_pic_item, container, false);
mImageView = v.findViewById(R.id.image_view);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mJpg == null)
return;
Intent i = new Intent(getActivity(), TouchImageActivity.class);
i.putExtra("jpgfilename", mItem.get_id() + ".jpg");
startActivity(i);
}
});
// 图片
if (mJpg == null) {
mImageView.setVisibility(View.GONE);
} else {
//Bitmap bm = getBitmapForView(getActivity(), mJpg);
//mImageView.setImageBitmap(bm);
Glide.with(DayPicItemFragment.this)
.load(mJpg)
.dontAnimate()
.into(mImageView);
}
// 文字
mTextView = v.findViewById(R.id.text_view);
mTextView.setMovementMethod(new ScrollingMovementMethod());
mTextView.setText("标题:" + mItem.getTitle() +
"\n介绍:" + mItem.getDescrip() +
"\n日期:" + mItem.getDate());
// 刷新菜单
getActivity().invalidateOptionsMenu();
return v;
}
@Override
public void onDestroyView() {
Glide.clear(mImageView);
super.onDestroyView();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_daypic_fragement, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mTts == null)
return;
MenuItem mi = menu.findItem(R.id.ttsid);
if (mTts.isSpeaking()) {
mi.setTitle("停止");
} else {
mi.setTitle("朗读");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
getActivity().finish();
return true;
case R.id.ttsid:
if (mTts == null)
return true;
if (mTts.isSpeaking()) {
mTts.stop();
} else {
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "UniqueID");
mTts.speak(mItem.getTitle() + ".\n" + mItem.getDescrip(),
QUEUE_FLUSH,
map);
}
getActivity().invalidateOptionsMenu();
return true;
case R.id.copytext:
Context cont = getActivity();
ClipboardManager clipboard = (ClipboardManager) cont.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", mTextView.getText().toString());
clipboard.setPrimaryClip(clip);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// tts引擎初始化之后调用此函数
@Override
public void onInit(int status) {
mTts.setLanguage(Locale.ENGLISH);
mTts.setSpeechRate((float) 0.78);
}
}
| UTF-8 | Java | 7,949 | java | DayPicItemFragment.java | Java | []
| null | []
| package man.animalize.ngdaypic;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import java.util.HashMap;
import java.util.Locale;
import man.animalize.ngdaypic.Base.DayPicItem;
import man.animalize.ngdaypic.Utility.FileReadWrite;
import static android.speech.tts.TextToSpeech.OnInitListener;
import static android.speech.tts.TextToSpeech.QUEUE_FLUSH;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class DayPicItemFragment
extends Fragment
implements OnInitListener {
private static final String TAG = "DayPicItemFragment";
private static final int TTSCHECKSUM = 1234;
private TextView mTextView;
private DayPicItem mItem;
private byte[] mJpg;
private Bitmap mBmp;
private ImageView mImageView;
private TextToSpeech mTts;
// tts的事件处理
private UtteranceProgressListener ttslistener = new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
getActivity().invalidateOptionsMenu();
}
@Override
public void onError(String utteranceId) {
}
};
public DayPicItemFragment() {
// Required empty public constructor
}
// 供DayPicItemActivity调用
public static DayPicItemFragment newInstance(DayPicItem item) {
Bundle arg = new Bundle();
arg.putSerializable("item", item);
DayPicItemFragment f = new DayPicItemFragment();
f.setArguments(arg);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// 得到参数item
Bundle arg = getArguments();
mItem = (DayPicItem) arg.getSerializable("item");
// 图片
if (mItem.getIcon() != null)
mJpg = FileReadWrite.readFile(mItem.get_id() + ".jpg");
// tts
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTSCHECKSUM);
}
// 创建tts实例
protected void instanceTTS() {
mTts = new TextToSpeech(getActivity(), this);
mTts.setOnUtteranceProgressListener(ttslistener);
}
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == TTSCHECKSUM) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
instanceTTS();
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onPause() {
if (mTts != null && mTts.isSpeaking())
mTts.stop();
super.onPause();
}
// TextToSpeech.OnInitListener的接口
@Override
public void onDestroy() {
if (mTts != null)
mTts.shutdown();
super.onDestroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the main_menu for this fragment
View v = inflater.inflate(R.layout.fragment_day_pic_item, container, false);
mImageView = v.findViewById(R.id.image_view);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mJpg == null)
return;
Intent i = new Intent(getActivity(), TouchImageActivity.class);
i.putExtra("jpgfilename", mItem.get_id() + ".jpg");
startActivity(i);
}
});
// 图片
if (mJpg == null) {
mImageView.setVisibility(View.GONE);
} else {
//Bitmap bm = getBitmapForView(getActivity(), mJpg);
//mImageView.setImageBitmap(bm);
Glide.with(DayPicItemFragment.this)
.load(mJpg)
.dontAnimate()
.into(mImageView);
}
// 文字
mTextView = v.findViewById(R.id.text_view);
mTextView.setMovementMethod(new ScrollingMovementMethod());
mTextView.setText("标题:" + mItem.getTitle() +
"\n介绍:" + mItem.getDescrip() +
"\n日期:" + mItem.getDate());
// 刷新菜单
getActivity().invalidateOptionsMenu();
return v;
}
@Override
public void onDestroyView() {
Glide.clear(mImageView);
super.onDestroyView();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_daypic_fragement, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mTts == null)
return;
MenuItem mi = menu.findItem(R.id.ttsid);
if (mTts.isSpeaking()) {
mi.setTitle("停止");
} else {
mi.setTitle("朗读");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
getActivity().finish();
return true;
case R.id.ttsid:
if (mTts == null)
return true;
if (mTts.isSpeaking()) {
mTts.stop();
} else {
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "UniqueID");
mTts.speak(mItem.getTitle() + ".\n" + mItem.getDescrip(),
QUEUE_FLUSH,
map);
}
getActivity().invalidateOptionsMenu();
return true;
case R.id.copytext:
Context cont = getActivity();
ClipboardManager clipboard = (ClipboardManager) cont.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", mTextView.getText().toString());
clipboard.setPrimaryClip(clip);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// tts引擎初始化之后调用此函数
@Override
public void onInit(int status) {
mTts.setLanguage(Locale.ENGLISH);
mTts.setSpeechRate((float) 0.78);
}
}
| 7,949 | 0.577477 | 0.576457 | 260 | 28.157692 | 22.869743 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484615 | false | false | 15 |
a5cfd3b9d61ce30ac49391c2b5b44d29f000e3f3 | 21,938,693,008,469 | 90aacb606c2993887cab1e9bc4800e3410e06f4d | /OneHashBilling/src/com/onehash/view/panel/subscription/SubscriptionPanel.java | 101d5a657d46bb0ef2ccf5f3b5566c8d4d5f95ad | []
| no_license | windieccf/onehashbilling-t4pt | https://github.com/windieccf/onehashbilling-t4pt | e9e8b199c5123d992909aafa5a0899602d911cf7 | 374adee33b6a8cff7f6703e35eba57044525bdc3 | refs/heads/master | 2020-05-17T11:06:05.441000 | 2012-04-07T01:49:05 | 2012-04-07T01:49:05 | 39,320,791 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.onehash.view.panel.subscription;
import java.awt.Dimension;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicComboBoxUI;
import com.onehash.constant.ConstantStatus;
import com.onehash.constant.ConstantSummary;
import com.onehash.controller.OneHashDataCache;
import com.onehash.enumeration.EnumUserAccess;
import com.onehash.exception.BusinessLogicException;
import com.onehash.model.base.BaseEntity;
import com.onehash.model.customer.Customer;
import com.onehash.model.scalar.ButtonAttributeScalar;
import com.onehash.model.scalar.PositionScalar;
import com.onehash.model.service.plan.CableTvPlan;
import com.onehash.model.service.plan.DigitalVoicePlan;
import com.onehash.model.service.plan.MobileVoicePlan;
import com.onehash.model.service.plan.ServicePlan;
import com.onehash.model.service.rate.ServiceRate;
import com.onehash.view.OneHashGui;
import com.onehash.view.component.FactoryComponent;
import com.onehash.view.component.comboboxitem.ComboBoxItem;
import com.onehash.view.component.listener.ButtonActionListener;
import com.onehash.view.component.listener.MouseTableListener;
import com.onehash.view.component.tablemodel.OneHashTableModel;
import com.onehash.view.panel.base.BaseOperationImpl;
import com.onehash.view.panel.base.BasePanel;
import com.onehash.view.panel.customer.CustomerListPanel;
import com.onehash.view.panel.customer.impl.CustomerTabInterface;
@SuppressWarnings("serial")
public class SubscriptionPanel extends BasePanel implements BaseOperationImpl , CustomerTabInterface{
private static final String LBL_SERVICE_PLAN = "LBL_SERVICE_PLAN";
private static final String LBL_SERVICE_RATE = "LBL_SERVICE_RATE";
private static final String SERVICEPLAN_TABLE = "SERVICEPLAN_TABLE";
private static final String SERVICEPLAN_BUTTON_ADD = "SERVICEPLAN_BUTTON_ADD";
private static final String SERVICEPLAN_BUTTON_REM = "SERVICEPLAN_BUTTON_REM";
private static final String SERVICEPLAN_COMBOBOX_SELECTION = "SERVICEPLAN_COMBOBOX_SELECTION";
private static final String SERVICEPLAN_LIST_SELECTED = "SERVICEPLAN_LIST_SELECTED";
private static final String SERVICEPLAN_LIST_AVAILABLE = "SERVICEPLAN_LIST_AVAILABLE";
private static final String SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN = "SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN";
private static final String SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN = "SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN";
private static final String SERVICEPLAN_BUTTON_ADD_OPTIONS = "SERVICEPLAN_BUTTON_ADD_OPTIONS";
private static final String SERVICEPLAN_BUTTON_REMOVE_OPTIONS = "SERVICEPLAN_BUTTON_REMOVE_OPTIONS";
private static final String SERVICEPLAN_LABEL_STARTDATE = "SERVICEPLAN_LABEL_STARTDATE";
private static final String SERVICEPLAN_LABEL_MONTH = "SERVICEPLAN_LABEL_MONTH";
private static final String SERVICEPLAN_COMBOBOX_MONTH = "SERVICEPLAN_COMBOBOX_MONTH";
private static final String SERVICEPLAN_LABEL_YEAR = "SERVICEPLAN_LABEL_YEAR";
private static final String SERVICEPLAN_COMBOBOX_YEAR = "SERVICEPLAN_COMBOBOX_YEAR";
private List<ServicePlan> servicePlans = new ArrayList<ServicePlan>();
private ServicePlan selectedServicePlan;
private String servicePlanMode;
private static final String SERVICEPLAN_EDIT_MODE = "SERVICEPLAN_EDIT_MODE";
private static final String SERVICEPLAN_CREATE_MODE = "SERVICEPLAN_CREATE_MODE";
private List<ServiceRate> selectedServiceRates = new ArrayList<ServiceRate>();
private final static Vector<ComboBoxItem> servicePlanList;
private Customer customer = new Customer(); // for data binding
public SubscriptionPanel(OneHashGui mainFrame) {
super(mainFrame);
}
static{
servicePlanList = new Vector<ComboBoxItem>();
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_DIGITAL_VOICE, ConstantSummary.DigitalVoice));
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_MOBILE_VOICE, ConstantSummary.MobileVoice));
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_CABLE_TV, ConstantSummary.CableTV));
}
@Override
public void draw(){
super.draw();
this.showServicePlanListPage();
}
@Override
protected void init() {
this.customer = new Customer();
this.registerListingComponent();
this.registerMaintenanceComponent();
}
private void registerListingComponent(){
/************************************ Subscription Listing****************************/
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(100, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getTableColumnNames() , this.getData()));
table.addMouseListener(new MouseTableListener(this,"loadServicePlanEditScreen"));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(20,20,400,215);
super.registerComponent(SERVICEPLAN_TABLE, scrollPane);
JButton addButton = FactoryComponent.createButton("Add", new ButtonAttributeScalar(20, 250, 100, 23 , new ButtonActionListener(this,"addServicePlan")));
super.registerComponent(SERVICEPLAN_BUTTON_ADD , addButton);
JButton removeButton = FactoryComponent.createButton("Remove", new ButtonAttributeScalar(150, 250, 100, 23 , new ButtonActionListener(this,"removeServicePlan")));
super.registerComponent(SERVICEPLAN_BUTTON_REM , removeButton);
/************************************ Subscription Listing****************************/
}
private void registerMaintenanceComponent(){
super.registerComponent(LBL_SERVICE_PLAN, FactoryComponent.createLabel("Service Plan", new PositionScalar(20,15,100,10)));
JComboBox servicePlanSelection = FactoryComponent.createComboBox(servicePlanList, new ButtonAttributeScalar(120, 10, 100, 23 , new ButtonActionListener(this,"updateServiceRateBySelectedServicePlan")));
super.registerComponent(SERVICEPLAN_COMBOBOX_SELECTION , servicePlanSelection);
super.registerComponent(SERVICEPLAN_LABEL_STARTDATE , FactoryComponent.createLabel("Start date:", new PositionScalar(20,50,100,10)));
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(false);
super.registerComponent(SERVICEPLAN_LABEL_MONTH , FactoryComponent.createLabel("Month :", new PositionScalar(120,50,100,10)));
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(false);
final Integer[] months = new Integer[12];
for(int i=0;i<months.length;i++){
months[i] = (i+1);
}
JComboBox monthSelector = new JComboBox(months);
monthSelector.setBounds(180, 45, 50, 20);
monthSelector.setUI(new BasicComboBoxUI() {
@Override
protected JButton createArrowButton() {
return new BasicArrowButton(BasicArrowButton.SOUTH);
}
});
super.registerComponent(SERVICEPLAN_COMBOBOX_MONTH , monthSelector);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(false);
super.registerComponent(SERVICEPLAN_LABEL_YEAR , FactoryComponent.createLabel("Year :", new PositionScalar(250, 50, 50, 10)));
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(false);
JComboBox yearSelector = new JComboBox();
Integer[] years = new Integer[100];
for (int i=2000; i<2100; i++)
years[i-2000] = i;
for (int i = 0; i < years.length; i++) {
yearSelector.addItem(years[i]);
}
yearSelector.setBounds(300, 45, 50, 20);
yearSelector.setUI(new BasicComboBoxUI() {
@Override
protected JButton createArrowButton() {
return new BasicArrowButton(BasicArrowButton.SOUTH);
}
});
super.registerComponent(SERVICEPLAN_COMBOBOX_YEAR , yearSelector);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(false);
super.registerComponent(LBL_SERVICE_RATE, FactoryComponent.createLabel("Available Rates", new PositionScalar(20,80,100,10)));
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(20,100, 200,185);
super.registerComponent(SERVICEPLAN_LIST_SELECTED, scrollPane);
super.registerComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS , FactoryComponent.createButton("<<", new ButtonAttributeScalar(235, 130, 50, 23 , new ButtonActionListener(this,"addOptions"))));
super.registerComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS , FactoryComponent.createButton(">>", new ButtonAttributeScalar(235, 160, 50, 23 , new ButtonActionListener(this,"removeOptions"))));
table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setModel(new OneHashTableModel(this.getAvailableServiceRateColumnNames() , this.getAvailableServiceRate()));
scrollPane = new JScrollPane(table);
scrollPane.setBounds(300,100,200,185);
super.registerComponent(SERVICEPLAN_LIST_AVAILABLE, scrollPane);
super.registerComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN , FactoryComponent.createButton("Save Subscription", new ButtonAttributeScalar(20, 300, 150, 23 , new ButtonActionListener(this,"saveServicePlan"))));
super.registerComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN , FactoryComponent.createButton("Cancel", new ButtonAttributeScalar(180, 300, 100, 23 , new ButtonActionListener(this,"showServicePlanListPage"))));
}
@Override
protected String getScreenTitle() {return "Subscription Panel";}
@Override
protected boolean isEnableHeader(){return false;}
@Override
public BaseEntity getSelectedEntity() {return this.customer;}
@Override
public void initializeCustomer(Customer customer){
this.customer = customer;
this.servicePlans = customer.getServicePlans();
this.refreshServicePlansJTable();
}
/***************************************** BUTTON LISTENER *****************************************************/
public void cancel(){
this.getMainFrame().doLoadScreen(CustomerListPanel.class);
}
public void refreshServicePlansJTable() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(100, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getTableColumnNames() , this.getData()));
table.addMouseListener(new MouseTableListener(this,"loadServicePlanEditScreen"));
JScrollPane servicePlansScrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_TABLE);
servicePlansScrollPane.setViewportView(table);
}
public void addServicePlan() {
servicePlanMode = SERVICEPLAN_CREATE_MODE;
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
component.setEnabled(true);
showServicePlanMaintenancePage();
}
public void removeServicePlan() {
JScrollPane selectedServicePlanScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_TABLE);
JTable ServicePlanJTable = (JTable)selectedServicePlanScrollPane.getViewport().getView();
/**
* Disable removing permanent ServicePlan, flag to deleted
*/
//servicePlans.remove(ServicePlanJTable.getSelectedRow());
servicePlans.get(ServicePlanJTable.getSelectedRow()).setStatus(ConstantStatus.SERVICEPLAN_DELETED);
refreshServicePlansJTable();
}
public void showServicePlanListPage(){
this.selectedServiceRates = null;
super.getComponent(SERVICEPLAN_TABLE).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_REM).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION).setVisible(false);
super.getComponent(SERVICEPLAN_LIST_SELECTED).setVisible(false);
super.getComponent(SERVICEPLAN_LIST_AVAILABLE).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setVisible(false);
super.getComponent(LBL_SERVICE_PLAN).setVisible(false);
super.getComponent(LBL_SERVICE_RATE).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(false);
}
public void showServicePlanMaintenancePage(){
this.updateSelectedServiceRate();
this.updateAvailableServiceRate();
this.updateSubscriptionField();
super.getComponent(SERVICEPLAN_TABLE).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_REM).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION).setVisible(true);
super.getComponent(SERVICEPLAN_LIST_SELECTED).setVisible(true);
super.getComponent(SERVICEPLAN_LIST_AVAILABLE).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setVisible(true);
super.getComponent(LBL_SERVICE_PLAN).setVisible(true);
super.getComponent(LBL_SERVICE_RATE).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(true);
if (selectedServicePlan != null && selectedServicePlan.getStatus().equals(ConstantStatus.SERVICEPLAN_DELETED)) {
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setEnabled(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setEnabled(false);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setEnabled(false);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setEnabled(false);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setEnabled(false);
}
else {
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setEnabled(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setEnabled(true);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setEnabled(true);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setEnabled(true);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setEnabled(true);
}
this.initiateAccessRights();
}
public void saveServicePlan() throws Exception {
try {
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
/**
* Determine New or Edit ServicePlan
*/
if (servicePlanMode.equals(SERVICEPLAN_CREATE_MODE)) {
if (prefix.getKey().equals(ServiceRate.PREFIX_MOBILE_VOICE)) {
selectedServicePlan = new MobileVoicePlan();
}
else if (prefix.getKey().equals(ServiceRate.PREFIX_DIGITAL_VOICE)) {
selectedServicePlan = new DigitalVoicePlan();
}
else {
selectedServicePlan = new CableTvPlan();
}
selectedServicePlan.setPlanId(prefix.getKey() + (this.customer.getServicePlans().size()+1));
selectedServicePlan.setPlanName(prefix.getValue());
servicePlans.add(selectedServicePlan);
}
else {
for(ServicePlan servicePlan:servicePlans) {
if (servicePlan.getPlanId().equals(selectedServicePlan.getPlanId())) {
servicePlan = selectedServicePlan;
break;
}
}
}
Calendar calendar = Calendar.getInstance();
Integer selectedYear = (Integer) super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_YEAR).getSelectedItem();//(Integer) yearComboBox.getSelectedItem();
Integer selectedMonth = (Integer) super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_MONTH).getSelectedItem(); //(Integer) monthComboBox.getSelectedItem();
Integer selectedDayOfMonth = 1;
// fix on the selected month, by default java recognise JAN as 0.
calendar.set(selectedYear , selectedMonth - 1 , selectedDayOfMonth);
selectedServicePlan.setStartDate(calendar.getTime());
selectedServicePlan.setServiceRates(selectedServiceRates);
//use the Save Customer button
//OneHashDataCache.getInstance().saveCustomer(this.customer);
//JOptionPane.showMessageDialog(this, "Subscriptions Successfully Saved");
this.refreshServicePlansJTable();
this.showServicePlanListPage();
// added by robin for dynamic object binding
this.customer.setServicePlans(servicePlans);
}catch(Exception e){
if(e instanceof BusinessLogicException)
JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
throw e;
}
}
public void updateServiceRateBySelectedServicePlan() {
this.selectedServiceRates = new ArrayList<ServiceRate>();
this.updateSelectedServiceRate();
this.updateAvailableServiceRate();
}
private void updateSubscriptionField(){
if(selectedServicePlan!=null && selectedServicePlan.getStartDate() != null){
Calendar cal = Calendar.getInstance();
cal.setTime(selectedServicePlan.getStartDate());
super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_YEAR).setSelectedItem(cal.get(Calendar.YEAR));
super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_MONTH).setSelectedItem(cal.get(Calendar.MONTH) + 1);
}
}
public void updateAvailableServiceRate() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getAvailableServiceRateColumnNames() , this.getAvailableServiceRate()));
JScrollPane scrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_LIST_AVAILABLE);
scrollPane.setViewportView(table);
}
public void updateSelectedServiceRate() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
JScrollPane scrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_LIST_SELECTED);
scrollPane.setViewportView(table);
}
public void addOptions() {
JScrollPane availableOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_AVAILABLE);
JTable availableOptionsJTable = (JTable)availableOptionsScrollPane.getViewport().getView();
HashSet<ServiceRate> selectedServiceRatesHashMap = new HashSet<ServiceRate>(selectedServiceRates);
JScrollPane selectedOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_SELECTED);
if (availableOptionsJTable.getSelectedRow() >= 0 && availableOptionsJTable.getSelectedColumn() >= 0) {
String selectedValue = (String) availableOptionsJTable.getValueAt(availableOptionsJTable.getSelectedRow(), availableOptionsJTable.getSelectedColumn());
for (ServiceRate serviceRate:OneHashDataCache.getInstance().getAvailableServiceRate()) {
if (selectedValue.equals(serviceRate.getRateCode()+": "+serviceRate.getRateDescription()) && !selectedServiceRatesHashMap.contains(serviceRate)) {
selectedServiceRates.add(serviceRate);
break;
}
}
}
JTable newTable = new JTable();
newTable.setPreferredScrollableViewportSize(new Dimension(200, 70));
newTable.setFillsViewportHeight(true);
newTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
newTable.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
selectedOptionsScrollPane.setViewportView(newTable);
updateAvailableServiceRate();
}
public void removeOptions() {
JScrollPane selectedOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_SELECTED);
JTable selectedOptionsJTable = (JTable)selectedOptionsScrollPane.getViewport().getView();
if (selectedOptionsJTable.getSelectedRow() >= 0 && selectedOptionsJTable.getSelectedColumn() >= 0) {
String selectedValue = (String) selectedOptionsJTable.getValueAt(selectedOptionsJTable.getSelectedRow(), selectedOptionsJTable.getSelectedColumn());
int selectedServiceRateSize = selectedServiceRates.size();
for (int i=0; i<selectedServiceRateSize; i++) {
ServiceRate sr = selectedServiceRates.get(i);
if (selectedValue.equals(sr.getRateCode()+": "+sr.getRateDescription())) {
selectedServiceRates.remove(i);
break;
}
}
}
JTable newTable = new JTable();
newTable.setPreferredScrollableViewportSize(new Dimension(200, 70));
newTable.setFillsViewportHeight(true);
newTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
newTable.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
selectedOptionsScrollPane.setViewportView(newTable);
updateAvailableServiceRate();
}
/**************************** REFLECTION UTILITY **********************************/
public void loadServicePlanEditScreen(String parameter){
servicePlanMode = SERVICEPLAN_EDIT_MODE;
selectedServicePlan = null;
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
int componentCount = component.getItemCount();
for(int i=0; i<componentCount; i++) {
ComboBoxItem comboBoxItem = (ComboBoxItem) component.getItemAt(i);
if (comboBoxItem.getKey().equals(parameter.substring(0, comboBoxItem.getKey().length()))) {
component.setSelectedIndex(i);
break;
}
}
component.setEnabled(false);
for(ServicePlan servicePlan:servicePlans) {
if (servicePlan.getPlanId().equals(parameter)) {
selectedServicePlan = servicePlan;
break;
}
}
if (selectedServicePlan == null)
throw new IllegalArgumentException("Could not find the selected ServicePlan : " + parameter);
selectedServiceRates = selectedServicePlan.getServiceRates();
this.showServicePlanMaintenancePage();
}
/******************************** TABLE UTILITY******************************************/
public Object[][] getData(){
Object[][] rowData = new String[1][4];
if (servicePlans == null)
servicePlans = new ArrayList<ServicePlan>();
if(servicePlans.isEmpty()){
rowData = new Object[0][4];
}else{
rowData = new Object[servicePlans.size()][4];
for(int i = 0 ; i < servicePlans.size(); i++){
ServicePlan servicePlan = servicePlans.get(i);
rowData[i][0] = servicePlan.getPlanId();
rowData[i][1] = servicePlan.getPlanName();
rowData[i][2] = DateFormat.getDateInstance(DateFormat.MEDIUM).format(servicePlan.getStartDate());
if (servicePlan.getStatus().equals(ConstantStatus.SERVICEPLAN_DELETED)) {
rowData[i][3] = DateFormat.getDateInstance(DateFormat.MEDIUM).format(servicePlan.getEndDate());
}
else {
rowData[i][3] = "";
}
}
}
return rowData;
}
public String[] getSelectedServiceRateColumnNames(){
return new String[]{"Selected Options"};
}
public Object[][] getSelectedServiceRate() {
Object[][] rowData = new String[1][1];
if (selectedServiceRates == null) {
selectedServiceRates = new ArrayList<ServiceRate>();
}
if (selectedServiceRates.size() == 0) {
ArrayList<ServiceRate> serviceRates2 = new ArrayList<ServiceRate>(OneHashDataCache.getInstance().getAvailableServiceRate());
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
for(ServiceRate serviceRate:serviceRates2) {
if (!serviceRate.getRateCode().startsWith(prefix.getKey()))
continue;
if (serviceRate.getRateDescription().indexOf("Local")>-1 || serviceRate.getRateCode().startsWith(prefix.getKey()+"S"))
selectedServiceRates.add(serviceRate);
}
}
rowData = new String[selectedServiceRates.size()][1];
int idx = 0;
for(ServiceRate serviceRate:selectedServiceRates) {
rowData[idx][0] = serviceRate.getRateCode()+": "+serviceRate.getRateDescription();
idx++;
}
return rowData;
}
public Object[][] getAvailableServiceRate() {
Object[][] rowData = new String[1][1];
List<ServiceRate> serviceRates = OneHashDataCache.getInstance().getAvailableServiceRate();
rowData = new String[serviceRates.toArray().length][1];
ArrayList<String> _availableServiceRate = new ArrayList<String>();
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
HashSet<ServiceRate> selectedServiceRatesHashMap = new HashSet<ServiceRate>(selectedServiceRates);
int maxIdx = 0, idx = 0;
for(ServiceRate serviceRate:serviceRates) {
if (!serviceRate.getRateCode().startsWith(prefix.getKey()) || selectedServiceRatesHashMap.contains(serviceRate))
continue;
_availableServiceRate.add(serviceRate.getRateCode()+": "+serviceRate.getRateDescription());
maxIdx++;
}
rowData = new String[maxIdx][1];
idx = 0;
for (String s:_availableServiceRate) {
rowData[idx][0] = s;
idx++;
}
return rowData;
}
public String[] getAvailableServiceRateColumnNames(){
return new String[]{"Available Options"};
}
public String[] getTableColumnNames(){
return new String[]{"Subs. Num.", "Name", "Start" , "End"};
}
@Override
public void setSelectedEntity(BaseEntity baseEntity) {
this.customer = (Customer) baseEntity;
}
@Override
protected void initiateAccessRights() {
if(!OneHashDataCache.getInstance().getCurrentUser().hasRights(EnumUserAccess.SERVICE_PLAN_UPDATE)){
super.disableComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN);
}
}
}
| UTF-8 | Java | 27,515 | java | SubscriptionPanel.java | Java | []
| null | []
| package com.onehash.view.panel.subscription;
import java.awt.Dimension;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicComboBoxUI;
import com.onehash.constant.ConstantStatus;
import com.onehash.constant.ConstantSummary;
import com.onehash.controller.OneHashDataCache;
import com.onehash.enumeration.EnumUserAccess;
import com.onehash.exception.BusinessLogicException;
import com.onehash.model.base.BaseEntity;
import com.onehash.model.customer.Customer;
import com.onehash.model.scalar.ButtonAttributeScalar;
import com.onehash.model.scalar.PositionScalar;
import com.onehash.model.service.plan.CableTvPlan;
import com.onehash.model.service.plan.DigitalVoicePlan;
import com.onehash.model.service.plan.MobileVoicePlan;
import com.onehash.model.service.plan.ServicePlan;
import com.onehash.model.service.rate.ServiceRate;
import com.onehash.view.OneHashGui;
import com.onehash.view.component.FactoryComponent;
import com.onehash.view.component.comboboxitem.ComboBoxItem;
import com.onehash.view.component.listener.ButtonActionListener;
import com.onehash.view.component.listener.MouseTableListener;
import com.onehash.view.component.tablemodel.OneHashTableModel;
import com.onehash.view.panel.base.BaseOperationImpl;
import com.onehash.view.panel.base.BasePanel;
import com.onehash.view.panel.customer.CustomerListPanel;
import com.onehash.view.panel.customer.impl.CustomerTabInterface;
@SuppressWarnings("serial")
public class SubscriptionPanel extends BasePanel implements BaseOperationImpl , CustomerTabInterface{
private static final String LBL_SERVICE_PLAN = "LBL_SERVICE_PLAN";
private static final String LBL_SERVICE_RATE = "LBL_SERVICE_RATE";
private static final String SERVICEPLAN_TABLE = "SERVICEPLAN_TABLE";
private static final String SERVICEPLAN_BUTTON_ADD = "SERVICEPLAN_BUTTON_ADD";
private static final String SERVICEPLAN_BUTTON_REM = "SERVICEPLAN_BUTTON_REM";
private static final String SERVICEPLAN_COMBOBOX_SELECTION = "SERVICEPLAN_COMBOBOX_SELECTION";
private static final String SERVICEPLAN_LIST_SELECTED = "SERVICEPLAN_LIST_SELECTED";
private static final String SERVICEPLAN_LIST_AVAILABLE = "SERVICEPLAN_LIST_AVAILABLE";
private static final String SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN = "SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN";
private static final String SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN = "SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN";
private static final String SERVICEPLAN_BUTTON_ADD_OPTIONS = "SERVICEPLAN_BUTTON_ADD_OPTIONS";
private static final String SERVICEPLAN_BUTTON_REMOVE_OPTIONS = "SERVICEPLAN_BUTTON_REMOVE_OPTIONS";
private static final String SERVICEPLAN_LABEL_STARTDATE = "SERVICEPLAN_LABEL_STARTDATE";
private static final String SERVICEPLAN_LABEL_MONTH = "SERVICEPLAN_LABEL_MONTH";
private static final String SERVICEPLAN_COMBOBOX_MONTH = "SERVICEPLAN_COMBOBOX_MONTH";
private static final String SERVICEPLAN_LABEL_YEAR = "SERVICEPLAN_LABEL_YEAR";
private static final String SERVICEPLAN_COMBOBOX_YEAR = "SERVICEPLAN_COMBOBOX_YEAR";
private List<ServicePlan> servicePlans = new ArrayList<ServicePlan>();
private ServicePlan selectedServicePlan;
private String servicePlanMode;
private static final String SERVICEPLAN_EDIT_MODE = "SERVICEPLAN_EDIT_MODE";
private static final String SERVICEPLAN_CREATE_MODE = "SERVICEPLAN_CREATE_MODE";
private List<ServiceRate> selectedServiceRates = new ArrayList<ServiceRate>();
private final static Vector<ComboBoxItem> servicePlanList;
private Customer customer = new Customer(); // for data binding
public SubscriptionPanel(OneHashGui mainFrame) {
super(mainFrame);
}
static{
servicePlanList = new Vector<ComboBoxItem>();
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_DIGITAL_VOICE, ConstantSummary.DigitalVoice));
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_MOBILE_VOICE, ConstantSummary.MobileVoice));
servicePlanList.add(new ComboBoxItem(ServiceRate.PREFIX_CABLE_TV, ConstantSummary.CableTV));
}
@Override
public void draw(){
super.draw();
this.showServicePlanListPage();
}
@Override
protected void init() {
this.customer = new Customer();
this.registerListingComponent();
this.registerMaintenanceComponent();
}
private void registerListingComponent(){
/************************************ Subscription Listing****************************/
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(100, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getTableColumnNames() , this.getData()));
table.addMouseListener(new MouseTableListener(this,"loadServicePlanEditScreen"));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(20,20,400,215);
super.registerComponent(SERVICEPLAN_TABLE, scrollPane);
JButton addButton = FactoryComponent.createButton("Add", new ButtonAttributeScalar(20, 250, 100, 23 , new ButtonActionListener(this,"addServicePlan")));
super.registerComponent(SERVICEPLAN_BUTTON_ADD , addButton);
JButton removeButton = FactoryComponent.createButton("Remove", new ButtonAttributeScalar(150, 250, 100, 23 , new ButtonActionListener(this,"removeServicePlan")));
super.registerComponent(SERVICEPLAN_BUTTON_REM , removeButton);
/************************************ Subscription Listing****************************/
}
private void registerMaintenanceComponent(){
super.registerComponent(LBL_SERVICE_PLAN, FactoryComponent.createLabel("Service Plan", new PositionScalar(20,15,100,10)));
JComboBox servicePlanSelection = FactoryComponent.createComboBox(servicePlanList, new ButtonAttributeScalar(120, 10, 100, 23 , new ButtonActionListener(this,"updateServiceRateBySelectedServicePlan")));
super.registerComponent(SERVICEPLAN_COMBOBOX_SELECTION , servicePlanSelection);
super.registerComponent(SERVICEPLAN_LABEL_STARTDATE , FactoryComponent.createLabel("Start date:", new PositionScalar(20,50,100,10)));
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(false);
super.registerComponent(SERVICEPLAN_LABEL_MONTH , FactoryComponent.createLabel("Month :", new PositionScalar(120,50,100,10)));
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(false);
final Integer[] months = new Integer[12];
for(int i=0;i<months.length;i++){
months[i] = (i+1);
}
JComboBox monthSelector = new JComboBox(months);
monthSelector.setBounds(180, 45, 50, 20);
monthSelector.setUI(new BasicComboBoxUI() {
@Override
protected JButton createArrowButton() {
return new BasicArrowButton(BasicArrowButton.SOUTH);
}
});
super.registerComponent(SERVICEPLAN_COMBOBOX_MONTH , monthSelector);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(false);
super.registerComponent(SERVICEPLAN_LABEL_YEAR , FactoryComponent.createLabel("Year :", new PositionScalar(250, 50, 50, 10)));
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(false);
JComboBox yearSelector = new JComboBox();
Integer[] years = new Integer[100];
for (int i=2000; i<2100; i++)
years[i-2000] = i;
for (int i = 0; i < years.length; i++) {
yearSelector.addItem(years[i]);
}
yearSelector.setBounds(300, 45, 50, 20);
yearSelector.setUI(new BasicComboBoxUI() {
@Override
protected JButton createArrowButton() {
return new BasicArrowButton(BasicArrowButton.SOUTH);
}
});
super.registerComponent(SERVICEPLAN_COMBOBOX_YEAR , yearSelector);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(false);
super.registerComponent(LBL_SERVICE_RATE, FactoryComponent.createLabel("Available Rates", new PositionScalar(20,80,100,10)));
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(20,100, 200,185);
super.registerComponent(SERVICEPLAN_LIST_SELECTED, scrollPane);
super.registerComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS , FactoryComponent.createButton("<<", new ButtonAttributeScalar(235, 130, 50, 23 , new ButtonActionListener(this,"addOptions"))));
super.registerComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS , FactoryComponent.createButton(">>", new ButtonAttributeScalar(235, 160, 50, 23 , new ButtonActionListener(this,"removeOptions"))));
table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setModel(new OneHashTableModel(this.getAvailableServiceRateColumnNames() , this.getAvailableServiceRate()));
scrollPane = new JScrollPane(table);
scrollPane.setBounds(300,100,200,185);
super.registerComponent(SERVICEPLAN_LIST_AVAILABLE, scrollPane);
super.registerComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN , FactoryComponent.createButton("Save Subscription", new ButtonAttributeScalar(20, 300, 150, 23 , new ButtonActionListener(this,"saveServicePlan"))));
super.registerComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN , FactoryComponent.createButton("Cancel", new ButtonAttributeScalar(180, 300, 100, 23 , new ButtonActionListener(this,"showServicePlanListPage"))));
}
@Override
protected String getScreenTitle() {return "Subscription Panel";}
@Override
protected boolean isEnableHeader(){return false;}
@Override
public BaseEntity getSelectedEntity() {return this.customer;}
@Override
public void initializeCustomer(Customer customer){
this.customer = customer;
this.servicePlans = customer.getServicePlans();
this.refreshServicePlansJTable();
}
/***************************************** BUTTON LISTENER *****************************************************/
public void cancel(){
this.getMainFrame().doLoadScreen(CustomerListPanel.class);
}
public void refreshServicePlansJTable() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(100, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getTableColumnNames() , this.getData()));
table.addMouseListener(new MouseTableListener(this,"loadServicePlanEditScreen"));
JScrollPane servicePlansScrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_TABLE);
servicePlansScrollPane.setViewportView(table);
}
public void addServicePlan() {
servicePlanMode = SERVICEPLAN_CREATE_MODE;
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
component.setEnabled(true);
showServicePlanMaintenancePage();
}
public void removeServicePlan() {
JScrollPane selectedServicePlanScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_TABLE);
JTable ServicePlanJTable = (JTable)selectedServicePlanScrollPane.getViewport().getView();
/**
* Disable removing permanent ServicePlan, flag to deleted
*/
//servicePlans.remove(ServicePlanJTable.getSelectedRow());
servicePlans.get(ServicePlanJTable.getSelectedRow()).setStatus(ConstantStatus.SERVICEPLAN_DELETED);
refreshServicePlansJTable();
}
public void showServicePlanListPage(){
this.selectedServiceRates = null;
super.getComponent(SERVICEPLAN_TABLE).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_REM).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION).setVisible(false);
super.getComponent(SERVICEPLAN_LIST_SELECTED).setVisible(false);
super.getComponent(SERVICEPLAN_LIST_AVAILABLE).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setVisible(false);
super.getComponent(LBL_SERVICE_PLAN).setVisible(false);
super.getComponent(LBL_SERVICE_RATE).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(false);
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(false);
}
public void showServicePlanMaintenancePage(){
this.updateSelectedServiceRate();
this.updateAvailableServiceRate();
this.updateSubscriptionField();
super.getComponent(SERVICEPLAN_TABLE).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD).setVisible(false);
super.getComponent(SERVICEPLAN_BUTTON_REM).setVisible(false);
super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION).setVisible(true);
super.getComponent(SERVICEPLAN_LIST_SELECTED).setVisible(true);
super.getComponent(SERVICEPLAN_LIST_AVAILABLE).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setVisible(true);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setVisible(true);
super.getComponent(LBL_SERVICE_PLAN).setVisible(true);
super.getComponent(LBL_SERVICE_RATE).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_STARTDATE).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_MONTH).setVisible(true);
super.getComponent(SERVICEPLAN_LABEL_YEAR).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setVisible(true);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setVisible(true);
if (selectedServicePlan != null && selectedServicePlan.getStatus().equals(ConstantStatus.SERVICEPLAN_DELETED)) {
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setEnabled(false);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setEnabled(false);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setEnabled(false);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setEnabled(false);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setEnabled(false);
}
else {
super.getComponent(SERVICEPLAN_BUTTON_SAVE_SERVICE_PLAN).setEnabled(true);
super.getComponent(SERVICEPLAN_BUTTON_ADD_OPTIONS).setEnabled(true);
super.getComponent(SERVICEPLAN_BUTTON_REMOVE_OPTIONS).setEnabled(true);
super.getComponent(SERVICEPLAN_COMBOBOX_MONTH).setEnabled(true);
super.getComponent(SERVICEPLAN_COMBOBOX_YEAR).setEnabled(true);
}
this.initiateAccessRights();
}
public void saveServicePlan() throws Exception {
try {
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
/**
* Determine New or Edit ServicePlan
*/
if (servicePlanMode.equals(SERVICEPLAN_CREATE_MODE)) {
if (prefix.getKey().equals(ServiceRate.PREFIX_MOBILE_VOICE)) {
selectedServicePlan = new MobileVoicePlan();
}
else if (prefix.getKey().equals(ServiceRate.PREFIX_DIGITAL_VOICE)) {
selectedServicePlan = new DigitalVoicePlan();
}
else {
selectedServicePlan = new CableTvPlan();
}
selectedServicePlan.setPlanId(prefix.getKey() + (this.customer.getServicePlans().size()+1));
selectedServicePlan.setPlanName(prefix.getValue());
servicePlans.add(selectedServicePlan);
}
else {
for(ServicePlan servicePlan:servicePlans) {
if (servicePlan.getPlanId().equals(selectedServicePlan.getPlanId())) {
servicePlan = selectedServicePlan;
break;
}
}
}
Calendar calendar = Calendar.getInstance();
Integer selectedYear = (Integer) super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_YEAR).getSelectedItem();//(Integer) yearComboBox.getSelectedItem();
Integer selectedMonth = (Integer) super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_MONTH).getSelectedItem(); //(Integer) monthComboBox.getSelectedItem();
Integer selectedDayOfMonth = 1;
// fix on the selected month, by default java recognise JAN as 0.
calendar.set(selectedYear , selectedMonth - 1 , selectedDayOfMonth);
selectedServicePlan.setStartDate(calendar.getTime());
selectedServicePlan.setServiceRates(selectedServiceRates);
//use the Save Customer button
//OneHashDataCache.getInstance().saveCustomer(this.customer);
//JOptionPane.showMessageDialog(this, "Subscriptions Successfully Saved");
this.refreshServicePlansJTable();
this.showServicePlanListPage();
// added by robin for dynamic object binding
this.customer.setServicePlans(servicePlans);
}catch(Exception e){
if(e instanceof BusinessLogicException)
JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
throw e;
}
}
public void updateServiceRateBySelectedServicePlan() {
this.selectedServiceRates = new ArrayList<ServiceRate>();
this.updateSelectedServiceRate();
this.updateAvailableServiceRate();
}
private void updateSubscriptionField(){
if(selectedServicePlan!=null && selectedServicePlan.getStartDate() != null){
Calendar cal = Calendar.getInstance();
cal.setTime(selectedServicePlan.getStartDate());
super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_YEAR).setSelectedItem(cal.get(Calendar.YEAR));
super.getComboBoxComponent(SERVICEPLAN_COMBOBOX_MONTH).setSelectedItem(cal.get(Calendar.MONTH) + 1);
}
}
public void updateAvailableServiceRate() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getAvailableServiceRateColumnNames() , this.getAvailableServiceRate()));
JScrollPane scrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_LIST_AVAILABLE);
scrollPane.setViewportView(table);
}
public void updateSelectedServiceRate() {
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(200, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
JScrollPane scrollPane = (JScrollPane) super.getComponent(SERVICEPLAN_LIST_SELECTED);
scrollPane.setViewportView(table);
}
public void addOptions() {
JScrollPane availableOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_AVAILABLE);
JTable availableOptionsJTable = (JTable)availableOptionsScrollPane.getViewport().getView();
HashSet<ServiceRate> selectedServiceRatesHashMap = new HashSet<ServiceRate>(selectedServiceRates);
JScrollPane selectedOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_SELECTED);
if (availableOptionsJTable.getSelectedRow() >= 0 && availableOptionsJTable.getSelectedColumn() >= 0) {
String selectedValue = (String) availableOptionsJTable.getValueAt(availableOptionsJTable.getSelectedRow(), availableOptionsJTable.getSelectedColumn());
for (ServiceRate serviceRate:OneHashDataCache.getInstance().getAvailableServiceRate()) {
if (selectedValue.equals(serviceRate.getRateCode()+": "+serviceRate.getRateDescription()) && !selectedServiceRatesHashMap.contains(serviceRate)) {
selectedServiceRates.add(serviceRate);
break;
}
}
}
JTable newTable = new JTable();
newTable.setPreferredScrollableViewportSize(new Dimension(200, 70));
newTable.setFillsViewportHeight(true);
newTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
newTable.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
selectedOptionsScrollPane.setViewportView(newTable);
updateAvailableServiceRate();
}
public void removeOptions() {
JScrollPane selectedOptionsScrollPane = (JScrollPane)super.getComponent(SERVICEPLAN_LIST_SELECTED);
JTable selectedOptionsJTable = (JTable)selectedOptionsScrollPane.getViewport().getView();
if (selectedOptionsJTable.getSelectedRow() >= 0 && selectedOptionsJTable.getSelectedColumn() >= 0) {
String selectedValue = (String) selectedOptionsJTable.getValueAt(selectedOptionsJTable.getSelectedRow(), selectedOptionsJTable.getSelectedColumn());
int selectedServiceRateSize = selectedServiceRates.size();
for (int i=0; i<selectedServiceRateSize; i++) {
ServiceRate sr = selectedServiceRates.get(i);
if (selectedValue.equals(sr.getRateCode()+": "+sr.getRateDescription())) {
selectedServiceRates.remove(i);
break;
}
}
}
JTable newTable = new JTable();
newTable.setPreferredScrollableViewportSize(new Dimension(200, 70));
newTable.setFillsViewportHeight(true);
newTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
newTable.setModel(new OneHashTableModel(this.getSelectedServiceRateColumnNames() , this.getSelectedServiceRate()));
selectedOptionsScrollPane.setViewportView(newTable);
updateAvailableServiceRate();
}
/**************************** REFLECTION UTILITY **********************************/
public void loadServicePlanEditScreen(String parameter){
servicePlanMode = SERVICEPLAN_EDIT_MODE;
selectedServicePlan = null;
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
int componentCount = component.getItemCount();
for(int i=0; i<componentCount; i++) {
ComboBoxItem comboBoxItem = (ComboBoxItem) component.getItemAt(i);
if (comboBoxItem.getKey().equals(parameter.substring(0, comboBoxItem.getKey().length()))) {
component.setSelectedIndex(i);
break;
}
}
component.setEnabled(false);
for(ServicePlan servicePlan:servicePlans) {
if (servicePlan.getPlanId().equals(parameter)) {
selectedServicePlan = servicePlan;
break;
}
}
if (selectedServicePlan == null)
throw new IllegalArgumentException("Could not find the selected ServicePlan : " + parameter);
selectedServiceRates = selectedServicePlan.getServiceRates();
this.showServicePlanMaintenancePage();
}
/******************************** TABLE UTILITY******************************************/
public Object[][] getData(){
Object[][] rowData = new String[1][4];
if (servicePlans == null)
servicePlans = new ArrayList<ServicePlan>();
if(servicePlans.isEmpty()){
rowData = new Object[0][4];
}else{
rowData = new Object[servicePlans.size()][4];
for(int i = 0 ; i < servicePlans.size(); i++){
ServicePlan servicePlan = servicePlans.get(i);
rowData[i][0] = servicePlan.getPlanId();
rowData[i][1] = servicePlan.getPlanName();
rowData[i][2] = DateFormat.getDateInstance(DateFormat.MEDIUM).format(servicePlan.getStartDate());
if (servicePlan.getStatus().equals(ConstantStatus.SERVICEPLAN_DELETED)) {
rowData[i][3] = DateFormat.getDateInstance(DateFormat.MEDIUM).format(servicePlan.getEndDate());
}
else {
rowData[i][3] = "";
}
}
}
return rowData;
}
public String[] getSelectedServiceRateColumnNames(){
return new String[]{"Selected Options"};
}
public Object[][] getSelectedServiceRate() {
Object[][] rowData = new String[1][1];
if (selectedServiceRates == null) {
selectedServiceRates = new ArrayList<ServiceRate>();
}
if (selectedServiceRates.size() == 0) {
ArrayList<ServiceRate> serviceRates2 = new ArrayList<ServiceRate>(OneHashDataCache.getInstance().getAvailableServiceRate());
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
for(ServiceRate serviceRate:serviceRates2) {
if (!serviceRate.getRateCode().startsWith(prefix.getKey()))
continue;
if (serviceRate.getRateDescription().indexOf("Local")>-1 || serviceRate.getRateCode().startsWith(prefix.getKey()+"S"))
selectedServiceRates.add(serviceRate);
}
}
rowData = new String[selectedServiceRates.size()][1];
int idx = 0;
for(ServiceRate serviceRate:selectedServiceRates) {
rowData[idx][0] = serviceRate.getRateCode()+": "+serviceRate.getRateDescription();
idx++;
}
return rowData;
}
public Object[][] getAvailableServiceRate() {
Object[][] rowData = new String[1][1];
List<ServiceRate> serviceRates = OneHashDataCache.getInstance().getAvailableServiceRate();
rowData = new String[serviceRates.toArray().length][1];
ArrayList<String> _availableServiceRate = new ArrayList<String>();
JComboBox component = (JComboBox)super.getComponent(SERVICEPLAN_COMBOBOX_SELECTION);
ComboBoxItem prefix = (ComboBoxItem)component.getSelectedItem();
HashSet<ServiceRate> selectedServiceRatesHashMap = new HashSet<ServiceRate>(selectedServiceRates);
int maxIdx = 0, idx = 0;
for(ServiceRate serviceRate:serviceRates) {
if (!serviceRate.getRateCode().startsWith(prefix.getKey()) || selectedServiceRatesHashMap.contains(serviceRate))
continue;
_availableServiceRate.add(serviceRate.getRateCode()+": "+serviceRate.getRateDescription());
maxIdx++;
}
rowData = new String[maxIdx][1];
idx = 0;
for (String s:_availableServiceRate) {
rowData[idx][0] = s;
idx++;
}
return rowData;
}
public String[] getAvailableServiceRateColumnNames(){
return new String[]{"Available Options"};
}
public String[] getTableColumnNames(){
return new String[]{"Subs. Num.", "Name", "Start" , "End"};
}
@Override
public void setSelectedEntity(BaseEntity baseEntity) {
this.customer = (Customer) baseEntity;
}
@Override
protected void initiateAccessRights() {
if(!OneHashDataCache.getInstance().getCurrentUser().hasRights(EnumUserAccess.SERVICE_PLAN_UPDATE)){
super.disableComponent(SERVICEPLAN_BUTTON_CANCEL_SERVICE_PLAN);
}
}
}
| 27,515 | 0.737452 | 0.727676 | 604 | 43.554634 | 38.095455 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.445364 | false | false | 15 |
c28c68a451d5c44902ae8e51f4a04067a10bbfe3 | 24,455,543,787,599 | eac1db2d78eed70d0e7af95d4358caf9c8d65c1f | /src/study/polymorphizm/Person.java | 25cf1bdf5a267718646480c5c739974cdca3a978 | []
| no_license | AtlanticP/javaAll | https://github.com/AtlanticP/javaAll | 8b8e260c53d4c632a0f3dd4684c6224e1450f9f4 | b3e5ff948152e1c77bf92e1587169287048598b2 | refs/heads/master | 2020-12-01T17:58:52.525000 | 2019-12-29T07:35:07 | 2019-12-29T07:35:07 | 230,719,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package study.polymorphizm;
public class Person {
public int height = 180;
public String name = "Default";
public static void say(String name) {
System.out.println ("Hello, " + name);
}
public Person () {}
public Person (int h) {}
public Person(int h, String n) {
height = h;
name = n;
}
}
| UTF-8 | Java | 349 | java | Person.java | Java | [
{
"context": "ublic int height = 180;\n public String name = \"Default\";\n\n public static void say(String name) {\n ",
"end": 114,
"score": 0.5329888463020325,
"start": 107,
"tag": "NAME",
"value": "Default"
}
]
| null | []
| package study.polymorphizm;
public class Person {
public int height = 180;
public String name = "Default";
public static void say(String name) {
System.out.println ("Hello, " + name);
}
public Person () {}
public Person (int h) {}
public Person(int h, String n) {
height = h;
name = n;
}
}
| 349 | 0.570201 | 0.561605 | 17 | 19.529411 | 14.955297 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 15 |
27eddb6d300625d45c3830fd0f2382c05cfa7153 | 6,786,048,394,677 | 6e28108100856bc0ac49343a7d52f1334f9792ab | /Week3_ExtraPrograms/samm.java | 5b5bfa7da99be2e1151f6c88f5cec47893c257b5 | []
| no_license | SaiPraveenMarni/java | https://github.com/SaiPraveenMarni/java | abb470609860f3224a0d099c210047a3ebdb99c2 | 5f531581eb249069b0af26eae59bdfe0aa225c9f | refs/heads/master | 2023-02-24T22:21:35.489000 | 2021-12-08T19:01:45 | 2021-12-08T19:01:45 | 296,529,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class samm
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the numbers:");
int num = in.nextInt();
int a[] = new int[num];
int b[] = new int[num];
int value,j=0,k=0;
for(int i=0;i<num;i++)
{
value = in.nextInt();
if(value%2==0)
{
a[j]=value;
j++;
}
else
{
b[k]=value;
k++;
}
}
int sum=0;
int small=a[0];
int big = a[0];
for(int i=0;i<j;i++)
{
sum=sum+a[i];
if(small>a[i])
{
small = a[i];
}
if(big<a[i])
{
big = a[i];
}
}
System.out.println("Sum of all numbers in C: "+sum);
System.out.println("Average of all numbers in C: "+(sum/2));
System.out.println("Smallest number in C: "+small);
System.out.println("Largest number in C: "+big);
}
}
| UTF-8 | Java | 806 | java | samm.java | Java | []
| null | []
| import java.util.Scanner;
public class samm
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the numbers:");
int num = in.nextInt();
int a[] = new int[num];
int b[] = new int[num];
int value,j=0,k=0;
for(int i=0;i<num;i++)
{
value = in.nextInt();
if(value%2==0)
{
a[j]=value;
j++;
}
else
{
b[k]=value;
k++;
}
}
int sum=0;
int small=a[0];
int big = a[0];
for(int i=0;i<j;i++)
{
sum=sum+a[i];
if(small>a[i])
{
small = a[i];
}
if(big<a[i])
{
big = a[i];
}
}
System.out.println("Sum of all numbers in C: "+sum);
System.out.println("Average of all numbers in C: "+(sum/2));
System.out.println("Smallest number in C: "+small);
System.out.println("Largest number in C: "+big);
}
}
| 806 | 0.566998 | 0.554591 | 46 | 15.521739 | 16.033577 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false | 15 |
4ab2296b1126b943f1d91d5366f56ed8922f6f04 | 22,497,038,719,798 | d0d4ce5946d14015e27c10c62bd21892ff78484b | /ilves-vaadin/src/main/java/org/bubblecloud/ilves/ui/administrator/directory/UserDirectoriesFlowlet.java | 25a0b846f94c8f4dd84fb06dca8274c97050fb23 | [
"Apache-2.0"
]
| permissive | bubblecloud/ilves | https://github.com/bubblecloud/ilves | 853b897ee11cb6de1a7aa641b9f7ebc26791f3d9 | f4745996bf72b831dc77440dbec29a0cca8d4395 | refs/heads/master | 2020-05-20T08:44:39.220000 | 2017-09-08T07:27:07 | 2017-09-08T07:27:07 | 23,491,281 | 7 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright 2013 Tommi S.E. Laukkanen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bubblecloud.ilves.ui.administrator.directory;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import org.bubblecloud.ilves.component.flow.AbstractFlowlet;
import org.bubblecloud.ilves.component.grid.FieldDescriptor;
import org.bubblecloud.ilves.component.grid.FilterDescriptor;
import org.bubblecloud.ilves.component.grid.Grid;
import org.bubblecloud.ilves.model.Company;
import org.bubblecloud.ilves.model.UserDirectory;
import org.bubblecloud.ilves.security.SecurityService;
import org.bubblecloud.ilves.site.SiteFields;
import org.vaadin.addons.lazyquerycontainer.EntityContainer;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* UserDirectory list flow.
*
* @author Tommi S.E. Laukkanen
*/
public final class UserDirectoriesFlowlet extends AbstractFlowlet {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
/** The entity container. */
private EntityContainer<UserDirectory> entityContainer;
/** The userDirectory grid. */
private Grid entityGrid;
@Override
public String getFlowletKey() {
return "directories";
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isValid() {
return true;
}
@Override
public void initialize() {
final List<FieldDescriptor> fieldDefinitions = new ArrayList<FieldDescriptor>(
SiteFields.getFieldDescriptors(UserDirectory.class));
for (final FieldDescriptor fieldDescriptor : fieldDefinitions) {
if (fieldDescriptor.getId().equals("loginPassword")) {
fieldDefinitions.remove(fieldDescriptor);
break;
}
}
final List<FilterDescriptor> filterDefinitions = new ArrayList<FilterDescriptor>();
final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
entityContainer = new EntityContainer<UserDirectory>(entityManager, true, false, false, UserDirectory.class, 1000, new String[] { "address", "port" }, new boolean[] { true, true }, "userDirectoryId");
for (final FieldDescriptor fieldDefinition : fieldDefinitions) {
entityContainer.addContainerProperty(fieldDefinition.getId(), fieldDefinition.getValueType(), fieldDefinition.getDefaultValue(),
fieldDefinition.isReadOnly(), fieldDefinition.isSortable());
}
final GridLayout gridLayout = new GridLayout(1, 2);
gridLayout.setSizeFull();
gridLayout.setMargin(false);
gridLayout.setSpacing(true);
gridLayout.setRowExpandRatio(1, 1f);
setViewContent(gridLayout);
final HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setSpacing(true);
buttonLayout.setSizeUndefined();
gridLayout.addComponent(buttonLayout, 0, 0);
final Table table = new Table();
entityGrid = new Grid(table, entityContainer);
entityGrid.setFields(fieldDefinitions);
entityGrid.setFilters(filterDefinitions);
//entityGrid.setFixedWhereCriteria("e.owner.companyId=:companyId");
table.setColumnCollapsed("loginDn", true);
table.setColumnCollapsed("userEmailAttribute", true);
table.setColumnCollapsed("userSearchBaseDn", true);
table.setColumnCollapsed("groupSearchBaseDn", true);
table.setColumnCollapsed("remoteLocalGroupMapping", true);
table.setColumnCollapsed("created", true);
table.setColumnCollapsed("modified", true);
gridLayout.addComponent(entityGrid, 0, 1);
final Button addButton = new Button("Add");
addButton.setIcon(getSite().getIcon("button-icon-add"));
buttonLayout.addComponent(addButton);
addButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
final UserDirectory userDirectory = new UserDirectory();
userDirectory.setCreated(new Date());
userDirectory.setModified(userDirectory.getCreated());
userDirectory.setOwner((Company) getSite().getSiteContext().getObject(Company.class));
final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
userDirectoryView.edit(userDirectory, true);
}
});
final Button editButton = new Button("Edit");
editButton.setIcon(getSite().getIcon("button-icon-edit"));
buttonLayout.addComponent(editButton);
editButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
if (entityGrid.getSelectedItemId() == null) {
return;
}
final UserDirectory entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
userDirectoryView.edit(entity, false);
}
});
final Button removeButton = new Button("Remove");
removeButton.setIcon(getSite().getIcon("button-icon-remove"));
buttonLayout.addComponent(removeButton);
removeButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
if (entityGrid.getSelectedItemId() == null) {
return;
}
final UserDirectory entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
SecurityService.removeUserDirectory(getSite().getSiteContext(), entity);
entityContainer.refresh();
}
});
}
@Override
public void enter() {
final Company company = getSite().getSiteContext().getObject(Company.class);
//entityGrid.getFixedWhereParameters().put("companyId", company.getCompanyId());
entityContainer.removeDefaultFilters();
entityContainer.addDefaultFilter(new Compare.Equal("owner.companyId", company.getCompanyId()));
entityGrid.refresh();
}
}
| UTF-8 | Java | 7,408 | java | UserDirectoriesFlowlet.java | Java | [
{
"context": "/**\n * Copyright 2013 Tommi S.E. Laukkanen\n *\n * Licensed under the Apache License, Version ",
"end": 42,
"score": 0.9998859167098999,
"start": 22,
"tag": "NAME",
"value": "Tommi S.E. Laukkanen"
},
{
"context": "st;\n\n/**\n * UserDirectory list flow.\n *\n * @author Tommi S.E. Laukkanen\n */\npublic final class UserDirectoriesFlowlet ext",
"end": 1588,
"score": 0.9998801946640015,
"start": 1568,
"tag": "NAME",
"value": "Tommi S.E. Laukkanen"
}
]
| null | []
| /**
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bubblecloud.ilves.ui.administrator.directory;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import org.bubblecloud.ilves.component.flow.AbstractFlowlet;
import org.bubblecloud.ilves.component.grid.FieldDescriptor;
import org.bubblecloud.ilves.component.grid.FilterDescriptor;
import org.bubblecloud.ilves.component.grid.Grid;
import org.bubblecloud.ilves.model.Company;
import org.bubblecloud.ilves.model.UserDirectory;
import org.bubblecloud.ilves.security.SecurityService;
import org.bubblecloud.ilves.site.SiteFields;
import org.vaadin.addons.lazyquerycontainer.EntityContainer;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* UserDirectory list flow.
*
* @author <NAME>
*/
public final class UserDirectoriesFlowlet extends AbstractFlowlet {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
/** The entity container. */
private EntityContainer<UserDirectory> entityContainer;
/** The userDirectory grid. */
private Grid entityGrid;
@Override
public String getFlowletKey() {
return "directories";
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isValid() {
return true;
}
@Override
public void initialize() {
final List<FieldDescriptor> fieldDefinitions = new ArrayList<FieldDescriptor>(
SiteFields.getFieldDescriptors(UserDirectory.class));
for (final FieldDescriptor fieldDescriptor : fieldDefinitions) {
if (fieldDescriptor.getId().equals("loginPassword")) {
fieldDefinitions.remove(fieldDescriptor);
break;
}
}
final List<FilterDescriptor> filterDefinitions = new ArrayList<FilterDescriptor>();
final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
entityContainer = new EntityContainer<UserDirectory>(entityManager, true, false, false, UserDirectory.class, 1000, new String[] { "address", "port" }, new boolean[] { true, true }, "userDirectoryId");
for (final FieldDescriptor fieldDefinition : fieldDefinitions) {
entityContainer.addContainerProperty(fieldDefinition.getId(), fieldDefinition.getValueType(), fieldDefinition.getDefaultValue(),
fieldDefinition.isReadOnly(), fieldDefinition.isSortable());
}
final GridLayout gridLayout = new GridLayout(1, 2);
gridLayout.setSizeFull();
gridLayout.setMargin(false);
gridLayout.setSpacing(true);
gridLayout.setRowExpandRatio(1, 1f);
setViewContent(gridLayout);
final HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setSpacing(true);
buttonLayout.setSizeUndefined();
gridLayout.addComponent(buttonLayout, 0, 0);
final Table table = new Table();
entityGrid = new Grid(table, entityContainer);
entityGrid.setFields(fieldDefinitions);
entityGrid.setFilters(filterDefinitions);
//entityGrid.setFixedWhereCriteria("e.owner.companyId=:companyId");
table.setColumnCollapsed("loginDn", true);
table.setColumnCollapsed("userEmailAttribute", true);
table.setColumnCollapsed("userSearchBaseDn", true);
table.setColumnCollapsed("groupSearchBaseDn", true);
table.setColumnCollapsed("remoteLocalGroupMapping", true);
table.setColumnCollapsed("created", true);
table.setColumnCollapsed("modified", true);
gridLayout.addComponent(entityGrid, 0, 1);
final Button addButton = new Button("Add");
addButton.setIcon(getSite().getIcon("button-icon-add"));
buttonLayout.addComponent(addButton);
addButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
final UserDirectory userDirectory = new UserDirectory();
userDirectory.setCreated(new Date());
userDirectory.setModified(userDirectory.getCreated());
userDirectory.setOwner((Company) getSite().getSiteContext().getObject(Company.class));
final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
userDirectoryView.edit(userDirectory, true);
}
});
final Button editButton = new Button("Edit");
editButton.setIcon(getSite().getIcon("button-icon-edit"));
buttonLayout.addComponent(editButton);
editButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
if (entityGrid.getSelectedItemId() == null) {
return;
}
final UserDirectory entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
userDirectoryView.edit(entity, false);
}
});
final Button removeButton = new Button("Remove");
removeButton.setIcon(getSite().getIcon("button-icon-remove"));
buttonLayout.addComponent(removeButton);
removeButton.addClickListener(new ClickListener() {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(final ClickEvent event) {
if (entityGrid.getSelectedItemId() == null) {
return;
}
final UserDirectory entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
SecurityService.removeUserDirectory(getSite().getSiteContext(), entity);
entityContainer.refresh();
}
});
}
@Override
public void enter() {
final Company company = getSite().getSiteContext().getObject(Company.class);
//entityGrid.getFixedWhereParameters().put("companyId", company.getCompanyId());
entityContainer.removeDefaultFilters();
entityContainer.addDefaultFilter(new Compare.Equal("owner.companyId", company.getCompanyId()));
entityGrid.refresh();
}
}
| 7,380 | 0.677916 | 0.674676 | 186 | 38.827957 | 31.856743 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.693548 | false | false | 15 |
c11809fb37900cb36ebf76ce18c738d15b520632 | 1,563,368,120,007 | 39b6f83641d1a80a48937c42beb6a73311aebc55 | /extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/sortedset/SortedSetCommands.java | abe766201c54e2fa1f0d1dfcf18430aa4e40c002 | [
"Apache-2.0"
]
| permissive | quarkusio/quarkus | https://github.com/quarkusio/quarkus | 112ecda7236bc061920978ac49289da6259360f4 | 68af440f3081de7a26bbee655f74bb8b2c57c2d5 | refs/heads/main | 2023-09-04T06:39:33.043000 | 2023-09-04T05:44:43 | 2023-09-04T05:44:43 | 139,914,932 | 13,109 | 2,940 | Apache-2.0 | false | 2023-09-14T21:31:23 | 2018-07-06T00:44:20 | 2023-09-14T21:29:58 | 2023-09-14T21:31:22 | 264,839 | 12,241 | 2,328 | 2,315 | Java | false | false | package io.quarkus.redis.datasource.sortedset;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalLong;
import io.quarkus.redis.datasource.RedisCommands;
import io.quarkus.redis.datasource.ScanArgs;
import io.quarkus.redis.datasource.SortArgs;
import io.quarkus.redis.datasource.list.KeyValue;
/**
* Allows executing commands from the {@code sorted set} group.
* See <a href="https://redis.io/commands/?group=sorted-set">the sorted set command
* list</a> for further information about these commands.
* <p>
* A {@code sorted set} is a set of value associated with scores. These scores allow comparing the elements. As a result,
* we obtain a sorted set.
* <p>
* Scores are of type {@code double}.
*
* @param <K> the type of the key
* @param <V> the type of the scored item
*/
public interface SortedSetCommands<K, V> extends RedisCommands {
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param score the score
* @param member the member
* @return {@code true} if the element was added, {@code false} otherwise
**/
boolean zadd(K key, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param items the map of score/value to be added
* @return the number of added elements
**/
int zadd(K key, Map<V, Double> items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param items the pairs of value/score to be added
* @return the number of added elements
**/
int zadd(K key, ScoredValue<V>... items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param score the score
* @param member the member
* @return {@code true} if the element was added or changed, {@code false} otherwise
**/
boolean zadd(K key, ZAddArgs zAddArgs, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param items the map of value/score to be added
* @return the number of added items
**/
int zadd(K key, ZAddArgs zAddArgs, Map<V, Double> items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param items the pairs of score/value to be added
* @return the number of added items
**/
int zadd(K key, ZAddArgs zAddArgs, ScoredValue<V>... items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists applying the {@code INCR}
* option
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This variant of {@code ZADD} acts like {@code ZINCRBY}. Only one score-element pair can be specified in this mode.
*
* @param key the key.
* @param score the increment.
* @param member the member.
* @return the new score of the updated member
*/
double zaddincr(K key, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists applying the {@code INCR}
* option
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This variant of {@code ZADD} acts like {@code ZINCRBY}. Only one score-element pair can be specified in this mode.
*
* @param key the key.
* @param score the increment.
* @param member the member.
* @return the new score of the updated member, or {@code empty} if the operation was aborted
* (when called with either the XX or the NX option).
*/
OptionalDouble zaddincr(K key, ZAddArgs zAddArgs, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zcard">ZCARD</a>.
* Summary: Get the number of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @return the cardinality (number of elements) of the sorted set. {@code 0} if the key does not exist.
**/
long zcard(K key);
/**
* Execute the command <a href="https://redis.io/commands/zcount">ZCOUNT</a>.
* Summary: Count the members in a sorted set with scores within the given values
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @param range the range
* @return the number of elements in the specified score range.
**/
long zcount(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zdiff">ZDIFF</a>.
* Summary: Subtract multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of the difference.
**/
List<V> zdiff(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zdiff">ZDIFF</a>.
* Summary: Subtract multiple sorted sets, and returns the list of keys with their scores
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of the difference.
**/
List<ScoredValue<V>> zdiffWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zdiffstore">ZDIFFSTORE</a>.
* Summary: Subtract multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param destination the destination key
* @param keys the keys to compare
* @return the number of elements in the resulting sorted set at destination.
**/
long zdiffstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zincrby">ZINCRBY</a>.
* Summary: Increment the score of a member in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @return the new score of member
**/
double zincrby(K key, double increment, V member);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param arguments the ZINTER command extra-arguments
* @param keys the keys
* @return the result of intersection.
**/
List<V> zinter(ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of intersection.
**/
List<V> zinter(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param arguments the ZINTER command extra-arguments
* @param keys the keys
* @return the result of intersection with the scores
**/
List<ScoredValue<V>> zinterWithScores(ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of intersection with the scores
**/
List<ScoredValue<V>> zinterWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zintercard">ZINTERCARD</a>.
* Summary: Intersect multiple sorted sets and return the cardinality of the result
* Group: sorted-set
* Requires Redis 7.0.0
*
* @param keys the keys
* @return the number of elements in the resulting intersection.
**/
long zintercard(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zintercard">ZINTERCARD</a>.
* Summary: Intersect multiple sorted sets and return the cardinality of the result
* Group: sorted-set
* Requires Redis 7.0.0
*
* @param limit if the intersection cardinality reaches limit partway through the computation, the algorithm will
* exit and yield limit as the cardinality.
* @param keys the keys
* @return the number of elements in the resulting intersection.
**/
long zintercard(long limit, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinterstore">ZINTERSTORE</a>.
* Summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param arguments the ZINTERSTORE command extra-arguments
* @param keys the keys of the sorted set to analyze
* @return the number of elements in the resulting sorted set at destination.
**/
long zinterstore(K destination, ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinterstore">ZINTERSTORE</a>.
* Summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param keys the keys of the sorted set to analyze
* @return the number of elements in the resulting sorted set at destination.
**/
long zinterstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zlexcount">ZLEXCOUNT</a>.
* Summary: Count the number of members in a sorted set between a given lexicographical range
* Group: sorted-set
* Requires Redis 2.8.9
*
* @param key the key
* @param range the range
* @return the number of elements in the specified score range.
**/
long zlexcount(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> zmpopMin(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> zmpopMin(int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> zmpopMax(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> zmpopMax(int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param timeout the timeout
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> bzmpopMin(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param timeout the timeout
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> bzmpopMin(Duration timeout, int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param timeout the timeout
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> bzmpopMax(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param timeout the timeout
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> bzmpopMax(Duration timeout, int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmscore">ZMSCORE</a>.
* Summary: Get the score associated with the given members in a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param members the members
* @return list of scores or {@code empty} associated with the specified member values.
**/
List<OptionalDouble> zmscore(K key, V... members);
/**
* Execute the command <a href="https://redis.io/commands/zpopmax">ZPOPMAX</a>.
* Summary: Remove and return members with the highest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped element and score, {@link ScoredValue#EMPTY} is no member can be popped.
**/
ScoredValue<V> zpopmax(K key);
/**
* Execute the command <a href="https://redis.io/commands/zpopmax">ZPOPMAX</a>.
* Summary: Remove and return members with the highest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped elements and scores.
**/
List<ScoredValue<V>> zpopmax(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zpopmin">ZPOPMIN</a>.
* Summary: Remove and return members with the lowest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped element and score, {@link ScoredValue#EMPTY} is no member can be popped.
**/
ScoredValue<V> zpopmin(K key);
/**
* Execute the command <a href="https://redis.io/commands/zpopmin">ZPOPMIN</a>.
* Summary: Remove and return members with the lowest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped elements and scores.
**/
List<ScoredValue<V>> zpopmin(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @return the randomly selected element, or {@code null} when key does not exist.
**/
V zrandmember(K key);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param count the number of member to select
* @return the list of elements, or an empty array when key does not exist.
**/
List<V> zrandmember(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @return the randomly selected element and its score, or {@code null} when key does not exist.
**/
ScoredValue<V> zrandmemberWithScores(K key);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param count the number of member to select
* @return the list of elements (with their score), or an empty array when key does not exist.
**/
List<ScoredValue<V>> zrandmemberWithScores(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/bzpopmin">BZPOPMIN</a>.
* Summary: Remove and return the member with the lowest score from one or more sorted sets, or block until one is available
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param timeout the max timeout
* @param keys the keys
* @return {@code null} when no element could be popped and the timeout expired. A structure containing the key and
* the {@link ScoredValue} with the popped value and the score.
**/
KeyValue<K, ScoredValue<V>> bzpopmin(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzpopmax">BZPOPMAX</a>.
* Summary: Remove and return the member with the highest score from one or more sorted sets, or block until one is
* available
* Group: sorted-set
* Requires Redis 5.0.0
*
* @return {@code null} when no element could be popped and the timeout expired. A structure containing the key and
* the {@link ScoredValue} with the popped value and the score.
**/
KeyValue<K, ScoredValue<V>> bzpopmax(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This method extracts a range my rank/index in the stream.
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrange(K key, long start, long stop, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @param args the extra ZRANGE parameters
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangeWithScores(K key, long start, long stop, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This method extracts a range my rank/index in the stream.
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @return list of elements in the specified range.
**/
List<V> zrange(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangeWithScores(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrangebylex(K key, Range<String> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements in the specified range.
**/
List<V> zrangebylex(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrangebyscore(K key, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangebyscoreWithScores(K key, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements in the specified range.
**/
List<V> zrangebyscore(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangebyscoreWithScores(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by rank) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param min the lower bound of the range
* @param max the upper bound of the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestore(K dst, K src, long min, long max, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by rank) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param min the lower bound of the range
* @param max the upper bound of the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestore(K dst, K src, long min, long max);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by lexicographical order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebylex(K dst, K src, Range<String> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by lexicographical order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebylex(K dst, K src, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by score order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebyscore(K dst, K src, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by score order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebyscore(K dst, K src, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrank">ZRANK</a>.
* Summary: Determine the index of a member in a sorted set
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @return the rank of member. If member does not exist in the sorted set or key does not exist, {@code empty}.
**/
OptionalLong zrank(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zrem">ZREM</a>.
* Summary: Remove one or more members from a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param members the members to remove
* @return The number of members removed from the sorted set, not including non-existing members.
**/
int zrem(K key, V... members);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebylex">ZREMRANGEBYLEX</a>.
* Summary: Remove all members in a sorted set between the given lexicographical range
* Group: sorted-set
* Requires Redis 2.8.9
*
* @param key the key
* @param range the range
* @return the number of elements removed.
**/
long zremrangebylex(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebyrank">ZREMRANGEBYRANK</a>.
* Summary: Remove all members in a sorted set within the given indexes
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @param start the lower bound of the range
* @param stop the upper bound of the range
* @return the number of elements removed.
**/
long zremrangebyrank(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebyscore">ZREMRANGEBYSCORE</a>.
* Summary: Remove all members in a sorted set within the given scores
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return the number of elements removed.
**/
long zremrangebyscore(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrevrank">ZREVRANK</a>.
* Summary: Determine the index of a member in a sorted set, with scores ordered from high to low
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @return the rank of member. If member does not exist in the sorted set or key does not exist, {@code empty}.
**/
OptionalLong zrevrank(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zscan">ZSCAN</a>.
* Summary: Incrementally iterate sorted sets elements and associated scores
* Group: sorted-set
* Requires Redis 2.8.0
*
* @param key the key
* @return the cursor to iterate over the sorted set
**/
ZScanCursor<V> zscan(K key);
/**
* Execute the command <a href="https://redis.io/commands/zscan">ZSCAN</a>.
* Summary: Incrementally iterate sorted sets elements and associated scores
* Group: sorted-set
* Requires Redis 2.8.0
*
* @param key the key
* @param args the extra scan arguments
* @return the cursor to iterate over the sorted set
**/
ZScanCursor<V> zscan(K key, ScanArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zscore">ZSCORE</a>.
* Summary: Get the score associated with the given member in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param member the member
* @return the score of member, {@code empty} if the member cannot be found or the key does not exist
**/
OptionalDouble zscore(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param args the ZUNION command extra-arguments
* @param keys the keys
* @return the result of union
**/
List<V> zunion(ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of union
**/
List<V> zunion(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param args the ZUNION command extra-arguments
* @param keys the keys
* @return the result of union
**/
List<ScoredValue<V>> zunionWithScores(ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of union
**/
List<ScoredValue<V>> zunionWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunionstore">ZUNIONSTORE</a>.
* Summary: Add multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param args the zunionstore command extra-arguments
* @param keys the keys
* @return the number of elements in the resulting sorted set at destination.
**/
long zunionstore(K destination, ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunionstore">ZUNIONSTORE</a>.
* Summary: Add multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param keys the keys
* @return the number of elements in the resulting sorted set at destination.
**/
long zunionstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a>.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @return the list of sorted elements.
**/
List<V> sort(K key);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a>.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param sortArguments the {@code SORT} command extra-arguments
* @return the list of sorted elements.
**/
List<V> sort(K key, SortArgs sortArguments);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a> with the {@code STORE} option.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @param sortArguments the SORT command extra-arguments
* @return the number of sorted elements in the destination list.
**/
long sortAndStore(K key, K destination, SortArgs sortArguments);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a> with the {@code STORE} option.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @return the number of sorted elements in the destination list.
**/
long sortAndStore(K key, K destination);
}
| UTF-8 | Java | 36,498 | java | SortedSetCommands.java | Java | []
| null | []
| package io.quarkus.redis.datasource.sortedset;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalLong;
import io.quarkus.redis.datasource.RedisCommands;
import io.quarkus.redis.datasource.ScanArgs;
import io.quarkus.redis.datasource.SortArgs;
import io.quarkus.redis.datasource.list.KeyValue;
/**
* Allows executing commands from the {@code sorted set} group.
* See <a href="https://redis.io/commands/?group=sorted-set">the sorted set command
* list</a> for further information about these commands.
* <p>
* A {@code sorted set} is a set of value associated with scores. These scores allow comparing the elements. As a result,
* we obtain a sorted set.
* <p>
* Scores are of type {@code double}.
*
* @param <K> the type of the key
* @param <V> the type of the scored item
*/
public interface SortedSetCommands<K, V> extends RedisCommands {
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param score the score
* @param member the member
* @return {@code true} if the element was added, {@code false} otherwise
**/
boolean zadd(K key, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param items the map of score/value to be added
* @return the number of added elements
**/
int zadd(K key, Map<V, Double> items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param items the pairs of value/score to be added
* @return the number of added elements
**/
int zadd(K key, ScoredValue<V>... items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param score the score
* @param member the member
* @return {@code true} if the element was added or changed, {@code false} otherwise
**/
boolean zadd(K key, ZAddArgs zAddArgs, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param items the map of value/score to be added
* @return the number of added items
**/
int zadd(K key, ZAddArgs zAddArgs, Map<V, Double> items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param zAddArgs the extra parameter
* @param items the pairs of score/value to be added
* @return the number of added items
**/
int zadd(K key, ZAddArgs zAddArgs, ScoredValue<V>... items);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists applying the {@code INCR}
* option
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This variant of {@code ZADD} acts like {@code ZINCRBY}. Only one score-element pair can be specified in this mode.
*
* @param key the key.
* @param score the increment.
* @param member the member.
* @return the new score of the updated member
*/
double zaddincr(K key, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zadd">ZADD</a>.
* Summary: Add one or more members to a sorted set, or update its score if it already exists applying the {@code INCR}
* option
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This variant of {@code ZADD} acts like {@code ZINCRBY}. Only one score-element pair can be specified in this mode.
*
* @param key the key.
* @param score the increment.
* @param member the member.
* @return the new score of the updated member, or {@code empty} if the operation was aborted
* (when called with either the XX or the NX option).
*/
OptionalDouble zaddincr(K key, ZAddArgs zAddArgs, double score, V member);
/**
* Execute the command <a href="https://redis.io/commands/zcard">ZCARD</a>.
* Summary: Get the number of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @return the cardinality (number of elements) of the sorted set. {@code 0} if the key does not exist.
**/
long zcard(K key);
/**
* Execute the command <a href="https://redis.io/commands/zcount">ZCOUNT</a>.
* Summary: Count the members in a sorted set with scores within the given values
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @param range the range
* @return the number of elements in the specified score range.
**/
long zcount(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zdiff">ZDIFF</a>.
* Summary: Subtract multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of the difference.
**/
List<V> zdiff(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zdiff">ZDIFF</a>.
* Summary: Subtract multiple sorted sets, and returns the list of keys with their scores
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of the difference.
**/
List<ScoredValue<V>> zdiffWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zdiffstore">ZDIFFSTORE</a>.
* Summary: Subtract multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param destination the destination key
* @param keys the keys to compare
* @return the number of elements in the resulting sorted set at destination.
**/
long zdiffstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zincrby">ZINCRBY</a>.
* Summary: Increment the score of a member in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @return the new score of member
**/
double zincrby(K key, double increment, V member);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param arguments the ZINTER command extra-arguments
* @param keys the keys
* @return the result of intersection.
**/
List<V> zinter(ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of intersection.
**/
List<V> zinter(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param arguments the ZINTER command extra-arguments
* @param keys the keys
* @return the result of intersection with the scores
**/
List<ScoredValue<V>> zinterWithScores(ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinter">ZINTER</a>.
* Summary: Intersect multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of intersection with the scores
**/
List<ScoredValue<V>> zinterWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zintercard">ZINTERCARD</a>.
* Summary: Intersect multiple sorted sets and return the cardinality of the result
* Group: sorted-set
* Requires Redis 7.0.0
*
* @param keys the keys
* @return the number of elements in the resulting intersection.
**/
long zintercard(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zintercard">ZINTERCARD</a>.
* Summary: Intersect multiple sorted sets and return the cardinality of the result
* Group: sorted-set
* Requires Redis 7.0.0
*
* @param limit if the intersection cardinality reaches limit partway through the computation, the algorithm will
* exit and yield limit as the cardinality.
* @param keys the keys
* @return the number of elements in the resulting intersection.
**/
long zintercard(long limit, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinterstore">ZINTERSTORE</a>.
* Summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param arguments the ZINTERSTORE command extra-arguments
* @param keys the keys of the sorted set to analyze
* @return the number of elements in the resulting sorted set at destination.
**/
long zinterstore(K destination, ZAggregateArgs arguments, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zinterstore">ZINTERSTORE</a>.
* Summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param keys the keys of the sorted set to analyze
* @return the number of elements in the resulting sorted set at destination.
**/
long zinterstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zlexcount">ZLEXCOUNT</a>.
* Summary: Count the number of members in a sorted set between a given lexicographical range
* Group: sorted-set
* Requires Redis 2.8.9
*
* @param key the key
* @param range the range
* @return the number of elements in the specified score range.
**/
long zlexcount(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> zmpopMin(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> zmpopMin(int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> zmpopMax(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmpop">ZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> zmpopMax(int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param timeout the timeout
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> bzmpopMin(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements popped are those with the lowest scores from the first non-empty sorted set.
*
* @param timeout the timeout
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> bzmpopMin(Duration timeout, int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param timeout the timeout
* @param keys the keys
* @return The popped element (value / score), or {@code null} if no element can be popped.
**/
ScoredValue<V> bzmpopMax(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzmpop">BZMPOP</a>.
* Summary: Remove and return members with scores in a sorted set or block until one is available.
* Group: sorted-set
* Requires Redis 7.0.0
* <p>
* The elements with the highest scores to be popped.
*
* @param timeout the timeout
* @param count the max number of element to pop
* @param keys the keys
* @return The popped element (value / score), or {@code empty} if no element can be popped.
**/
List<ScoredValue<V>> bzmpopMax(Duration timeout, int count, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zmscore">ZMSCORE</a>.
* Summary: Get the score associated with the given members in a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param members the members
* @return list of scores or {@code empty} associated with the specified member values.
**/
List<OptionalDouble> zmscore(K key, V... members);
/**
* Execute the command <a href="https://redis.io/commands/zpopmax">ZPOPMAX</a>.
* Summary: Remove and return members with the highest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped element and score, {@link ScoredValue#EMPTY} is no member can be popped.
**/
ScoredValue<V> zpopmax(K key);
/**
* Execute the command <a href="https://redis.io/commands/zpopmax">ZPOPMAX</a>.
* Summary: Remove and return members with the highest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped elements and scores.
**/
List<ScoredValue<V>> zpopmax(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zpopmin">ZPOPMIN</a>.
* Summary: Remove and return members with the lowest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped element and score, {@link ScoredValue#EMPTY} is no member can be popped.
**/
ScoredValue<V> zpopmin(K key);
/**
* Execute the command <a href="https://redis.io/commands/zpopmin">ZPOPMIN</a>.
* Summary: Remove and return members with the lowest scores in a sorted set
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param key the key
* @return the popped elements and scores.
**/
List<ScoredValue<V>> zpopmin(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @return the randomly selected element, or {@code null} when key does not exist.
**/
V zrandmember(K key);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param count the number of member to select
* @return the list of elements, or an empty array when key does not exist.
**/
List<V> zrandmember(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @return the randomly selected element and its score, or {@code null} when key does not exist.
**/
ScoredValue<V> zrandmemberWithScores(K key);
/**
* Execute the command <a href="https://redis.io/commands/zrandmember">ZRANDMEMBER</a>.
* Summary: Get one or multiple random elements from a sorted set
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param key the key
* @param count the number of member to select
* @return the list of elements (with their score), or an empty array when key does not exist.
**/
List<ScoredValue<V>> zrandmemberWithScores(K key, int count);
/**
* Execute the command <a href="https://redis.io/commands/bzpopmin">BZPOPMIN</a>.
* Summary: Remove and return the member with the lowest score from one or more sorted sets, or block until one is available
* Group: sorted-set
* Requires Redis 5.0.0
*
* @param timeout the max timeout
* @param keys the keys
* @return {@code null} when no element could be popped and the timeout expired. A structure containing the key and
* the {@link ScoredValue} with the popped value and the score.
**/
KeyValue<K, ScoredValue<V>> bzpopmin(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/bzpopmax">BZPOPMAX</a>.
* Summary: Remove and return the member with the highest score from one or more sorted sets, or block until one is
* available
* Group: sorted-set
* Requires Redis 5.0.0
*
* @return {@code null} when no element could be popped and the timeout expired. A structure containing the key and
* the {@link ScoredValue} with the popped value and the score.
**/
KeyValue<K, ScoredValue<V>> bzpopmax(Duration timeout, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This method extracts a range my rank/index in the stream.
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrange(K key, long start, long stop, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @param args the extra ZRANGE parameters
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangeWithScores(K key, long start, long stop, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
* <p>
* This method extracts a range my rank/index in the stream.
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @return list of elements in the specified range.
**/
List<V> zrange(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param start the start position
* @param stop the stop position
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangeWithScores(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrangebylex(K key, Range<String> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements in the specified range.
**/
List<V> zrangebylex(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements in the specified range.
**/
List<V> zrangebyscore(K key, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using lexicographical ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @param args the extra ZRANGE parameters
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangebyscoreWithScores(K key, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements in the specified range.
**/
List<V> zrangebyscore(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrange">ZRANGE</a>.
* Summary: Return a range of members in a sorted set using score ranges
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return list of elements with their scores in the specified range.
**/
List<ScoredValue<V>> zrangebyscoreWithScores(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by rank) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param min the lower bound of the range
* @param max the upper bound of the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestore(K dst, K src, long min, long max, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by rank) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param min the lower bound of the range
* @param max the upper bound of the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestore(K dst, K src, long min, long max);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by lexicographical order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebylex(K dst, K src, Range<String> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by lexicographical order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebylex(K dst, K src, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by score order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @param args the ZRANGESTORE command extra-arguments
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebyscore(K dst, K src, ScoreRange<Double> range, ZRangeArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zrangestore">ZRANGESTORE</a>.
* Summary: Store a range (by score order) of members from sorted set into another key
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param dst the key
* @param src the key
* @param range the range
* @return the number of elements in the resulting sorted set.
**/
long zrangestorebyscore(K dst, K src, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrank">ZRANK</a>.
* Summary: Determine the index of a member in a sorted set
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @return the rank of member. If member does not exist in the sorted set or key does not exist, {@code empty}.
**/
OptionalLong zrank(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zrem">ZREM</a>.
* Summary: Remove one or more members from a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param members the members to remove
* @return The number of members removed from the sorted set, not including non-existing members.
**/
int zrem(K key, V... members);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebylex">ZREMRANGEBYLEX</a>.
* Summary: Remove all members in a sorted set between the given lexicographical range
* Group: sorted-set
* Requires Redis 2.8.9
*
* @param key the key
* @param range the range
* @return the number of elements removed.
**/
long zremrangebylex(K key, Range<String> range);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebyrank">ZREMRANGEBYRANK</a>.
* Summary: Remove all members in a sorted set within the given indexes
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @param start the lower bound of the range
* @param stop the upper bound of the range
* @return the number of elements removed.
**/
long zremrangebyrank(K key, long start, long stop);
/**
* Execute the command <a href="https://redis.io/commands/zremrangebyscore">ZREMRANGEBYSCORE</a>.
* Summary: Remove all members in a sorted set within the given scores
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param range the range
* @return the number of elements removed.
**/
long zremrangebyscore(K key, ScoreRange<Double> range);
/**
* Execute the command <a href="https://redis.io/commands/zrevrank">ZREVRANK</a>.
* Summary: Determine the index of a member in a sorted set, with scores ordered from high to low
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param key the key
* @return the rank of member. If member does not exist in the sorted set or key does not exist, {@code empty}.
**/
OptionalLong zrevrank(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zscan">ZSCAN</a>.
* Summary: Incrementally iterate sorted sets elements and associated scores
* Group: sorted-set
* Requires Redis 2.8.0
*
* @param key the key
* @return the cursor to iterate over the sorted set
**/
ZScanCursor<V> zscan(K key);
/**
* Execute the command <a href="https://redis.io/commands/zscan">ZSCAN</a>.
* Summary: Incrementally iterate sorted sets elements and associated scores
* Group: sorted-set
* Requires Redis 2.8.0
*
* @param key the key
* @param args the extra scan arguments
* @return the cursor to iterate over the sorted set
**/
ZScanCursor<V> zscan(K key, ScanArgs args);
/**
* Execute the command <a href="https://redis.io/commands/zscore">ZSCORE</a>.
* Summary: Get the score associated with the given member in a sorted set
* Group: sorted-set
* Requires Redis 1.2.0
*
* @param key the key
* @param member the member
* @return the score of member, {@code empty} if the member cannot be found or the key does not exist
**/
OptionalDouble zscore(K key, V member);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param args the ZUNION command extra-arguments
* @param keys the keys
* @return the result of union
**/
List<V> zunion(ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of union
**/
List<V> zunion(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param args the ZUNION command extra-arguments
* @param keys the keys
* @return the result of union
**/
List<ScoredValue<V>> zunionWithScores(ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunion">ZUNION</a>.
* Summary: Add multiple sorted sets
* Group: sorted-set
* Requires Redis 6.2.0
*
* @param keys the keys
* @return the result of union
**/
List<ScoredValue<V>> zunionWithScores(K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunionstore">ZUNIONSTORE</a>.
* Summary: Add multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param args the zunionstore command extra-arguments
* @param keys the keys
* @return the number of elements in the resulting sorted set at destination.
**/
long zunionstore(K destination, ZAggregateArgs args, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/zunionstore">ZUNIONSTORE</a>.
* Summary: Add multiple sorted sets and store the resulting sorted set in a new key
* Group: sorted-set
* Requires Redis 2.0.0
*
* @param destination the destination key
* @param keys the keys
* @return the number of elements in the resulting sorted set at destination.
**/
long zunionstore(K destination, K... keys);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a>.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @return the list of sorted elements.
**/
List<V> sort(K key);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a>.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @param key the key
* @param sortArguments the {@code SORT} command extra-arguments
* @return the list of sorted elements.
**/
List<V> sort(K key, SortArgs sortArguments);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a> with the {@code STORE} option.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @param sortArguments the SORT command extra-arguments
* @return the number of sorted elements in the destination list.
**/
long sortAndStore(K key, K destination, SortArgs sortArguments);
/**
* Execute the command <a href="https://redis.io/commands/sort">SORT</a> with the {@code STORE} option.
* Summary: Sort the elements in a list, set or sorted set
* Group: generic
* Requires Redis 1.0.0
*
* @return the number of sorted elements in the destination list.
**/
long sortAndStore(K key, K destination);
}
| 36,498 | 0.638227 | 0.63187 | 989 | 35.903942 | 30.865995 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.229525 | false | false | 15 |
55ac0f4bce0dde1eeaf4d715f7a63d2252029c9c | 9,972,914,067,419 | 412e0f779d443b04c2b8c72cd6bd14fbd1d37604 | /ile interdite/src/Vue/VueGrille.java | 775499c076109631562a8253d996a8d74815e3f7 | []
| no_license | anaismoussouni/projetpogl | https://github.com/anaismoussouni/projetpogl | 780178eee6827510484379332e9eb475eac4d30e | 17f5d0a4df5f276641d6861b74c408463f3730bb | refs/heads/master | 2020-03-17T04:09:41.314000 | 2018-05-13T18:50:21 | 2018-05-13T18:50:21 | 133,265,054 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Vue;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
import Modele.CModele;
import Modele.Cellule;
import Modele.Joueur;
/**
* Une classe pour représenter la zone d'affichage des cellules.
*
* JPanel est une classe d'éléments graphiques, pouvant comme JFrame contenir
* d'autres éléments graphiques.
*
* Cette vue va être un observateur du modèle et sera mise à jour à chaque
* nouvelle génération des cellules.
*/
class VueGrille extends JPanel implements Observer {
/** On maintient une référence vers le modèle. */
private CModele modele;
/** Définition d'une taille (en pixels) pour l'affichage des cellules. */
private final static int TAILLE = 100;
public static final int ovalRayon = TAILLE/5;
/** Constructeur. */
public VueGrille(CModele modele) {
this.modele = modele;
/** On enregistre la vue [this] en tant qu'observateur de [modele]. */
modele.addObserver(this);
/**
* Définition et application d'une taille fixe pour cette zone de
* l'interface, calculée en fonction du nombre de cellules et de la
* taille d'affichage.
*/
Dimension dim = new Dimension(TAILLE*CModele.LARGEUR,
TAILLE*CModele.HAUTEUR);
this.setPreferredSize(dim);
}
/**
* L'interface [Observer] demande de fournir une méthode [update], qui
* sera appelée lorsque la vue sera notifiée d'un changement dans le
* modèle. Ici on se content de réafficher toute la grille avec la méthode
* prédéfinie [repaint].
*/
public void update(Observable obs, Object obj) { repaint(); }
/**
* Les éléments graphiques comme [JPanel] possèdent une méthode
* [paintComponent] qui définit l'action à accomplir pour afficher cet
* élément. On la redéfinit ici pour lui confier l'affichage des cellules.
*
* La classe [Graphics] regroupe les éléments de style sur le dessin,
* comme la couleur actuelle.
*/
public void paintComponent(Graphics g) {
super.repaint();
/** Pour chaque cellule... */
for(int i=1; i<=CModele.LARGEUR; i++) {
for(int j=1; j<=CModele.HAUTEUR; j++) {
/**
* ... Appeler une fonction d'affichage auxiliaire.
* On lui fournit les informations de dessin [g] et les
* coordonnées du coin en haut à gauche.
*/
paint(g, modele.getCellule(i, j),
(i-1)*TAILLE,
(j-1)*TAILLE,
modele.getJoueur(0),
modele.getJoueur(1),
modele.getJoueur(2),
modele.getJoueur(3));
}
}
}
/**
* Fonction auxiliaire de dessin d'une cellule.
* Ici, la classe [Cellule] ne peut être désignée que par l'intermédiaire
* de la classe [CModele] à laquelle elle est interne, d'où le type
* [CModele.Cellule].
* Ceci serait impossible si [Cellule] était déclarée privée dans [CModele].
*/
private void paint(Graphics g, Cellule c, int x, int y, Joueur joueur1, Joueur joueur2, Joueur joueur3, Joueur joueur4) {
/** Sélection d'une couleur. */
if (Cellule.Etat.EMERGE.equals(c.getEtat())){
g.setColor(Color.GREEN);
}
else if (Cellule.Etat.INONDE.equals(c.getEtat())){
g.setColor(Color.BLUE);
}
else {
g.setColor(Color.BLACK);
}
/** Coloration d'un rectangle. */
g.fillRect(x, y, TAILLE, TAILLE);
/** Placement des joueurs */
int x1=joueur1.getX();
int y1=joueur1.getY();
g.setColor(Color.red);
int xOval1 = x1 + TAILLE/2 - ovalRayon/2;
int yOval1 = y1 + 20 - ovalRayon/2;
g.fillOval(xOval1, yOval1, ovalRayon, ovalRayon);
int x2=joueur2.getX();
int y2=joueur2.getY();
g.setColor(Color.yellow);
int xOval2 = x2 + TAILLE/2 - ovalRayon/2;
int yOval2 = y2 + TAILLE - 20 - ovalRayon/2;
g.fillOval(xOval2, yOval2, ovalRayon, ovalRayon);
int x3=joueur3.getX();
int y3=joueur3.getY();
g.setColor(Color.white);
int xOval3 = x3 + 20 - ovalRayon/2;
int yOval3 = y3 + TAILLE/2 - ovalRayon/2;
g.fillOval(xOval3, yOval3, ovalRayon, ovalRayon);
int x4=joueur1.getX();
int y4=joueur1.getY();
g.setColor(Color.orange);
int xOval4 = x4 + TAILLE - 20 - ovalRayon/2 ;
int yOval4 = y4 + TAILLE/2 - ovalRayon/2;
g.fillOval(xOval4, yOval4, ovalRayon, ovalRayon);
/**Coloration du grillage */
g.setColor(Color.white);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(4));
for (int i=0; i<=CModele.LARGEUR*TAILLE; i+=TAILLE) {
g2.draw(new Line2D.Float(i, 0, i, CModele.HAUTEUR*TAILLE));
}
for (int j=0; j<=CModele.HAUTEUR*TAILLE; j+=TAILLE) {
g2.draw(new Line2D.Float(0, j,CModele.LARGEUR*TAILLE,j));
}
}
}
| UTF-8 | Java | 5,023 | java | VueGrille.java | Java | []
| null | []
| package Vue;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
import Modele.CModele;
import Modele.Cellule;
import Modele.Joueur;
/**
* Une classe pour représenter la zone d'affichage des cellules.
*
* JPanel est une classe d'éléments graphiques, pouvant comme JFrame contenir
* d'autres éléments graphiques.
*
* Cette vue va être un observateur du modèle et sera mise à jour à chaque
* nouvelle génération des cellules.
*/
class VueGrille extends JPanel implements Observer {
/** On maintient une référence vers le modèle. */
private CModele modele;
/** Définition d'une taille (en pixels) pour l'affichage des cellules. */
private final static int TAILLE = 100;
public static final int ovalRayon = TAILLE/5;
/** Constructeur. */
public VueGrille(CModele modele) {
this.modele = modele;
/** On enregistre la vue [this] en tant qu'observateur de [modele]. */
modele.addObserver(this);
/**
* Définition et application d'une taille fixe pour cette zone de
* l'interface, calculée en fonction du nombre de cellules et de la
* taille d'affichage.
*/
Dimension dim = new Dimension(TAILLE*CModele.LARGEUR,
TAILLE*CModele.HAUTEUR);
this.setPreferredSize(dim);
}
/**
* L'interface [Observer] demande de fournir une méthode [update], qui
* sera appelée lorsque la vue sera notifiée d'un changement dans le
* modèle. Ici on se content de réafficher toute la grille avec la méthode
* prédéfinie [repaint].
*/
public void update(Observable obs, Object obj) { repaint(); }
/**
* Les éléments graphiques comme [JPanel] possèdent une méthode
* [paintComponent] qui définit l'action à accomplir pour afficher cet
* élément. On la redéfinit ici pour lui confier l'affichage des cellules.
*
* La classe [Graphics] regroupe les éléments de style sur le dessin,
* comme la couleur actuelle.
*/
public void paintComponent(Graphics g) {
super.repaint();
/** Pour chaque cellule... */
for(int i=1; i<=CModele.LARGEUR; i++) {
for(int j=1; j<=CModele.HAUTEUR; j++) {
/**
* ... Appeler une fonction d'affichage auxiliaire.
* On lui fournit les informations de dessin [g] et les
* coordonnées du coin en haut à gauche.
*/
paint(g, modele.getCellule(i, j),
(i-1)*TAILLE,
(j-1)*TAILLE,
modele.getJoueur(0),
modele.getJoueur(1),
modele.getJoueur(2),
modele.getJoueur(3));
}
}
}
/**
* Fonction auxiliaire de dessin d'une cellule.
* Ici, la classe [Cellule] ne peut être désignée que par l'intermédiaire
* de la classe [CModele] à laquelle elle est interne, d'où le type
* [CModele.Cellule].
* Ceci serait impossible si [Cellule] était déclarée privée dans [CModele].
*/
private void paint(Graphics g, Cellule c, int x, int y, Joueur joueur1, Joueur joueur2, Joueur joueur3, Joueur joueur4) {
/** Sélection d'une couleur. */
if (Cellule.Etat.EMERGE.equals(c.getEtat())){
g.setColor(Color.GREEN);
}
else if (Cellule.Etat.INONDE.equals(c.getEtat())){
g.setColor(Color.BLUE);
}
else {
g.setColor(Color.BLACK);
}
/** Coloration d'un rectangle. */
g.fillRect(x, y, TAILLE, TAILLE);
/** Placement des joueurs */
int x1=joueur1.getX();
int y1=joueur1.getY();
g.setColor(Color.red);
int xOval1 = x1 + TAILLE/2 - ovalRayon/2;
int yOval1 = y1 + 20 - ovalRayon/2;
g.fillOval(xOval1, yOval1, ovalRayon, ovalRayon);
int x2=joueur2.getX();
int y2=joueur2.getY();
g.setColor(Color.yellow);
int xOval2 = x2 + TAILLE/2 - ovalRayon/2;
int yOval2 = y2 + TAILLE - 20 - ovalRayon/2;
g.fillOval(xOval2, yOval2, ovalRayon, ovalRayon);
int x3=joueur3.getX();
int y3=joueur3.getY();
g.setColor(Color.white);
int xOval3 = x3 + 20 - ovalRayon/2;
int yOval3 = y3 + TAILLE/2 - ovalRayon/2;
g.fillOval(xOval3, yOval3, ovalRayon, ovalRayon);
int x4=joueur1.getX();
int y4=joueur1.getY();
g.setColor(Color.orange);
int xOval4 = x4 + TAILLE - 20 - ovalRayon/2 ;
int yOval4 = y4 + TAILLE/2 - ovalRayon/2;
g.fillOval(xOval4, yOval4, ovalRayon, ovalRayon);
/**Coloration du grillage */
g.setColor(Color.white);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(4));
for (int i=0; i<=CModele.LARGEUR*TAILLE; i+=TAILLE) {
g2.draw(new Line2D.Float(i, 0, i, CModele.HAUTEUR*TAILLE));
}
for (int j=0; j<=CModele.HAUTEUR*TAILLE; j+=TAILLE) {
g2.draw(new Line2D.Float(0, j,CModele.LARGEUR*TAILLE,j));
}
}
}
| 5,023 | 0.638319 | 0.620024 | 163 | 29.509203 | 24.467926 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.503067 | false | false | 15 |
8d68586b0ed3690a7e2ac796f8a4e283c097b34a | 22,144,851,448,147 | 1d077e92735f63ee8eef32cae08dc34c72d7c694 | /Exercise_1/Driver.java | 97a8c473c0cad58d8333782a66b6c70c9858f860 | []
| no_license | yulizar/Task_3-1 | https://github.com/yulizar/Task_3-1 | 18f9b9c296f231e1912bf8dde2aa00ca45934c9d | d4eba5f106db3e4231c2ce25d12082e9b517c16f | refs/heads/master | 2021-01-18T10:06:35.977000 | 2016-02-03T04:50:32 | 2016-02-03T04:50:32 | 50,777,634 | 0 | 0 | null | true | 2016-01-31T14:11:31 | 2016-01-31T14:11:31 | 2016-01-28T03:19:50 | 2016-01-31T12:24:05 | 163 | 0 | 0 | 0 | null | null | null |
/*
Name : Erwin Yulizar F
NIM : 1301144031
Class: IF-38-01
*/
public class Driver{
public static void main(String[] args){
AppStore store = new AppStore();
store.createNewApp("app1",100);
store.createNewApp("app2",200);
store.createNewApp("app3",300);
store.createNewApp("app4",400);
System.out.println(store.toString());
System.out.println(store.getApp(2).toString());
SmartPhone phone1 = new SmartPhone();
phone1.setMemory(300);
System.out.println(phone1.toString());
phone1.addApplication(store,1);
System.out.println(phone1.toString());
phone1.addApplication(store,2);
System.out.println(phone1.toString());
phone1.addApplication(store,3);
System.out.println(phone1.toString());
}
}
| UTF-8 | Java | 745 | java | Driver.java | Java | [
{
"context": "\n/*\nName : Erwin Yulizar F\nNIM : 1301144031\nClass: IF-38-01\n*/\n\npublic clas",
"end": 26,
"score": 0.999871551990509,
"start": 11,
"tag": "NAME",
"value": "Erwin Yulizar F"
}
]
| null | []
|
/*
Name : <NAME>
NIM : 1301144031
Class: IF-38-01
*/
public class Driver{
public static void main(String[] args){
AppStore store = new AppStore();
store.createNewApp("app1",100);
store.createNewApp("app2",200);
store.createNewApp("app3",300);
store.createNewApp("app4",400);
System.out.println(store.toString());
System.out.println(store.getApp(2).toString());
SmartPhone phone1 = new SmartPhone();
phone1.setMemory(300);
System.out.println(phone1.toString());
phone1.addApplication(store,1);
System.out.println(phone1.toString());
phone1.addApplication(store,2);
System.out.println(phone1.toString());
phone1.addApplication(store,3);
System.out.println(phone1.toString());
}
}
| 736 | 0.695302 | 0.633557 | 33 | 21.545454 | 16.439219 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.151515 | false | false | 15 |
6ae6a3bd406eb7f5cdc40cae559b386cbdc19bec | 33,371,895,915,361 | 7d59f9a786fa0f053a21978555b6da91d6f8d3eb | /app/src/main/java/klecet/cn/sudhir/cnklecet/SplashScreen.java | 474df6ae0625f24a892afdb751547607454be469 | []
| no_license | sudhirbelagali/CNApplication | https://github.com/sudhirbelagali/CNApplication | 261ccb7da38686d68fd3abc02253f20b1e433a7b | 8eaa48e64705173dc8e6487379620e6defdd308b | refs/heads/master | 2021-04-18T19:22:19.585000 | 2018-03-26T11:47:17 | 2018-03-26T11:47:17 | 126,819,846 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package klecet.cn.sudhir.cnklecet;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;
public class SplashScreen extends AppCompatActivity {
//Splash screen timer
private static int SPLASH_TIME_OUT = 5000;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
progressBar = (ProgressBar) findViewById(R.id.progressbarsplashscreen);
Thread timerThread = new Thread() {
public void run() {
try {
sleep(SPLASH_TIME_OUT);
progressBar.setVisibility(View.VISIBLE);
//moveTaskToBack(true);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
} | UTF-8 | Java | 1,475 | java | SplashScreen.java | Java | []
| null | []
| package klecet.cn.sudhir.cnklecet;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;
public class SplashScreen extends AppCompatActivity {
//Splash screen timer
private static int SPLASH_TIME_OUT = 5000;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
progressBar = (ProgressBar) findViewById(R.id.progressbarsplashscreen);
Thread timerThread = new Thread() {
public void run() {
try {
sleep(SPLASH_TIME_OUT);
progressBar.setVisibility(View.VISIBLE);
//moveTaskToBack(true);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
} | 1,475 | 0.626441 | 0.622373 | 45 | 31.799999 | 20.50214 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 15 |
343060367fa814c672bc2410c749298ec97e6a44 | 15,616,501,148,582 | 95ed821b2d311a9155b477fcc1c3182dbcfd0642 | /UsersManager/src/main/java/com/springapp/mvc/service/UserServiceImpl.java | 5cf0f96a42fcaa808e019d35178adad8131d192c | []
| no_license | AlexandrPetkov/JavaRushTestTask | https://github.com/AlexandrPetkov/JavaRushTestTask | 0ca1860524adeafc473f1a08f54383664011a122 | 7802496ff715ad132e4c939e0a5f72306d562d1f | refs/heads/master | 2020-04-19T08:52:41.468000 | 2016-08-31T12:55:28 | 2016-08-31T12:55:28 | 66,908,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springapp.mvc.service;
import com.springapp.mvc.dao.UserDao;
import com.springapp.mvc.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Саша on 27.08.2016.
*/
@Service
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public void addUser(User user) {
userDao.addUser(user);
}
@Override
@Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
@Override
@Transactional
public void deleteUser(int id) {
userDao.deleteUser(id);
}
@Override
@Transactional
public User getUserById(int id) {
return userDao.getUserById(id);
}
@Override
@Transactional
public List<User> listUsers(String filter) {
return userDao.listUsers(filter);
}
@Override
@Transactional
public void fillUsers() {
userDao.fillUsers();
}
}
| UTF-8 | Java | 1,211 | java | UserServiceImpl.java | Java | [
{
"context": "l;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * Created by Саша on 27.08.2016.\r\n */\r\n\r\n@Service\r\npublic class Use",
"end": 280,
"score": 0.9996621012687683,
"start": 276,
"tag": "NAME",
"value": "Саша"
}
]
| null | []
| package com.springapp.mvc.service;
import com.springapp.mvc.dao.UserDao;
import com.springapp.mvc.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Саша on 27.08.2016.
*/
@Service
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public void addUser(User user) {
userDao.addUser(user);
}
@Override
@Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
@Override
@Transactional
public void deleteUser(int id) {
userDao.deleteUser(id);
}
@Override
@Transactional
public User getUserById(int id) {
return userDao.getUserById(id);
}
@Override
@Transactional
public List<User> listUsers(String filter) {
return userDao.listUsers(filter);
}
@Override
@Transactional
public void fillUsers() {
userDao.fillUsers();
}
}
| 1,211 | 0.637117 | 0.630489 | 58 | 18.810345 | 16.783054 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 15 |
21277c35978a92516cb894d177caf39ff933432e | 23,441,931,544,557 | 7e5c47c05b31c9264546ea6b82730fa83d7ad2f3 | /BidmWebReport1.0.2/src/main/java/com/boe/idm/project/controller/CfMoveMonthRptController.java | d38d667d261037dfe24d6622fae750cb3984eebb | []
| no_license | northcastle/AJavaWebProjectUseAngular | https://github.com/northcastle/AJavaWebProjectUseAngular | 109d7336114d06120b0189fd8ebecc42e1c41b1f | d97b8ad0c2de3fc7c64194c83ad33bf30d899459 | refs/heads/master | 2020-05-15T22:30:15.481000 | 2020-04-07T07:33:07 | 2020-04-07T07:33:07 | 182,522,371 | 0 | 1 | null | false | 2020-04-30T02:53:20 | 2019-04-21T11:03:26 | 2020-04-07T07:33:11 | 2020-04-30T02:53:18 | 143,504 | 0 | 1 | 1 | TypeScript | false | false | package com.boe.idm.project.controller;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.boe.idm.project.model.mybatis.CfMoveMonthRptVO;
import com.boe.idm.project.service.CfMoveMonthRptService;
@RestController
@RequestMapping("/api")
public class CfMoveMonthRptController {
@Autowired
private CfMoveMonthRptService service;
@RequestMapping(value = "/sc/cfreport/movemonth", method = RequestMethod.GET)
public List<CfMoveMonthRptVO> getData(HttpServletRequest request, HttpServletResponse response) throws Exception {
Calendar c = Calendar.getInstance();
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
return service.getData(date, hour);
}
@RequestMapping(value = "/sc/cfreport/movemonthQ", method = RequestMethod.GET)
public List<CfMoveMonthRptVO> queryData(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "datename", required = true) String datename) throws Exception {
return service.queryData(datename);
}
}
| UTF-8 | Java | 1,419 | java | CfMoveMonthRptController.java | Java | []
| null | []
| package com.boe.idm.project.controller;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.boe.idm.project.model.mybatis.CfMoveMonthRptVO;
import com.boe.idm.project.service.CfMoveMonthRptService;
@RestController
@RequestMapping("/api")
public class CfMoveMonthRptController {
@Autowired
private CfMoveMonthRptService service;
@RequestMapping(value = "/sc/cfreport/movemonth", method = RequestMethod.GET)
public List<CfMoveMonthRptVO> getData(HttpServletRequest request, HttpServletResponse response) throws Exception {
Calendar c = Calendar.getInstance();
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
return service.getData(date, hour);
}
@RequestMapping(value = "/sc/cfreport/movemonthQ", method = RequestMethod.GET)
public List<CfMoveMonthRptVO> queryData(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "datename", required = true) String datename) throws Exception {
return service.queryData(datename);
}
}
| 1,419 | 0.808316 | 0.808316 | 41 | 33.609756 | 31.232315 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.121951 | false | false | 1 |
194c55f8d29c2e8730bdef88df82d126629c6f46 | 6,038,724,048,404 | 516d432dd6f68f790f24452373924e09640967c0 | /src/main/java/com/janliao/leetcode/MergeTwoSortedLists.java | e93368d72e7688cebda9c812a55c1d6b7cc742a8 | []
| no_license | JanLiao/SELearn | https://github.com/JanLiao/SELearn | df18788d675f2e79b672a38f6ea93a06f17e76e9 | c24afa496fb741bc1678e2f41374138119a45efa | refs/heads/master | 2023-02-07T09:21:40.276000 | 2021-01-04T14:39:51 | 2021-01-04T14:39:51 | 326,157,100 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.janliao.leetcode;
public class MergeTwoSortedLists {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
n1.next = n2;n2.next = n3;n3.next = n4;
Node n5 = new Node(1);
Node n6 = new Node(3);
Node n7 = new Node(5);
Node n8 = new Node(7);
Node n9 = new Node(8);
Node n10 = new Node(10);
Node n11 = new Node(11);
Node n12 = new Node(12);
n5.next = n6;n6.next = n7;n7.next = n8;
n8.next = n9;n9.next = n10;n10.next = n11;
n11.next = n12;
Node res = new MergeTwoSortedLists().mergeTwoLists(n1, n5);
while(res != null){
System.out.println(res.value);
res = res.next;
}
}
public Node mergeTwoLists(Node l1, Node l2) {
// 哨兵节点
Node root = new Node();
Node pre = root;
while(l1 != null && l2 != null){
if(l1.value > l2.value){
root.next = l2;
l2 = l2.next;
} else {
root.next = l1;
l1 = l1.next;
}
root = root.next;
}
// while(l1 != null){
// root.next = l1;
// l1 = l1.next;
// root = root.next;
// }
if(l1 != null){
root.next = l1;
}
// while(l2 != null){
// root.next = l2;
// l2 = l2.next;
// root = root.next;
// }
if(l2 != null){
root.next = l2;
}
return pre.next;
}
}
| UTF-8 | Java | 1,671 | java | MergeTwoSortedLists.java | Java | []
| null | []
| package com.janliao.leetcode;
public class MergeTwoSortedLists {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
n1.next = n2;n2.next = n3;n3.next = n4;
Node n5 = new Node(1);
Node n6 = new Node(3);
Node n7 = new Node(5);
Node n8 = new Node(7);
Node n9 = new Node(8);
Node n10 = new Node(10);
Node n11 = new Node(11);
Node n12 = new Node(12);
n5.next = n6;n6.next = n7;n7.next = n8;
n8.next = n9;n9.next = n10;n10.next = n11;
n11.next = n12;
Node res = new MergeTwoSortedLists().mergeTwoLists(n1, n5);
while(res != null){
System.out.println(res.value);
res = res.next;
}
}
public Node mergeTwoLists(Node l1, Node l2) {
// 哨兵节点
Node root = new Node();
Node pre = root;
while(l1 != null && l2 != null){
if(l1.value > l2.value){
root.next = l2;
l2 = l2.next;
} else {
root.next = l1;
l1 = l1.next;
}
root = root.next;
}
// while(l1 != null){
// root.next = l1;
// l1 = l1.next;
// root = root.next;
// }
if(l1 != null){
root.next = l1;
}
// while(l2 != null){
// root.next = l2;
// l2 = l2.next;
// root = root.next;
// }
if(l2 != null){
root.next = l2;
}
return pre.next;
}
}
| 1,671 | 0.431149 | 0.382441 | 60 | 26.716667 | 12.811572 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 1 |
b12a1ef22c39757adcb23857448edb04370fa0f1 | 29,394,756,233,484 | b5e398dc064a9d13dca096bb55346851a0155be7 | /src/minhasseries/recomendados/RecomendacaoPorEmissora.java | 8af1c5a85feed92ce122b51d3a948b400e8a5398 | []
| no_license | lbltavares/Minhas-Series | https://github.com/lbltavares/Minhas-Series | 5f43eb8be5f7c283c5fa6534c0670ba7782874ab | 210a488b01f0d3c8b9b2312955506b3fec9805a7 | refs/heads/master | 2021-07-03T09:03:02.633000 | 2018-10-29T21:19:37 | 2018-10-29T21:19:37 | 155,282,702 | 0 | 0 | null | false | 2020-08-31T23:13:54 | 2018-10-29T21:18:21 | 2018-10-29T21:19:39 | 2020-08-31T23:13:15 | 890 | 0 | 0 | 1 | Java | false | false | package minhasseries.recomendados;
import java.util.HashMap;
import javax.swing.event.TableModelEvent;
import minhasseries.modelos.ModeloTabela;
import minhasseries.modelos.Serie;
public class RecomendacaoPorEmissora implements Algoritmo {
private HashMap<String, Integer> emissoras;
private ModeloTabela favoritos = ModeloTabela.getFavoritos();
private ModeloTabela principal = ModeloTabela.getPrincipal();
// Probabilidade de recomendar série de uma emissora que não está nos
// favoritos
private double probEmissoraNova = 0.1;
public RecomendacaoPorEmissora() {
emissoras = new HashMap<>();
ModeloTabela.getRecomendados().limpar();
}
private void update() {
emissoras.clear();
ModeloTabela.getRecomendados().limpar();
for (int i = 0; i < favoritos.getSeries().size(); i++) {
Serie serie = favoritos.getSerie(i);
String emissora = serie.getEmissora();
if (!emissoras.containsKey(emissora)) {
emissoras.put(emissora, 1);
} else {
emissoras.put(emissora, emissoras.get(emissora) + 1);
}
}
preencherRecomendados();
}
private void preencherRecomendados() {
for (int i = 0; i < principal.getSeries().size(); i++) {
Serie serie = principal.getSerie(i);
String emissora = serie.getEmissora();
if (favoritos.contemIgnoreCase(serie.getNome())) {
continue;
} else if (emissoras.containsKey(emissora)) {
double prob = ((emissoras.get(emissora) * 1.0) / (favoritos.getSeries().size() * 1.0));
double randomVal = Math.random();
if (randomVal <= prob) {
ModeloTabela.getRecomendados().addSerie(serie);
}
} else if (Math.random() < probEmissoraNova) {
ModeloTabela.getRecomendados().addSerie(serie);
}
}
}
@Override
public void favoritosModificado(TableModelEvent e) {
update();
}
@Override
public void principalModificado(TableModelEvent e) {
update();
}
@Override
public String getNome() {
return "Recomendação por Emissora";
}
}
| ISO-8859-1 | Java | 1,954 | java | RecomendacaoPorEmissora.java | Java | []
| null | []
| package minhasseries.recomendados;
import java.util.HashMap;
import javax.swing.event.TableModelEvent;
import minhasseries.modelos.ModeloTabela;
import minhasseries.modelos.Serie;
public class RecomendacaoPorEmissora implements Algoritmo {
private HashMap<String, Integer> emissoras;
private ModeloTabela favoritos = ModeloTabela.getFavoritos();
private ModeloTabela principal = ModeloTabela.getPrincipal();
// Probabilidade de recomendar série de uma emissora que não está nos
// favoritos
private double probEmissoraNova = 0.1;
public RecomendacaoPorEmissora() {
emissoras = new HashMap<>();
ModeloTabela.getRecomendados().limpar();
}
private void update() {
emissoras.clear();
ModeloTabela.getRecomendados().limpar();
for (int i = 0; i < favoritos.getSeries().size(); i++) {
Serie serie = favoritos.getSerie(i);
String emissora = serie.getEmissora();
if (!emissoras.containsKey(emissora)) {
emissoras.put(emissora, 1);
} else {
emissoras.put(emissora, emissoras.get(emissora) + 1);
}
}
preencherRecomendados();
}
private void preencherRecomendados() {
for (int i = 0; i < principal.getSeries().size(); i++) {
Serie serie = principal.getSerie(i);
String emissora = serie.getEmissora();
if (favoritos.contemIgnoreCase(serie.getNome())) {
continue;
} else if (emissoras.containsKey(emissora)) {
double prob = ((emissoras.get(emissora) * 1.0) / (favoritos.getSeries().size() * 1.0));
double randomVal = Math.random();
if (randomVal <= prob) {
ModeloTabela.getRecomendados().addSerie(serie);
}
} else if (Math.random() < probEmissoraNova) {
ModeloTabela.getRecomendados().addSerie(serie);
}
}
}
@Override
public void favoritosModificado(TableModelEvent e) {
update();
}
@Override
public void principalModificado(TableModelEvent e) {
update();
}
@Override
public String getNome() {
return "Recomendação por Emissora";
}
}
| 1,954 | 0.708569 | 0.703438 | 75 | 24.986666 | 22.788589 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 1 |
2afb2d055ff78aec75d42a3d6b75e6c1f0ed571a | 17,832,704,270,399 | fa132c8618ecdc102450e47173b9741d3eb205bf | /src/main/java/config/test.java | 0698d860395b7506ad1b9acd5d48d0b83ba7a69b | []
| no_license | ZLGG/gg | https://github.com/ZLGG/gg | 54b9d096a219bc8e51128ca4c8067107229c1da3 | 17d57ea15e1f1087d93626084aa9f99eef78d9d9 | refs/heads/master | 2020-04-27T17:28:36.758000 | 2019-03-08T10:48:15 | 2019-03-08T10:48:15 | 174,521,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package config;
import dao.UserMapper;
import entity.User;
import entity.UserExample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.SQLException;
import java.util.List;
/**
* @Description 测试IOC
* @Author LaiYu
* @Date 2018/10/28 4:15
*/
public class test {
public static void main(String[] args) throws SQLException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GlobalConfig.class);
for(String s: context.getBeanDefinitionNames()){
System.out.println(s);
}
}
}
| UTF-8 | Java | 667 | java | test.java | Java | [
{
"context": "a.util.List;\n\n/**\n * @Description 测试IOC\n * @Author LaiYu\n * @Date 2018/10/28 4:15\n */\npublic class test {\n",
"end": 325,
"score": 0.9991777539253235,
"start": 320,
"tag": "NAME",
"value": "LaiYu"
}
]
| null | []
| package config;
import dao.UserMapper;
import entity.User;
import entity.UserExample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.SQLException;
import java.util.List;
/**
* @Description 测试IOC
* @Author LaiYu
* @Date 2018/10/28 4:15
*/
public class test {
public static void main(String[] args) throws SQLException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GlobalConfig.class);
for(String s: context.getBeanDefinitionNames()){
System.out.println(s);
}
}
}
| 667 | 0.74359 | 0.726999 | 25 | 25.52 | 26.582882 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 1 |
2ed831cd120179e314b6ae4211bd652bd637b786 | 6,871,947,726,220 | 21f4434fefa95d20297e2cd4ca83d616da240363 | /OneDrive/Documentos/NetBeansProjects/PhoneNumberToWordsFinder/src/main/java/com/mycompany/phonenumbertowordsfinder/PhoneNumberToWordsFinder.java | 8c84960841e11135b595f3e69d5bea4c3a3246d6 | []
| no_license | kbeck410/Kashif-Beckford | https://github.com/kbeck410/Kashif-Beckford | 6a4ada965711ac8fe0289d421c915d602a4b415f | d1136902ec6b4027735d9d31b6746870434729e4 | refs/heads/master | 2023-06-18T06:54:26.831000 | 2021-07-12T19:04:59 | 2021-07-12T19:04:59 | 350,854,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mycompany.phonenumbertowordsfinder;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Kashif Beckford
*/
public class PhoneNumberToWordsFinder {
int noofChar;
List<String> words;
public List<String> findWords(String phoneNumber) {
System.out.println("I will find the words, I promise " + phoneNumber);
noofChar = phoneNumber.length();
words = new ArrayList<>();
permutate("", phoneNumber);
return words;
}
public String findPhoneNumber(String phoneWord) {
String[] letters = phoneWord.split("");
String phoneNumber = "";
for (String letter: letters) {
if ("ABC".contains(letter)) phoneNumber += "2";
else if ("DEF".contains(letter)) phoneNumber += "3";
else if ("GHI".contains(letter)) phoneNumber += "4";
else if ("JKL".contains(letter)) phoneNumber += "5";
else if ("MNO".contains(letter)) phoneNumber += "6";
else if ("PQRS".contains(letter)) phoneNumber += "7";
else if ("TUV".contains(letter)) phoneNumber += "8";
else if ("WXYZ".contains(letter)) phoneNumber += "9";
else phoneNumber += letter;
}
return phoneNumber;
}
private void permutate(String prefix, String numStr) {
if (prefix.length() == noofChar) {
words.add(prefix);
}
if (numStr.equals("")) return;
int n = Character.getNumericValue(numStr.charAt(0));
String[] letters = getLettersFromNumber(n);
numStr = numStr.substring(1);
for (String letter: letters) {
permutate(prefix + letter, numStr);
}
}
private String[] getLettersFromNumber(int n) {
String[] num2strMap = {
"000", // 0
"111", // 1
"ABC", // 2
"DEF", // 3
"GHI", // 4
"JKL", // 5
"MNO", // 6
"PQRS", // 7
"TUV", // 8
"WXYZ", // 9
};
String[] letters = num2strMap[n].split("");
return letters;
}
}
| UTF-8 | Java | 2,183 | java | PhoneNumberToWordsFinder.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n *\n * @author Kashif Beckford\n */\npublic class PhoneNumberToWordsFinder {\n i",
"end": 134,
"score": 0.9998725056648254,
"start": 119,
"tag": "NAME",
"value": "Kashif Beckford"
}
]
| null | []
| package com.mycompany.phonenumbertowordsfinder;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author <NAME>
*/
public class PhoneNumberToWordsFinder {
int noofChar;
List<String> words;
public List<String> findWords(String phoneNumber) {
System.out.println("I will find the words, I promise " + phoneNumber);
noofChar = phoneNumber.length();
words = new ArrayList<>();
permutate("", phoneNumber);
return words;
}
public String findPhoneNumber(String phoneWord) {
String[] letters = phoneWord.split("");
String phoneNumber = "";
for (String letter: letters) {
if ("ABC".contains(letter)) phoneNumber += "2";
else if ("DEF".contains(letter)) phoneNumber += "3";
else if ("GHI".contains(letter)) phoneNumber += "4";
else if ("JKL".contains(letter)) phoneNumber += "5";
else if ("MNO".contains(letter)) phoneNumber += "6";
else if ("PQRS".contains(letter)) phoneNumber += "7";
else if ("TUV".contains(letter)) phoneNumber += "8";
else if ("WXYZ".contains(letter)) phoneNumber += "9";
else phoneNumber += letter;
}
return phoneNumber;
}
private void permutate(String prefix, String numStr) {
if (prefix.length() == noofChar) {
words.add(prefix);
}
if (numStr.equals("")) return;
int n = Character.getNumericValue(numStr.charAt(0));
String[] letters = getLettersFromNumber(n);
numStr = numStr.substring(1);
for (String letter: letters) {
permutate(prefix + letter, numStr);
}
}
private String[] getLettersFromNumber(int n) {
String[] num2strMap = {
"000", // 0
"111", // 1
"ABC", // 2
"DEF", // 3
"GHI", // 4
"JKL", // 5
"MNO", // 6
"PQRS", // 7
"TUV", // 8
"WXYZ", // 9
};
String[] letters = num2strMap[n].split("");
return letters;
}
}
| 2,174 | 0.521759 | 0.508933 | 71 | 29.746479 | 20.922203 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633803 | false | false | 1 |
2b3de92c75cb51f933bd8380fa81af9043696d4e | 29,300,266,950,535 | 88e8069dc53a4693dbf7ae2a50d136047f495a60 | /edaas-persistence/test/org/persistence/test/InvoiceTest.java | a58e1c0a475a1123181fbab51026ef64f64a4a29 | []
| no_license | rbuhler/SAP_CIRRUS | https://github.com/rbuhler/SAP_CIRRUS | a25f3de3b0f014e2c0c573dc2297a4c4cb5ae526 | 86865661117a5c55e38cb5049a68734e96ea2c4e | refs/heads/master | 2016-09-06T19:39:15.768000 | 2015-09-14T15:59:58 | 2015-09-14T15:59:58 | 42,458,183 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.persistence.test;
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.junit.BeforeClass;
import org.junit.Test;
import org.persistence.Invoice;
public class InvoiceTest {
private static final String PERSISTENCE_UNIT_NAME = "Invoice";
private EntityManagerFactory factory;
@BeforeClass
public void setUp() throws Exception {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Begin a new local transaction so that we can persist a new entity
em.getTransaction().begin();
// read the existing entries
Query q = em.createQuery("select m from Person m");
// Persons should be empty
// do we have entries?
boolean createNewEntries = (q.getResultList().size() == 0);
// No, so lets create new entries
if (createNewEntries) {
assertTrue(q.getResultList().size() == 0);
Invoice invoice = new Invoice();
invoice.setCountry("BR");
em.persist(invoice);
}
// Commit the transaction, which will cause the entity to
// be stored in the database
em.getTransaction().commit();
// It is always good practice to close the EntityManager so that
// resources are conserved.
em.close();
}
@Test
public void test() {
// now lets check the database and see if the created entries are there
// create a fresh, new EntityManager
EntityManager em = factory.createEntityManager();
// Perform a simple query for all the Message entities
Query q = em.createQuery("select i from Invoice i");
// We should have 40 Persons in the database
assertTrue(q.getResultList().size() == 1);
em.close();
}
}
| UTF-8 | Java | 1,940 | java | InvoiceTest.java | Java | []
| null | []
| package org.persistence.test;
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.junit.BeforeClass;
import org.junit.Test;
import org.persistence.Invoice;
public class InvoiceTest {
private static final String PERSISTENCE_UNIT_NAME = "Invoice";
private EntityManagerFactory factory;
@BeforeClass
public void setUp() throws Exception {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Begin a new local transaction so that we can persist a new entity
em.getTransaction().begin();
// read the existing entries
Query q = em.createQuery("select m from Person m");
// Persons should be empty
// do we have entries?
boolean createNewEntries = (q.getResultList().size() == 0);
// No, so lets create new entries
if (createNewEntries) {
assertTrue(q.getResultList().size() == 0);
Invoice invoice = new Invoice();
invoice.setCountry("BR");
em.persist(invoice);
}
// Commit the transaction, which will cause the entity to
// be stored in the database
em.getTransaction().commit();
// It is always good practice to close the EntityManager so that
// resources are conserved.
em.close();
}
@Test
public void test() {
// now lets check the database and see if the created entries are there
// create a fresh, new EntityManager
EntityManager em = factory.createEntityManager();
// Perform a simple query for all the Message entities
Query q = em.createQuery("select i from Invoice i");
// We should have 40 Persons in the database
assertTrue(q.getResultList().size() == 1);
em.close();
}
}
| 1,940 | 0.675258 | 0.67268 | 65 | 28.846153 | 22.927465 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.784615 | false | false | 1 |
3d77f6de7a7cc2df53ac39fada50328b2c88b866 | 27,178,553,097,788 | 5d9eccc11bfa011c349238552f86addf48bec974 | /containerize-step-by-step/web-app/src/main/java/daggerok/counter/Counter.java | 63b76e4ed7e67cb956c1bcba294a7bbbfd5be737 | []
| no_license | daggerok/kubernetes-examples | https://github.com/daggerok/kubernetes-examples | ec135ef0fd05c33357b2a4d694d34cf18db9a686 | a3576af53c4a88166feaadcdc2cc2f54ed7d96aa | refs/heads/master | 2022-04-09T12:33:46.200000 | 2020-03-22T18:06:29 | 2020-03-22T18:06:29 | 104,202,709 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package daggerok.counter;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import java.io.Serializable;
@Data
@RedisHash
@Accessors(chain = true)
public class Counter implements Serializable {
private static final long serialVersionUID = -2377353749298919423L;
@Id
String id;
Long total;
}
| UTF-8 | Java | 414 | java | Counter.java | Java | []
| null | []
| package daggerok.counter;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import java.io.Serializable;
@Data
@RedisHash
@Accessors(chain = true)
public class Counter implements Serializable {
private static final long serialVersionUID = -2377353749298919423L;
@Id
String id;
Long total;
}
| 414 | 0.794686 | 0.748792 | 21 | 18.714285 | 20.267597 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 1 |
be7d3d1a1d6a0801a32eb3290118b9b182c31d6a | 33,311,766,417,382 | 5acfbb03c7b2eede4ab3fc48b0cb9d4a5ebb7ff1 | /CountDownLatch/src/Model/Statements/NopStatement.java | d837accbf3deb712fa3799c2a8131fa3fb0640bc | []
| no_license | tudor-alexa99/MAP | https://github.com/tudor-alexa99/MAP | 867fed4a806864323bded68d43d8fa87ea24cd89 | 9435881c33ec9b421dd7693f2f2c05cb451b5f60 | refs/heads/master | 2021-05-24T08:54:35.709000 | 2020-04-06T11:51:17 | 2020-04-06T11:51:17 | 253,481,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Model.Statements;
import Model.ADT.MyIDictionary;
import Model.DataTypes.Type;
import Model.Exceptions.MyException;
import Model.ProgramState;
public class NopStatement implements IStatement {
@Override
public ProgramState execute(ProgramState state) throws MyException {
// return state;
return null;
}
@Override
public MyIDictionary<String, Type> typecheck(MyIDictionary<String, Type> typeEnv) throws MyException {
return typeEnv;
}
@Override
public String toString(){return "Nop statement() ";}
}
| UTF-8 | Java | 589 | java | NopStatement.java | Java | []
| null | []
| package Model.Statements;
import Model.ADT.MyIDictionary;
import Model.DataTypes.Type;
import Model.Exceptions.MyException;
import Model.ProgramState;
public class NopStatement implements IStatement {
@Override
public ProgramState execute(ProgramState state) throws MyException {
// return state;
return null;
}
@Override
public MyIDictionary<String, Type> typecheck(MyIDictionary<String, Type> typeEnv) throws MyException {
return typeEnv;
}
@Override
public String toString(){return "Nop statement() ";}
}
| 589 | 0.697793 | 0.697793 | 22 | 24.772728 | 25.949131 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
dbb03741ec21dd1d8c8674df4bb1e8532bcae03b | 20,907,900,848,129 | 1a880fd76a194fd263939ae813fe39b7045b96ec | /src/main/java/ioStream/ReadInputs.java | 5ab568f7aa7386a8788697aa33c2692d57e70354 | []
| no_license | lunqus/exercises | https://github.com/lunqus/exercises | 94c0787441036d88fc46755291d886e71264f048 | 3df2b2c2be84368463333b03c234f5e04a413edb | refs/heads/master | 2020-04-10T09:52:13.404000 | 2019-04-18T17:58:43 | 2019-04-18T17:58:43 | 160,943,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ioStream;
import java.io.IOException;
public class ReadInputs {
public static void main(String[] args) throws IOException {
byte data[] = new byte[11];
System.out.print("Enter some characters: ");
System.in.read(data);
System.out.print("You entered: ");
for (int i = 0; i < data.length; i++) {
System.out.print( (char) data[i]);
}
}
}
| UTF-8 | Java | 418 | java | ReadInputs.java | Java | []
| null | []
| package ioStream;
import java.io.IOException;
public class ReadInputs {
public static void main(String[] args) throws IOException {
byte data[] = new byte[11];
System.out.print("Enter some characters: ");
System.in.read(data);
System.out.print("You entered: ");
for (int i = 0; i < data.length; i++) {
System.out.print( (char) data[i]);
}
}
}
| 418 | 0.57177 | 0.564593 | 20 | 19.9 | 20.806009 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 1 |
b46b2f4c3ca73656ed90d7bfa501ea421dc97b51 | 20,907,900,847,440 | 14128ebf17d6e84d5cfd52f9d705384d3c252058 | /app/src/main/java/com/example/lab8kotlin/SecondActivity.java | fd4b6b23add9b3e3bd3b954d401be19c034d0443 | []
| no_license | Mikaella-25-02/SAD_8 | https://github.com/Mikaella-25-02/SAD_8 | 11d46bc185077d0e0204d8a5492beb7978dc350e | d4f2bb125b7d146e3753dbe5ed5311cff5ab3c4f | refs/heads/master | 2022-08-24T23:35:16.934000 | 2020-05-20T16:48:12 | 2020-05-20T16:48:12 | 265,553,163 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.lab8kotlin;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.PolyUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import ru.mirea.lab8.R;
public class SecondActivity extends AppCompatActivity {
private SupportMapFragment mapFragment;
private GoogleMap map;
private PlaceItem place1;
private PlaceItem place2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
place1 = intent.getParcelableExtra("place1");
place2 = intent.getParcelableExtra("place2");
createMapView();
String[] addresses = new String[2];
addresses[0] = place1.getAddress();
addresses[1] = place2.getAddress();
new GetCoordinates().execute(addresses);
}
private void createMapView() {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
try {
if (null == map) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
});
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
private class GetCoordinates extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... strings) {
String response = "";
try {
String[] address = strings;
HttpDataHandler http = new HttpDataHandler();
String url = String.format(
"https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&key=%s",
address[0], address[1], HttpDataHandler.KEY_API);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
JSONObject jsonObject = null;
String way = "";
try {
jsonObject = new JSONObject(s);
way = jsonObject.getJSONArray("routes")
.getJSONObject(0)
.getJSONObject("overview_polyline")
.getString("points");
} catch (JSONException e) {
e.printStackTrace();
}
List<LatLng> mPoints = PolyUtil.decode(way);
PolylineOptions line = new PolylineOptions();
line.width(4f).color(Color.BLACK);
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
for (int i = 0; i < mPoints.size(); i++) {
if (i == 0) {
MarkerOptions startMarkerOptions = new MarkerOptions()
.position(mPoints.get(i));
map.addMarker(startMarkerOptions).setTitle("Начало пути");
} else if (i == mPoints.size() - 1) {
MarkerOptions endMarkerOptions = new MarkerOptions()
.position(mPoints.get(i));
map.addMarker(endMarkerOptions).setTitle("Конец пути");
}
line.add(mPoints.get(i));
latLngBuilder.include(mPoints.get(i));
}
map.addPolyline(line);
try {
int size = getResources().getDisplayMetrics().widthPixels;
LatLngBounds latLngBounds = latLngBuilder.build();
CameraUpdate track = CameraUpdateFactory.newLatLngBounds(latLngBounds, size, size, 25);
map.moveCamera(track);
} catch (Exception e) {
Toast.makeText(SecondActivity.this,
"Not found",
Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
}
}
| UTF-8 | Java | 4,997 | java | SecondActivity.java | Java | []
| null | []
| package com.example.lab8kotlin;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.PolyUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import ru.mirea.lab8.R;
public class SecondActivity extends AppCompatActivity {
private SupportMapFragment mapFragment;
private GoogleMap map;
private PlaceItem place1;
private PlaceItem place2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
place1 = intent.getParcelableExtra("place1");
place2 = intent.getParcelableExtra("place2");
createMapView();
String[] addresses = new String[2];
addresses[0] = place1.getAddress();
addresses[1] = place2.getAddress();
new GetCoordinates().execute(addresses);
}
private void createMapView() {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
try {
if (null == map) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
});
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
private class GetCoordinates extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... strings) {
String response = "";
try {
String[] address = strings;
HttpDataHandler http = new HttpDataHandler();
String url = String.format(
"https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&key=%s",
address[0], address[1], HttpDataHandler.KEY_API);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
JSONObject jsonObject = null;
String way = "";
try {
jsonObject = new JSONObject(s);
way = jsonObject.getJSONArray("routes")
.getJSONObject(0)
.getJSONObject("overview_polyline")
.getString("points");
} catch (JSONException e) {
e.printStackTrace();
}
List<LatLng> mPoints = PolyUtil.decode(way);
PolylineOptions line = new PolylineOptions();
line.width(4f).color(Color.BLACK);
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
for (int i = 0; i < mPoints.size(); i++) {
if (i == 0) {
MarkerOptions startMarkerOptions = new MarkerOptions()
.position(mPoints.get(i));
map.addMarker(startMarkerOptions).setTitle("Начало пути");
} else if (i == mPoints.size() - 1) {
MarkerOptions endMarkerOptions = new MarkerOptions()
.position(mPoints.get(i));
map.addMarker(endMarkerOptions).setTitle("Конец пути");
}
line.add(mPoints.get(i));
latLngBuilder.include(mPoints.get(i));
}
map.addPolyline(line);
try {
int size = getResources().getDisplayMetrics().widthPixels;
LatLngBounds latLngBounds = latLngBuilder.build();
CameraUpdate track = CameraUpdateFactory.newLatLngBounds(latLngBounds, size, size, 25);
map.moveCamera(track);
} catch (Exception e) {
Toast.makeText(SecondActivity.this,
"Not found",
Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
}
}
| 4,997 | 0.580956 | 0.576537 | 136 | 35.588234 | 23.548283 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610294 | false | false | 1 |
93c2bd050e6c0ff4c519489956d24691268e90eb | 31,799,937,919,187 | c6ba1c7e9253edb457549af90508f2c421622f41 | /src/main/java/com/baizhi/service/HomeService.java | d44e275a52f060d4a4ac6d17bda16c7a3f03b780 | []
| no_license | zhangzheyu0010/education | https://github.com/zhangzheyu0010/education | 3ab7805a457f23b55e546a945dda4ad0743e5f7a | f1d506292478b8748dd04f19ca1e14b06e699cca | refs/heads/master | 2023-08-03T14:29:03.912000 | 2021-09-22T02:05:01 | 2021-09-22T02:05:01 | 409,035,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.baizhi.service;
import com.baizhi.entity.Home;
import java.util.List;
public interface HomeService {
List<Home> queryAllHome(Integer page,Integer rows);
Long queryHomeTotal();
void updateService(Home home);
Home queryOneService(Integer id);
}
| UTF-8 | Java | 275 | java | HomeService.java | Java | []
| null | []
| package com.baizhi.service;
import com.baizhi.entity.Home;
import java.util.List;
public interface HomeService {
List<Home> queryAllHome(Integer page,Integer rows);
Long queryHomeTotal();
void updateService(Home home);
Home queryOneService(Integer id);
}
| 275 | 0.745455 | 0.745455 | 13 | 20.153847 | 17.452557 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 1 |
06188c266e6d8263cc315b18c3d85276f355b96c | 14,723,147,952,582 | 5dd3e1c900157b1848d45237dac69cba8cbdf081 | /CrossNgMain/src/main/java/com/neccton/api/dto/PersonDTO.java | c6ec250d9a67721aa1882bcb4fa9121f7b94a414 | []
| no_license | ebs-software/CrossNgSQLPrototype | https://github.com/ebs-software/CrossNgSQLPrototype | 27df603ef43a675d9a1e0dec4acd57852e25b159 | 566b5a434dae8b2f6cf3ffc62e9d9e32f5c93919 | refs/heads/master | 2016-09-10T19:48:34.350000 | 2015-05-11T14:24:50 | 2015-05-11T14:24:50 | 35,140,346 | 0 | 1 | null | false | 2015-05-07T07:13:42 | 2015-05-06T05:02:20 | 2015-05-06T05:09:42 | 2015-05-07T07:13:42 | 0 | 0 | 1 | 0 | JavaScript | null | null | package com.neccton.api.dto;
import java.util.Date;
/**
* Created by gla on 06.05.2015.
*/
public class PersonDTO extends BusinessPartnerDTO
{
private String firstName;
private Date dateOfBirth;
public PersonDTO()
{
}
public PersonDTO(String firstName, String lastName, Date dateOfBirth)
{
super(lastName);
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(final String firstName)
{
this.firstName = firstName;
}
public Date getDateOfBirth()
{
return dateOfBirth;
}
public void setDateOfBirth(final Date dateOfBirth)
{
this.dateOfBirth = dateOfBirth;
}
}
| UTF-8 | Java | 790 | java | PersonDTO.java | Java | [
{
"context": "pi.dto;\n\nimport java.util.Date;\n\n/**\n * Created by gla on 06.05.2015.\n */\npublic class PersonDTO extends",
"end": 75,
"score": 0.9992748498916626,
"start": 72,
"tag": "USERNAME",
"value": "gla"
},
{
"context": "\n super(lastName);\n this.firstName = firstName;\n this.dateOfBirth = dateOfBirth;\n }\n\n ",
"end": 384,
"score": 0.974235475063324,
"start": 375,
"tag": "NAME",
"value": "firstName"
}
]
| null | []
| package com.neccton.api.dto;
import java.util.Date;
/**
* Created by gla on 06.05.2015.
*/
public class PersonDTO extends BusinessPartnerDTO
{
private String firstName;
private Date dateOfBirth;
public PersonDTO()
{
}
public PersonDTO(String firstName, String lastName, Date dateOfBirth)
{
super(lastName);
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(final String firstName)
{
this.firstName = firstName;
}
public Date getDateOfBirth()
{
return dateOfBirth;
}
public void setDateOfBirth(final Date dateOfBirth)
{
this.dateOfBirth = dateOfBirth;
}
}
| 790 | 0.634177 | 0.624051 | 44 | 16.954546 | 18.432869 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false | 1 |
ad7c3cd0989efa97f9cdf5512ef7f7bf2a522a9a | 28,793,460,802,784 | 2240a54f0b2c2212524e951d147254918a987579 | /Day89_Elasticsearch/elasticsearch_client/src/main/java/com/itheima/A10_QueryByPage.java | f9f544f1e78b2bf92c70e6867d265e0fc104ec11 | []
| no_license | niyueyeee/MyCode | https://github.com/niyueyeee/MyCode | 2d2aa61cb872f4ccd48b447d41383359639c2465 | 68cc2a2abe40dfe4372de0adbddd7fd50f6c5bc2 | refs/heads/master | 2022-12-22T06:13:14.343000 | 2019-07-12T04:15:50 | 2019-07-12T04:15:50 | 167,680,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itheima;
import com.itheima.utils.TransportClients;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import java.net.UnknownHostException;
/**
* @author NiYueYeee
* @create 2019-06-09 12:23
*/
public class A10_QueryByPage {
public static void main(String[] args) throws UnknownHostException {
//1、获取客户端
TransportClient client = TransportClients.getClient();
//2、请求对象:查询请求。设置查询方式,设置类型
SearchRequestBuilder request = client.prepareSearch("a");
request.setQuery(QueryBuilders.matchAllQuery());
request.setTypes("article");
request.setFrom(0);//其实页
request.setSize(20);//每页显示多少条
//3、发送请求,获取响应底线
TransportClients.toConsuleResultHits(request.get());
//4、关闭客户端,释放资源
client.close();
}
}
| UTF-8 | Java | 1,046 | java | A10_QueryByPage.java | Java | [
{
"context": "ort java.net.UnknownHostException;\n\n/**\n * @author NiYueYeee\n * @create 2019-06-09 12:23\n */\npublic class A10_",
"end": 301,
"score": 0.9980366826057434,
"start": 292,
"tag": "NAME",
"value": "NiYueYeee"
}
]
| null | []
| package com.itheima;
import com.itheima.utils.TransportClients;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import java.net.UnknownHostException;
/**
* @author NiYueYeee
* @create 2019-06-09 12:23
*/
public class A10_QueryByPage {
public static void main(String[] args) throws UnknownHostException {
//1、获取客户端
TransportClient client = TransportClients.getClient();
//2、请求对象:查询请求。设置查询方式,设置类型
SearchRequestBuilder request = client.prepareSearch("a");
request.setQuery(QueryBuilders.matchAllQuery());
request.setTypes("article");
request.setFrom(0);//其实页
request.setSize(20);//每页显示多少条
//3、发送请求,获取响应底线
TransportClients.toConsuleResultHits(request.get());
//4、关闭客户端,释放资源
client.close();
}
}
| 1,046 | 0.704545 | 0.681818 | 29 | 30.862068 | 22.08717 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false | 1 |
dbb16ffa8b032117002c7aaedc5e2958d76726e0 | 12,859,132,097,442 | 18d1e0a34d8dcdfa9ee1821ab63b8b756df40e17 | /src/main/java/com/kpt/utils/reportes/service/style/StyleReportePdf.java | 7084baccbf7687ea96e4a2d788e9488ec0310fb0 | []
| no_license | Luisangelperezherrera/MTS-EQUIPO-MED | https://github.com/Luisangelperezherrera/MTS-EQUIPO-MED | 3a8df80263c80b9a28d32c95d30fd5c62a5ea710 | d4fc1ce61e3f504c0feb7f571181daeade72654c | refs/heads/master | 2016-08-12T18:08:03.476000 | 2016-04-07T17:33:18 | 2016-04-07T17:33:18 | 55,714,099 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kpt.utils.reportes.service.style;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
public class StyleReportePdf {
private static final BaseColor COLOR_BLACK=new BaseColor(0,0,0);
private static final BaseColor COLOR_WHITE=new BaseColor(255,255,255);
private static final BaseColor COLOR_GREY_50_PERCENT=new BaseColor(100,103,99);
private static final BaseColor COLOR_BLUE_50=new BaseColor(67,36,104);
private static final BaseColor COLOR_VIOLET=new BaseColor(120,36,107);
private static final String BASE_FONT = "arial";
private static final Font TITLE_HEADER = FontFactory.getFont(BASE_FONT,14,Font.BOLD,COLOR_VIOLET);
private static final Font TITLE_REPORTE_HEADER = FontFactory.getFont(BASE_FONT,14,Font.NORMAL,COLOR_BLUE_50);
private static final Font LABEL_HEADER = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_BLUE_50);
private static final Font VALUE_HEADER = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_GREY_50_PERCENT);
private static final Font VALUE_BODY_ODD= FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_BLUE_50);
private static final Font VALUE_BODY_PAIR = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_GREY_50_PERCENT);
public static void rowCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.NO_BORDER);
cell.setBorderWidth(0);
// height
}
public static void headerCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderWidth(1f);
// height
}
public static void headerPeriodoLabelCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
// height
}
public static void headerPeriodoValueCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderColorTop(COLOR_BLACK);
// height
}
public static void headerNoDatoCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthBottom(1f);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerNoDatoPeriodoCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorderWidthBottom(1f);
cell.setBorderColorBottom(COLOR_BLACK);
// height
}
public static void headerNoDatoPeriodoLeftCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthBottom(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerNoDatoTopCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.RIGHT);
cell.setBorder(Rectangle.TOP);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerTitlesEmpCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.LEFT);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthTop(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerTitlesRepCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.LEFT);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthBottom(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerBodyCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.LEFT);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthBottom(1f);
cell.setBackgroundColor(COLOR_WHITE);
}
public static void headerLastBodyCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderWidthRight(1f);
cell.setBackgroundColor(COLOR_WHITE);
}
public static void titlePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, TITLE_HEADER));
}
public static void titleReportePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, TITLE_REPORTE_HEADER));
}
public static void labelPhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, LABEL_HEADER));
}
public static void valuePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_HEADER));
}
public static void valuePhraseBodyOdd(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_BODY_ODD));
}
public static void valuePhraseBodyPair(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_BODY_PAIR));
}
}
| UTF-8 | Java | 7,095 | java | StyleReportePdf.java | Java | []
| null | []
| package com.kpt.utils.reportes.service.style;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
public class StyleReportePdf {
private static final BaseColor COLOR_BLACK=new BaseColor(0,0,0);
private static final BaseColor COLOR_WHITE=new BaseColor(255,255,255);
private static final BaseColor COLOR_GREY_50_PERCENT=new BaseColor(100,103,99);
private static final BaseColor COLOR_BLUE_50=new BaseColor(67,36,104);
private static final BaseColor COLOR_VIOLET=new BaseColor(120,36,107);
private static final String BASE_FONT = "arial";
private static final Font TITLE_HEADER = FontFactory.getFont(BASE_FONT,14,Font.BOLD,COLOR_VIOLET);
private static final Font TITLE_REPORTE_HEADER = FontFactory.getFont(BASE_FONT,14,Font.NORMAL,COLOR_BLUE_50);
private static final Font LABEL_HEADER = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_BLUE_50);
private static final Font VALUE_HEADER = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_GREY_50_PERCENT);
private static final Font VALUE_BODY_ODD= FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_BLUE_50);
private static final Font VALUE_BODY_PAIR = FontFactory.getFont(BASE_FONT,10,Font.NORMAL,COLOR_GREY_50_PERCENT);
public static void rowCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.NO_BORDER);
cell.setBorderWidth(0);
// height
}
public static void headerCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderWidth(1f);
// height
}
public static void headerPeriodoLabelCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
// height
}
public static void headerPeriodoValueCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderColorTop(COLOR_BLACK);
// height
}
public static void headerNoDatoCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthRight(1f);
cell.setBorderWidthBottom(1f);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerNoDatoPeriodoCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorderWidthBottom(1f);
cell.setBorderColorBottom(COLOR_BLACK);
// height
}
public static void headerNoDatoPeriodoLeftCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthBottom(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerNoDatoTopCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.RIGHT);
cell.setBorder(Rectangle.TOP);
cell.setBorderWidthRight(1f);
cell.setBorderWidthTop(1f);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerTitlesEmpCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.TOP);
cell.setBorder(Rectangle.LEFT);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthTop(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorTop(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerTitlesRepCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// border
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.LEFT);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthBottom(1f);
cell.setBorderWidthRight(1f);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderColorRight(COLOR_BLACK);
// height
}
public static void headerBodyCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.LEFT);
cell.setBorderColorLeft(COLOR_BLACK);
cell.setBorderColorBottom(COLOR_BLACK);
cell.setBorderWidthLeft(1f);
cell.setBorderWidthBottom(1f);
cell.setBackgroundColor(COLOR_WHITE);
}
public static void headerLastBodyCellStyle(PdfPCell cell) {
// alignment
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderColorRight(COLOR_BLACK);
cell.setBorderWidthRight(1f);
cell.setBackgroundColor(COLOR_WHITE);
}
public static void titlePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, TITLE_HEADER));
}
public static void titleReportePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, TITLE_REPORTE_HEADER));
}
public static void labelPhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, LABEL_HEADER));
}
public static void valuePhraseHeader(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_HEADER));
}
public static void valuePhraseBodyOdd(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_BODY_ODD));
}
public static void valuePhraseBodyPair(PdfPCell cell, String text) {
cell.setPhrase(new Paragraph(text, VALUE_BODY_PAIR));
}
}
| 7,095 | 0.769697 | 0.757858 | 238 | 28.810925 | 24.954117 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.159664 | false | false | 1 |
df4de469208a66b778ae93ee8dfb24ded4fe039c | 5,523,328,012,901 | 61a69ccad63b070a1d7095e4d8738b5f35a5693b | /ledgers-postings/ledgers-postings-repository/src/main/java/de/adorsys/ledgers/postings/db/domain/FinancialStmt.java | ffa5dcdbb42173196f6683ebdca6354cdce5ffb8 | [
"Apache-2.0"
]
| permissive | productinfo/ledgers | https://github.com/productinfo/ledgers | d0c9299a9db8d98ad74bbce8cd314e94e2c9916d | c8d820faa3e362ab81d19638b6679b880c7f34a3 | refs/heads/master | 2020-04-28T18:05:23.058000 | 2019-02-26T12:17:39 | 2019-02-26T12:17:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.adorsys.ledgers.postings.db.domain;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters.LocalDateTimeConverter;
import javax.persistence.*;
import java.time.LocalDateTime;
/**
* A financial statement will help draw time lines on ledgers and accounts.
* <p>
* A trial balance is also a financial statement on the balance sheet that is
* not closed.
* <p>
* You can continuously modify trial balances by adding posting and recomputing
* some balances.
* <p>
* No changes are allowed in a ledger when the ledger has closed with a
* financial statement.
*
* @author fpo
*/
@MappedSuperclass
public abstract class FinancialStmt {
/**
* The record id
*/
@Id
private String id;
/**
* The corresponding posting.
*/
@OneToOne
private Posting posting;
/**
* Documents the time of the posting.
*/
@Column(nullable = false, updatable = false)
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime pstTime;
@Enumerated(EnumType.STRING)
@Column(nullable = false, updatable = false)
private StmtStatus stmtStatus;
/**
* Identifier of the latest processed posting. We use this to
* perform batch processing. The latest posting process will allways be
* held here.
*/
@OneToOne
private PostingTrace latestPst;
/**
* The sequence number of the operation processed by this posting.
* <p>
* A single statement can be overridden many times as long as the enclosing
* ledger is not closed. These overriding happens synchronously. Each single one
* increasing the sequence number of the former posting.
*/
@Column(nullable = false, updatable = false)
private int stmtSeqNbr = 0;
public LocalDateTime getPstTime() {
return pstTime;
}
public int getStmtSeqNbr() {
return stmtSeqNbr;
}
public String getId() {
return id;
}
public StmtStatus getStmtStatus() {
return stmtStatus;
}
public void setId(String id) {
this.id = id;
}
public void setPstTime(LocalDateTime pstTime) {
this.pstTime = pstTime;
}
public void setStmtStatus(StmtStatus stmtStatus) {
this.stmtStatus = stmtStatus;
}
public void setStmtSeqNbr(int stmtSeqNbr) {
this.stmtSeqNbr = stmtSeqNbr;
}
public PostingTrace getLatestPst() {
return latestPst;
}
public void setLatestPst(PostingTrace latestPst) {
this.latestPst = latestPst;
}
public Posting getPosting() {
return posting;
}
public void setPosting(Posting posting) {
this.posting = posting;
}
}
| UTF-8 | Java | 2,724 | java | FinancialStmt.java | Java | [
{
"context": "losed with a\n * financial statement.\n *\n * @author fpo\n */\n@MappedSuperclass\npublic abstract class Finan",
"end": 612,
"score": 0.9996655583381653,
"start": 609,
"tag": "USERNAME",
"value": "fpo"
}
]
| null | []
| package de.adorsys.ledgers.postings.db.domain;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters.LocalDateTimeConverter;
import javax.persistence.*;
import java.time.LocalDateTime;
/**
* A financial statement will help draw time lines on ledgers and accounts.
* <p>
* A trial balance is also a financial statement on the balance sheet that is
* not closed.
* <p>
* You can continuously modify trial balances by adding posting and recomputing
* some balances.
* <p>
* No changes are allowed in a ledger when the ledger has closed with a
* financial statement.
*
* @author fpo
*/
@MappedSuperclass
public abstract class FinancialStmt {
/**
* The record id
*/
@Id
private String id;
/**
* The corresponding posting.
*/
@OneToOne
private Posting posting;
/**
* Documents the time of the posting.
*/
@Column(nullable = false, updatable = false)
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime pstTime;
@Enumerated(EnumType.STRING)
@Column(nullable = false, updatable = false)
private StmtStatus stmtStatus;
/**
* Identifier of the latest processed posting. We use this to
* perform batch processing. The latest posting process will allways be
* held here.
*/
@OneToOne
private PostingTrace latestPst;
/**
* The sequence number of the operation processed by this posting.
* <p>
* A single statement can be overridden many times as long as the enclosing
* ledger is not closed. These overriding happens synchronously. Each single one
* increasing the sequence number of the former posting.
*/
@Column(nullable = false, updatable = false)
private int stmtSeqNbr = 0;
public LocalDateTime getPstTime() {
return pstTime;
}
public int getStmtSeqNbr() {
return stmtSeqNbr;
}
public String getId() {
return id;
}
public StmtStatus getStmtStatus() {
return stmtStatus;
}
public void setId(String id) {
this.id = id;
}
public void setPstTime(LocalDateTime pstTime) {
this.pstTime = pstTime;
}
public void setStmtStatus(StmtStatus stmtStatus) {
this.stmtStatus = stmtStatus;
}
public void setStmtSeqNbr(int stmtSeqNbr) {
this.stmtSeqNbr = stmtSeqNbr;
}
public PostingTrace getLatestPst() {
return latestPst;
}
public void setLatestPst(PostingTrace latestPst) {
this.latestPst = latestPst;
}
public Posting getPosting() {
return posting;
}
public void setPosting(Posting posting) {
this.posting = posting;
}
}
| 2,724 | 0.661894 | 0.660426 | 114 | 22.894737 | 23.525785 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.219298 | false | false | 1 |
dfd6ada0625d89e7c3209ea5e0b54a74f9e1b602 | 33,139,967,711,834 | 3d0e9149d2292f803330203a51482b6c28e169a4 | /Mohit's WebDriver Framework/Page Object Framework/src/com/ironmountain/pageobject/pageobjectrunner/framework/SeleniumUITest.java | 246a0f3ff0f3b4a3f757eb30eb8b5fb62b8ad09d | []
| no_license | sundeep-gupta/codebase | https://github.com/sundeep-gupta/codebase | ae8543541a22fb08d08c41514ae51b86c0e7edf2 | e2c8cc2181e26ba509818733dd463789c964e6c4 | refs/heads/master | 2021-08-16T02:58:18.875000 | 2017-11-18T21:12:08 | 2017-11-18T21:12:08 | 111,229,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ironmountain.pageobject.pageobjectrunner.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface SeleniumUITest {
/**
* This represents the class or method priority
*
* @return
*/
int priority() default 100;
String HPQCID() default "No ID Found";
String[] defectIds() default "No Defects Associated";
boolean skipAllTestsIfFail() default false;
boolean resetSkipAllTestsIfFail() default false;
}
| UTF-8 | Java | 646 | java | SeleniumUITest.java | Java | []
| null | []
| package com.ironmountain.pageobject.pageobjectrunner.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface SeleniumUITest {
/**
* This represents the class or method priority
*
* @return
*/
int priority() default 100;
String HPQCID() default "No ID Found";
String[] defectIds() default "No Defects Associated";
boolean skipAllTestsIfFail() default false;
boolean resetSkipAllTestsIfFail() default false;
}
| 646 | 0.781734 | 0.77709 | 22 | 28.363636 | 20.44626 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.045455 | false | false | 1 |
50cda473d20d43c9f52f179417e18529ba7ef240 | 5,961,414,674,183 | e1d571471f64c16e40f2885e2f1bbf3fd2c9a37a | /src/EPAM_LECTURE_14/Car.java | 999b34b02937abed65b596af5a6ec1603361ce58 | []
| no_license | mishadra4/EPAM_TASKS | https://github.com/mishadra4/EPAM_TASKS | a4dcb2c9b728664880134a9161851a9903f6991d | 93910791b6036829fa98a921aeef0b248524b6bb | refs/heads/master | 2021-05-06T04:26:10.787000 | 2018-03-07T20:07:52 | 2018-03-07T20:07:52 | 114,935,689 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package EPAM_LECTURE_14;
class Car {
public enum Status { DRY, FOAMED, WASHED }
private Status status = Status.DRY;
private final int id;
public Car(int idn) { id = idn; }
public void foam() { status = Status.FOAMED; }
public void wash() { status = Status.WASHED; }
public Status getStatus() { return status; }
public int getId() { return id; }
public String toString() {
return "Car " + id + ": " + status;
}
}
| UTF-8 | Java | 462 | java | Car.java | Java | []
| null | []
| package EPAM_LECTURE_14;
class Car {
public enum Status { DRY, FOAMED, WASHED }
private Status status = Status.DRY;
private final int id;
public Car(int idn) { id = idn; }
public void foam() { status = Status.FOAMED; }
public void wash() { status = Status.WASHED; }
public Status getStatus() { return status; }
public int getId() { return id; }
public String toString() {
return "Car " + id + ": " + status;
}
}
| 462 | 0.606061 | 0.601732 | 16 | 27.875 | 18.27524 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 1 |
7109a684acacca3f7d8e30d67b629b0ee940660b | 8,933,532,039,566 | b3b76f7ba4f5705f6ce9ff802a714bf3e646a047 | /spring-boot-learning/src/main/java/com/wangwenjun/concurrency/video/phase1/chapter12/GoupDemo.java | deca0136a82b4e73e3db02a6be39918f115fa079 | [
"Apache-2.0"
]
| permissive | liubo404/sb205 | https://github.com/liubo404/sb205 | 4deb6f912a75e0a3e4efbee77d609c21d18fa6c3 | e4246568fa0aca9c4f14a5f2f80410df3f0a116e | refs/heads/master | 2023-01-08T17:05:46.387000 | 2020-07-10T07:17:12 | 2020-07-10T07:17:12 | 249,325,228 | 0 | 0 | Apache-2.0 | false | 2022-12-27T14:52:46 | 2020-03-23T03:17:12 | 2020-07-10T07:17:48 | 2022-12-27T14:52:43 | 5,550 | 0 | 0 | 41 | Java | false | false | package com.wangwenjun.concurrency.video.phase1.chapter12;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* sleep 不会放弃CPU的执行权,不会block住
*/
@Slf4j
public class GoupDemo {
public static void main(String[] args) {
log.info("{}", Thread.currentThread().getName());
log.info("{}", Thread.currentThread().getThreadGroup());
//1. use name
ThreadGroup tg1 = new ThreadGroup("TG1");
Thread t1 = new Thread(tg1, "t1") {
@Override
public void run() {
while (true) {
try {
log.info("t1.group={},parent={}", getThreadGroup().getName(),getThreadGroup().getParent());
log.info(" parent.parent={}", getThreadGroup().getParent().activeCount());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.start();
ThreadGroup tg2 = new ThreadGroup(tg1,"TG2");
log.info("tg2.group={},parent={}", tg2.getName() ,tg2.getParent() );
}
}
| UTF-8 | Java | 998 | java | GoupDemo.java | Java | []
| null | []
| package com.wangwenjun.concurrency.video.phase1.chapter12;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* sleep 不会放弃CPU的执行权,不会block住
*/
@Slf4j
public class GoupDemo {
public static void main(String[] args) {
log.info("{}", Thread.currentThread().getName());
log.info("{}", Thread.currentThread().getThreadGroup());
//1. use name
ThreadGroup tg1 = new ThreadGroup("TG1");
Thread t1 = new Thread(tg1, "t1") {
@Override
public void run() {
while (true) {
try {
log.info("t1.group={},parent={}", getThreadGroup().getName(),getThreadGroup().getParent());
log.info(" parent.parent={}", getThreadGroup().getParent().activeCount());
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.start();
ThreadGroup tg2 = new ThreadGroup(tg1,"TG2");
log.info("tg2.group={},parent={}", tg2.getName() ,tg2.getParent() );
}
}
| 998 | 0.63655 | 0.61499 | 48 | 19.291666 | 24.191044 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.104167 | false | false | 1 |
147a8d4dfdab5ed46f768b43d8bade148d64179f | 26,242,250,188,354 | b9451c54b2ff7ddb797afc029672c57181a79bf9 | /server/rest/src/main/java/org/infinispan/rest/RestResponseException.java | 568cbadbc10e3eeb9136afd7ae1d46ed97d71ff5 | [
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
]
| permissive | infinispan/infinispan | https://github.com/infinispan/infinispan | 4c16a7f7381894e1c38c80e39cc9346b566407ad | 1babc3340f2cf9bd42c84102a42c901d20feaa84 | refs/heads/main | 2023-08-31T19:46:06.326000 | 2023-06-20T08:14:50 | 2023-08-31T17:54:31 | 1,050,944 | 920 | 527 | Apache-2.0 | false | 2023-09-14T21:00:45 | 2010-11-04T12:33:19 | 2023-09-13T11:30:16 | 2023-09-14T21:00:44 | 145,284 | 1,077 | 595 | 22 | Java | false | false | package org.infinispan.rest;
import org.infinispan.commons.util.Util;
import io.netty.handler.codec.http.HttpResponseStatus;
/**
* An exception representing non-critical HTTP processing errors which will be translated
* into {@link org.infinispan.rest.framework.RestResponse} and sent back to the client.
*
* <p>
* {@link RestRequestHandler} and {@link RestRequestHandler} are responsible for catching subtypes of this
* exception and translate them into proper Netty responses.
* </p>
*/
public class RestResponseException extends RuntimeException {
private final HttpResponseStatus status;
private final String text;
/**
* Creates new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param text Text returned to the client.
*/
public RestResponseException(HttpResponseStatus status, String text) {
this.status = status;
this.text = text;
}
/**
* Creates a new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param text Text returned to the client.
* @param t Throwable instance.
*/
public RestResponseException(HttpResponseStatus status, String text, Throwable t) {
super(t);
this.status = status;
this.text = text;
}
/**
* Creates a new {@link RestResponseException} whose status is 500.
*
* @param t Throwable instance.
*/
public RestResponseException(Throwable t) {
this(HttpResponseStatus.INTERNAL_SERVER_ERROR, Util.getRootCause(t));
}
/**
* Creates a new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param t Throwable instance.
*/
public RestResponseException(HttpResponseStatus status, Throwable t) {
this(status, t.getMessage(), t);
}
public HttpResponseStatus getStatus() {
return status;
}
public String getText() {
return text;
}
}
| UTF-8 | Java | 1,979 | java | RestResponseException.java | Java | []
| null | []
| package org.infinispan.rest;
import org.infinispan.commons.util.Util;
import io.netty.handler.codec.http.HttpResponseStatus;
/**
* An exception representing non-critical HTTP processing errors which will be translated
* into {@link org.infinispan.rest.framework.RestResponse} and sent back to the client.
*
* <p>
* {@link RestRequestHandler} and {@link RestRequestHandler} are responsible for catching subtypes of this
* exception and translate them into proper Netty responses.
* </p>
*/
public class RestResponseException extends RuntimeException {
private final HttpResponseStatus status;
private final String text;
/**
* Creates new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param text Text returned to the client.
*/
public RestResponseException(HttpResponseStatus status, String text) {
this.status = status;
this.text = text;
}
/**
* Creates a new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param text Text returned to the client.
* @param t Throwable instance.
*/
public RestResponseException(HttpResponseStatus status, String text, Throwable t) {
super(t);
this.status = status;
this.text = text;
}
/**
* Creates a new {@link RestResponseException} whose status is 500.
*
* @param t Throwable instance.
*/
public RestResponseException(Throwable t) {
this(HttpResponseStatus.INTERNAL_SERVER_ERROR, Util.getRootCause(t));
}
/**
* Creates a new {@link RestResponseException}.
*
* @param status Status code returned to the client.
* @param t Throwable instance.
*/
public RestResponseException(HttpResponseStatus status, Throwable t) {
this(status, t.getMessage(), t);
}
public HttpResponseStatus getStatus() {
return status;
}
public String getText() {
return text;
}
}
| 1,979 | 0.685195 | 0.683679 | 71 | 26.87324 | 27.731068 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295775 | false | false | 1 |
529fc161e33c5d78d69954180db2ff3ab35f503b | 26,242,250,189,517 | 7b144f74bc76c6739b97f01cfe36f9fe1a0d5f9c | /balenced.java | 79e079bf5fbf41a8c60053152cf008bbda7ae63c | []
| no_license | gokulsankary/project1 | https://github.com/gokulsankary/project1 | 7a69656d5a32a1b3a438b151f2b8e2c11e9c2974 | a08ac7981e24f9d93888f893c8d96e6187fa4e14 | refs/heads/master | 2021-01-19T01:00:26.608000 | 2016-08-08T11:11:09 | 2016-08-08T11:11:09 | 63,868,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class balenced {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String a=s.nextLine();
String b[]=a.split(" ");
char c[]=new char[100];
for(int i=0;i<=b.length-1;i++){
c=b[i].toCharArray();int m=0,n=0;
for(int j=0;j<=c.length-1;j++){
if(c[j]>=65&&c[j]<=78||c[j]>=97&&c[j]<=110){
m++;
}else if(c[j]>=79&&c[j]<=91||c[j]>=111&&c[j]<=122){
n++;
}
}
if(m==n){
System.out.println(b[i]+" is balenced");
}else{
System.out.println(b[i]+" is not balenced");
}
}
}
}
| UTF-8 | Java | 541 | java | balenced.java | Java | []
| null | []
| import java.util.Scanner;
public class balenced {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String a=s.nextLine();
String b[]=a.split(" ");
char c[]=new char[100];
for(int i=0;i<=b.length-1;i++){
c=b[i].toCharArray();int m=0,n=0;
for(int j=0;j<=c.length-1;j++){
if(c[j]>=65&&c[j]<=78||c[j]>=97&&c[j]<=110){
m++;
}else if(c[j]>=79&&c[j]<=91||c[j]>=111&&c[j]<=122){
n++;
}
}
if(m==n){
System.out.println(b[i]+" is balenced");
}else{
System.out.println(b[i]+" is not balenced");
}
}
}
}
| 541 | 0.571164 | 0.519409 | 24 | 21.541666 | 16.573019 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false | 1 |
8d7f0c4517a74c1a092039e23bdecb85dc406b6d | 27,874,337,810,510 | c9bfb2608d424037e9854041bc1f89a36f3029e6 | /jelly-farm-service/src/test/java/org/meijer/jelly/jellyFarmService/integration/JellyDetailsControllerTest.java | 1bbdddd7cdf06099f2266af196b1f82b930fc583 | []
| no_license | Namiswami/Jelly-Farm | https://github.com/Namiswami/Jelly-Farm | 0bceeefccb4ff112fad0df298845f0ec75a5fd31 | 2e748788138c8da61af806bd7c592367b2623ec4 | refs/heads/master | 2022-08-05T08:18:48.219000 | 2020-06-03T10:15:40 | 2020-06-03T10:15:40 | 265,485,957 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.meijer.jelly.jellyFarmService.integration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.meijer.jelly.jellyFarmService.DataManager;
import org.meijer.jelly.jellyFarmService.JellyFarmServiceApplication;
import org.meijer.jelly.jellyFarmService.controller.JellyDetailsController;
import org.meijer.jelly.jellyFarmService.exception.GlobalExceptionHandler;
import org.meijer.jelly.jellyFarmService.model.jelly.entity.JellyEntity;
import org.meijer.jelly.jellyFarmService.repository.JellyStockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.UUID;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Color.*;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Gender.FEMALE;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Gender.MALE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@SpringBootTest(
classes = {JellyFarmServiceApplication.class},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@RunWith(SpringRunner.class)
@EmbeddedKafka(brokerProperties={"log.dir=./tmp/kafka/eventListenerTest", "port=9092", "listeners=PLAINTEXT://:9092"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class JellyDetailsControllerTest {
private MockMvc mockMvc;
@Autowired
private JellyDetailsController jellyDetailsController;
@Autowired
private JellyStockRepository jellyStockRepository;
@Autowired
private DataManager dataManager;
@Before
public void init() {
mockMvc = standaloneSetup(jellyDetailsController)
.setControllerAdvice(new GlobalExceptionHandler())
.build();
dataManager.cleanUp();
dataManager.createCage();
}
@Test
public void getAllJelliesReturnsAllJellies() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/stock"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilteredByColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(MALE, YELLOW);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilterByGenderAndColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(FEMALE, BLUE);
dataManager.saveNewJelly(MALE, RED);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString())
.param("gender", MALE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilteredByCageGenderAndColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(2L);
dataManager.saveNewJelly(MALE, RED);
dataManager.saveNewJelly(FEMALE, BLUE);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString())
.param("cageNumber", "1")
.param("gender", MALE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesExceptFreedJellies() throws Exception {
//given
dataManager.saveFreedJelly();
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/stock"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesGives400WhenInvalidParameterValues() throws Exception {
mockMvc.perform(get("/v1/details/stock")
.param("gender", "not-a-gender"))
.andExpect(status().isBadRequest());
}
@Test
public void getSingleJellyReturnsSingleJelly() throws Exception {
//given
JellyEntity jelly = dataManager.saveNewJelly(1L);
//when-then
mockMvc.perform(get("/v1/details/stock/" + jelly.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.color").value(BLUE.toString()))
.andExpect(jsonPath("$.cageNumber").value(1))
.andExpect(jsonPath("$.gender").value(MALE.toString()))
.andExpect(jsonPath("$.id").value(jelly.getId().toString()));
}
@Test
public void getSingleJellyReturns404WhenNotFound() throws Exception {
//when-then
mockMvc.perform(get("/v1/details/stock/" + UUID.randomUUID()))
.andExpect(status().isNotFound());
}
@Test
public void getCageOverviewGivesBackCageOverviewForSpecificCage() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage")
.param("cageNumber", "1"))
.andExpect(status().isOk())
.andDo(print())
.andExpect(jsonPath("$.cages.[0].cage.cageNumber").value(1))
.andExpect(jsonPath("$.cages.[0].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[0].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[0].jellyOverview.blue").value(3));
}
@Test
public void getCageOverviewGivesBackCageOverviewForAllCages() throws Exception {
//given
dataManager.createCage(2L);
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveThreeBlueMales(3, 2L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.cages.[0].cage.cageNumber").value(1))
.andExpect(jsonPath("$.cages.[0].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[0].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[0].jellyOverview.blue").value(3))
.andExpect(jsonPath("$.cages.[1].cage.cageNumber").value(2))
.andExpect(jsonPath("$.cages.[1].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[1].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[1].jellyOverview.blue").value(3));
}
public void getOverviewGivesBackCageOverviewForAllJellies() throws Exception {
//given
dataManager.createCage(2L);
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveThreeBlueMales(3, 2L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyOverview.total").value(6))
.andExpect(jsonPath("$.jellyOverview.blue").value(6));
}
}
| UTF-8 | Java | 10,405 | java | JellyDetailsControllerTest.java | Java | []
| null | []
| package org.meijer.jelly.jellyFarmService.integration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.meijer.jelly.jellyFarmService.DataManager;
import org.meijer.jelly.jellyFarmService.JellyFarmServiceApplication;
import org.meijer.jelly.jellyFarmService.controller.JellyDetailsController;
import org.meijer.jelly.jellyFarmService.exception.GlobalExceptionHandler;
import org.meijer.jelly.jellyFarmService.model.jelly.entity.JellyEntity;
import org.meijer.jelly.jellyFarmService.repository.JellyStockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.UUID;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Color.*;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Gender.FEMALE;
import static org.meijer.jelly.jellyFarmService.model.jelly.attributes.Gender.MALE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@SpringBootTest(
classes = {JellyFarmServiceApplication.class},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@RunWith(SpringRunner.class)
@EmbeddedKafka(brokerProperties={"log.dir=./tmp/kafka/eventListenerTest", "port=9092", "listeners=PLAINTEXT://:9092"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class JellyDetailsControllerTest {
private MockMvc mockMvc;
@Autowired
private JellyDetailsController jellyDetailsController;
@Autowired
private JellyStockRepository jellyStockRepository;
@Autowired
private DataManager dataManager;
@Before
public void init() {
mockMvc = standaloneSetup(jellyDetailsController)
.setControllerAdvice(new GlobalExceptionHandler())
.build();
dataManager.cleanUp();
dataManager.createCage();
}
@Test
public void getAllJelliesReturnsAllJellies() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/stock"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilteredByColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(MALE, YELLOW);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilterByGenderAndColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(FEMALE, BLUE);
dataManager.saveNewJelly(MALE, RED);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString())
.param("gender", MALE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesFilteredByCageGenderAndColor() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveNewJelly(2L);
dataManager.saveNewJelly(MALE, RED);
dataManager.saveNewJelly(FEMALE, BLUE);
//when-then
mockMvc.perform(get("/v1/details/stock")
.param("color", BLUE.toString())
.param("cageNumber", "1")
.param("gender", MALE.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesReturnsAllJelliesExceptFreedJellies() throws Exception {
//given
dataManager.saveFreedJelly();
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/stock"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyList", hasSize(3)))
.andExpect(jsonPath("$.jellyList.[*].color", containsInAnyOrder(BLUE.toString(), BLUE.toString(), BLUE.toString())))
.andExpect(jsonPath("$.jellyList.[*].cageNumber", containsInAnyOrder(1,1,1)))
.andExpect(jsonPath("$.jellyList.[*].gender", containsInAnyOrder(MALE.toString(), MALE.toString() ,MALE.toString())))
.andExpect(jsonPath("$.jellyList.[*].id", hasSize(3)));
}
@Test
public void getAllJelliesGives400WhenInvalidParameterValues() throws Exception {
mockMvc.perform(get("/v1/details/stock")
.param("gender", "not-a-gender"))
.andExpect(status().isBadRequest());
}
@Test
public void getSingleJellyReturnsSingleJelly() throws Exception {
//given
JellyEntity jelly = dataManager.saveNewJelly(1L);
//when-then
mockMvc.perform(get("/v1/details/stock/" + jelly.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.color").value(BLUE.toString()))
.andExpect(jsonPath("$.cageNumber").value(1))
.andExpect(jsonPath("$.gender").value(MALE.toString()))
.andExpect(jsonPath("$.id").value(jelly.getId().toString()));
}
@Test
public void getSingleJellyReturns404WhenNotFound() throws Exception {
//when-then
mockMvc.perform(get("/v1/details/stock/" + UUID.randomUUID()))
.andExpect(status().isNotFound());
}
@Test
public void getCageOverviewGivesBackCageOverviewForSpecificCage() throws Exception {
//given
dataManager.saveThreeBlueMales(3, 1L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage")
.param("cageNumber", "1"))
.andExpect(status().isOk())
.andDo(print())
.andExpect(jsonPath("$.cages.[0].cage.cageNumber").value(1))
.andExpect(jsonPath("$.cages.[0].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[0].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[0].jellyOverview.blue").value(3));
}
@Test
public void getCageOverviewGivesBackCageOverviewForAllCages() throws Exception {
//given
dataManager.createCage(2L);
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveThreeBlueMales(3, 2L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.cages.[0].cage.cageNumber").value(1))
.andExpect(jsonPath("$.cages.[0].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[0].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[0].jellyOverview.blue").value(3))
.andExpect(jsonPath("$.cages.[1].cage.cageNumber").value(2))
.andExpect(jsonPath("$.cages.[1].cage.habitatName").value("Tropical Forest"))
.andExpect(jsonPath("$.cages.[1].jellyOverview.total").value(3))
.andExpect(jsonPath("$.cages.[1].jellyOverview.blue").value(3));
}
public void getOverviewGivesBackCageOverviewForAllJellies() throws Exception {
//given
dataManager.createCage(2L);
dataManager.saveThreeBlueMales(3, 1L);
dataManager.saveThreeBlueMales(3, 2L);
//when-then
mockMvc.perform(get("/v1/details/overview/cage"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.jellyOverview.total").value(6))
.andExpect(jsonPath("$.jellyOverview.blue").value(6));
}
}
| 10,405 | 0.651418 | 0.641711 | 224 | 45.450893 | 34.953377 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651786 | false | false | 1 |
8ecf0e4aa8363116c3a04c25a714cc42cb796355 | 28,217,935,193,853 | 428dd9ad3055aaad12c8414374379fe79de803a5 | /src/org/helllabs/android/xmp/service/PlayerService.java | c2a1fc6e7a257cc3faa68f6c0eb74c00ba07c5c3 | []
| no_license | hoangtu23/xmp-android | https://github.com/hoangtu23/xmp-android | 37348623adb81a5dca5c7eb3ab30342832edb723 | bef4c0603d9dd404943df40942fe20d9a3a24976 | refs/heads/master | 2017-04-29T00:22:06.359000 | 2014-07-13T11:42:06 | 2014-07-13T11:42:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.helllabs.android.xmp.service;
import org.helllabs.android.xmp.Xmp;
import org.helllabs.android.xmp.preferences.Preferences;
import org.helllabs.android.xmp.service.receiver.HeadsetPlugReceiver;
import org.helllabs.android.xmp.service.receiver.NotificationActionReceiver;
import org.helllabs.android.xmp.service.receiver.RemoteControlReceiver;
import org.helllabs.android.xmp.util.InfoCache;
import org.helllabs.android.xmp.util.Log;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
public final class PlayerService extends Service {
private static final String TAG = "PlayerService";
private static final int CMD_NONE = 0;
private static final int CMD_NEXT = 1;
private static final int CMD_PREV = 2;
private static final int CMD_STOP = 3;
private AudioTrack audio;
private Thread playThread;
private SharedPreferences prefs;
private Watchdog watchdog;
private int bufferSize;
private int sampleRate, sampleFormat;
private Notifier notifier;
private int cmd;
private boolean restart;
private boolean canRelease;
private boolean paused;
private boolean looped;
private int startIndex;
private boolean updateData;
private String fileName; // currently playing file
private QueueManager queue;
private final RemoteCallbackList<PlayerCallback> callbacks =
new RemoteCallbackList<PlayerCallback>();
private int sequenceNumber;
// Telephony autopause
private boolean autoPaused; // paused on phone call
private boolean previousPaused; // save previous pause state
// Headset autopause
private HeadsetPlugReceiver headsetPlugReceiver;
private boolean headsetPause;
// remote control
private MediaButtons mediaButtons;
public static boolean isAlive;
public static boolean isLoaded;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Create service");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(Preferences.HEADSET_PAUSE, true)) {
// For listening to headset changes, the broadcast receiver cannot be
// declared in the manifest, it must be dynamically registered.
headsetPlugReceiver = new HeadsetPlugReceiver();
registerReceiver(headsetPlugReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
}
final int bufferMs = prefs.getInt(Preferences.BUFFER_MS, 500);
sampleRate = Integer.parseInt(prefs.getString(Preferences.SAMPLING_RATE, "44100"));
sampleFormat = 0;
final boolean stereo = prefs.getBoolean(Preferences.STEREO, true);
if (!stereo) {
sampleFormat |= Xmp.FORMAT_MONO;
}
bufferSize = (sampleRate * (stereo ? 2 : 1) * 2 * bufferMs / 1000) & ~0x3;
final int channelConfig = stereo ?
AudioFormat.CHANNEL_OUT_STEREO :
AudioFormat.CHANNEL_OUT_MONO;
final int minSize = AudioTrack.getMinBufferSize(
sampleRate,
channelConfig,
AudioFormat.ENCODING_PCM_16BIT);
if (bufferSize < minSize) {
bufferSize = minSize;
}
audio = new AudioTrack(
AudioManager.STREAM_MUSIC, sampleRate,
channelConfig,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize,
AudioTrack.MODE_STREAM);
Xmp.init();
isAlive = false;
isLoaded = false;
paused = false;
notifier = new Notifier(this);
final XmpPhoneStateListener listener = new XmpPhoneStateListener(this);
final TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(listener, XmpPhoneStateListener.LISTEN_CALL_STATE);
mediaButtons = new MediaButtons(this);
mediaButtons.register();
watchdog = new Watchdog(5);
watchdog.setOnTimeoutListener(new Watchdog.OnTimeoutListener() {
public void onTimeout() {
Log.e(TAG, "Stopped by watchdog");
stopSelf();
}
});
watchdog.start();
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
if (headsetPlugReceiver != null) {
unregisterReceiver(headsetPlugReceiver);
}
mediaButtons.unregister();
watchdog.stop();
notifier.cancel();
end();
super.onDestroy();
}
@Override
public IBinder onBind(final Intent intent) {
return binder;
}
private void updateNotification() {
if (paused) {
notifier.pauseNotification(Xmp.getModName(), queue.getIndex());
} else {
notifier.unpauseNotification(Xmp.getModName(), queue.getIndex());
}
}
private void doPauseAndNotify() {
paused ^= true;
updateNotification();
}
private void actionStop() {
Xmp.stopModule();
paused = false;
cmd = CMD_STOP;
}
private void actionPause() {
doPauseAndNotify();
// Notify clients that we paused
final int numClients = callbacks.beginBroadcast();
for (int i = 0; i < numClients; i++) {
try {
callbacks.getBroadcastItem(i).pauseCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying pause to client");
}
}
callbacks.finishBroadcast();
}
private void actionPrev() {
if (Xmp.time() > 2000) {
Xmp.seek(0);
} else {
Xmp.stopModule();
cmd = CMD_PREV;
}
paused = false;
}
private void actionNext() {
Xmp.stopModule();
paused = false;
cmd = CMD_NEXT;
}
private void checkMediaButtons() {
final int key = RemoteControlReceiver.getKeyCode();
if (key != RemoteControlReceiver.NO_KEY) {
switch (key) {
case KeyEvent.KEYCODE_MEDIA_NEXT:
Log.i(TAG, "Handle KEYCODE_MEDIA_NEXT");
actionNext();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.i(TAG, "Handle KEYCODE_MEDIA_PREVIOUS");
actionPrev();
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
Log.i(TAG, "Handle KEYCODE_MEDIA_STOP");
actionStop();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
Log.i(TAG, "Handle KEYCODE_MEDIA_PLAY_PAUSE");
actionPause();
headsetPause = false;
break;
}
RemoteControlReceiver.setKeyCode(RemoteControlReceiver.NO_KEY);
}
}
private void checkNotificationButtons() {
final int key = NotificationActionReceiver.getKeyCode();
if (key != NotificationActionReceiver.NO_KEY) {
switch (key) {
case NotificationActionReceiver.STOP:
Log.i(TAG, "Handle notification stop");
actionStop();
break;
case NotificationActionReceiver.PAUSE:
Log.i(TAG, "Handle notification pause");
actionPause();
headsetPause = false;
break;
case NotificationActionReceiver.NEXT:
Log.i(TAG, "Handle notification next");
actionNext();
break;
}
NotificationActionReceiver.setKeyCode(NotificationActionReceiver.NO_KEY);
}
}
private void checkHeadsetState() {
final int state = HeadsetPlugReceiver.getState();
if (state != HeadsetPlugReceiver.NO_STATE) {
switch (state) {
case HeadsetPlugReceiver.HEADSET_UNPLUGGED:
Log.i(TAG, "Handle headset unplugged");
// If not already paused
if (!paused && !autoPaused) {
headsetPause = true;
actionPause();
} else {
Log.i(TAG, "Already paused");
}
break;
case HeadsetPlugReceiver.HEADSET_PLUGGED:
Log.i(TAG, "Handle headset plugged");
// If paused by headset unplug
if (headsetPause) {
// Don't unpause if we're paused due to phone call
if (!autoPaused) {
actionPause();
} else {
Log.i(TAG, "Paused by phone state, don't unpause");
}
headsetPause = false;
} else {
Log.i(TAG, "Manual pause, don't unpause");
}
break;
}
HeadsetPlugReceiver.setState(HeadsetPlugReceiver.NO_STATE);
}
}
private int playFrame() {
// Synchronize frame play with data gathering so we don't change playing variables
// in the middle of e.g. sample data reading, which results in a segfault in C code
synchronized (playThread) {
return Xmp.playFrame();
}
}
private void notifyNewSequence() {
final int numClients = callbacks.beginBroadcast();
for (int j = 0; j < numClients; j++) {
try {
callbacks.getBroadcastItem(j).newSequenceCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of module to client");
}
}
callbacks.finishBroadcast();
}
private class PlayRunnable implements Runnable {
public void run() {
final short buffer[] = new short[bufferSize];
cmd = CMD_NONE;
do {
fileName = queue.getFilename(); // Used in reconnection
// If this file is unrecognized, and we're going backwards, go to previous
if (fileName == null || !InfoCache.testModule(fileName)) {
Log.w(TAG, fileName + ": unrecognized format");
if (cmd == CMD_PREV) {
if (queue.getIndex() < 0) {
break;
}
queue.previous();
}
continue;
}
// Ditto if we can't load the module
Log.w(TAG, "Load " + fileName);
if (Xmp.loadModule(fileName) < 0) {
Log.e(TAG, "Error loading " + fileName);
if (cmd == CMD_PREV) {
if (queue.getIndex() < 0) {
break;
}
queue.previous();
}
continue;
}
cmd = CMD_NONE;
notifier.tickerNotification(Xmp.getModName(), queue.getIndex());
isLoaded = true;
// Unmute all channels
for (int i = 0; i < 64; i++) {
Xmp.mute(i, 0);
}
int numClients = callbacks.beginBroadcast();
for (int j = 0; j < numClients; j++) {
try {
callbacks.getBroadcastItem(j).newModCallback(fileName, Xmp.getInstruments());
} catch (RemoteException e) {
Log.e(TAG, "Error notifying new module to client");
}
}
callbacks.finishBroadcast();
final String volBoost = prefs.getString(Preferences.VOL_BOOST, "1");
final int[] interpTypes = { Xmp.INTERP_NEAREST, Xmp.INTERP_LINEAR, Xmp.INTERP_SPLINE };
final int temp = Integer.parseInt(prefs.getString(Preferences.INTERP_TYPE, "1"));
int interpType;
if (temp >= 1 && temp <= 2) {
interpType = interpTypes[temp];
} else {
interpType = Xmp.INTERP_LINEAR;
}
int dsp = 0;
if (prefs.getBoolean(Preferences.FILTER, true)) {
dsp |= Xmp.DSP_LOWPASS;
}
if (!prefs.getBoolean(Preferences.INTERPOLATE, true)) {
interpType = Xmp.INTERP_NEAREST;
}
audio.play();
Xmp.startPlayer(0, sampleRate, sampleFormat);
Xmp.setPlayer(Xmp.PLAYER_AMP, Integer.parseInt(volBoost));
Xmp.setPlayer(Xmp.PLAYER_MIX, prefs.getInt(Preferences.PAN_SEPARATION, 70));
Xmp.setPlayer(Xmp.PLAYER_INTERP, interpType);
Xmp.setPlayer(Xmp.PLAYER_DSP, dsp);
updateData = true;
int count;
int loopCount = 0;
sequenceNumber = 0;
boolean playNewSequence;
final boolean allSequences = prefs.getBoolean(Preferences.ALL_SEQUENCES, false);
Xmp.setSequence(sequenceNumber);
do {
while (playFrame() == 0) {
count = Xmp.getLoopCount();
if (!looped && count != loopCount) {
break;
}
loopCount = count;
final int size = Xmp.getBuffer(buffer);
audio.write(buffer, 0, size);
while (paused) {
audio.flush();
audio.pause();
watchdog.refresh();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
checkMediaButtons();
checkHeadsetState();
checkNotificationButtons();
}
audio.play();
watchdog.refresh();
checkMediaButtons();
checkHeadsetState();
checkNotificationButtons();
}
// Subsong explorer
// Do all this if we've exited normally and explorer is active
playNewSequence = false;
if (allSequences && cmd == CMD_NONE) {
sequenceNumber++;
loopCount = Xmp.getLoopCount();
Log.w(TAG, "Play sequence " + sequenceNumber);
if (Xmp.setSequence(sequenceNumber)) {
playNewSequence = true;
notifyNewSequence();
}
}
} while (playNewSequence);
Xmp.endPlayer();
isLoaded = false;
// notify end of module to our clients
numClients = callbacks.beginBroadcast();
if (numClients > 0) {
canRelease = false;
for (int j = 0; j < numClients; j++) {
try {
Log.w(TAG, "Call end of module callback");
callbacks.getBroadcastItem(j).endModCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of module to client");
}
}
callbacks.finishBroadcast();
// if we have clients, make sure we can release module
int timeout = 0;
try {
while (!canRelease && timeout < 20) {
Thread.sleep(100);
timeout++;
}
} catch (InterruptedException e) {
Log.e(TAG, "Sleep interrupted: " + e);
}
} else {
callbacks.finishBroadcast();
}
Log.w(TAG, "Release module");
Xmp.releaseModule();
audio.stop();
// Used when current files are replaced by a new set
if (restart) {
Log.i(TAG, "Restart");
queue.setIndex(startIndex - 1);
cmd = CMD_NONE;
restart = false;
continue;
} else if (cmd == CMD_PREV) {
queue.previous();
//returnToPrev = false;
continue;
}
} while (cmd != CMD_STOP && queue.next());
synchronized (playThread) {
updateData = false; // stop getChannelData update
}
watchdog.stop();
notifier.cancel();
//end();
Log.i(TAG, "Stop service");
stopSelf();
}
}
private void end() {
Log.i(TAG, "End service");
final int numClients = callbacks.beginBroadcast();
for (int i = 0; i < numClients; i++) {
try {
callbacks.getBroadcastItem(i).endPlayCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of play to client");
}
}
callbacks.finishBroadcast();
isAlive = false;
Xmp.stopModule();
paused = false;
Xmp.deinit();
audio.release();
}
private final ModInterface.Stub binder = new ModInterface.Stub() {
public void play(final String[] files, final int start, final boolean shuffle, final boolean loopList, final boolean keepFirst) {
queue = new QueueManager(files, start, shuffle, loopList, keepFirst);
notifier.setQueue(queue);
//notifier.clean();
cmd = CMD_NONE;
paused = false;
if (isAlive) {
Log.i(TAG, "Use existing player thread");
restart = true;
startIndex = keepFirst ? 0 : start;
nextSong();
} else {
Log.i(TAG, "Start player thread");
playThread = new Thread(new PlayRunnable());
playThread.start();
}
isAlive = true;
}
public void add(final String[] files) {
queue.add(files);
updateNotification();
//notifier.notification("Added to play queue");
}
public void stop() {
actionStop();
}
public void pause() {
doPauseAndNotify();
headsetPause = false;
}
public void getInfo(final int[] values) {
Xmp.getInfo(values);
}
public void seek(final int seconds) {
Xmp.seek(seconds);
}
public int time() {
return Xmp.time();
}
public void getModVars(final int[] vars) {
Xmp.getModVars(vars);
}
public String getModName() {
return Xmp.getModName();
}
public String getModType() {
return Xmp.getModType();
}
public void getChannelData(int[] volumes, int[] finalvols, int[] pans, int[] instruments, int[] keys, int[] periods) {
if (updateData) {
synchronized (playThread) {
Xmp.getChannelData(volumes, finalvols, pans, instruments, keys, periods);
}
}
}
public void getSampleData(boolean trigger, int ins, int key, int period, int chn, int width, byte[] buffer) {
if (updateData) {
synchronized (playThread) {
Xmp.getSampleData(trigger, ins, key, period, chn, width, buffer);
}
}
}
public void nextSong() {
Xmp.stopModule();
cmd = CMD_NEXT;
paused = false;
}
public void prevSong() {
Xmp.stopModule();
cmd = CMD_PREV;
paused = false;
}
public boolean toggleLoop() throws RemoteException {
looped ^= true;
return looped;
}
public boolean isPaused() {
return paused;
}
public boolean setSequence(int seq) {
final boolean ret = Xmp.setSequence(seq);
if (ret) {
sequenceNumber = seq;
notifyNewSequence();
}
return ret;
}
public void allowRelease() {
canRelease = true;
}
public void getSeqVars(final int[] vars) {
Xmp.getSeqVars(vars);
}
// for Reconnection
public String getFileName() {
return fileName;
}
public String[] getInstruments() {
return Xmp.getInstruments();
}
public void getPatternRow(final int pat, final int row, final byte[] rowNotes, final byte[] rowInstruments) {
if (isAlive) {
Xmp.getPatternRow(pat, row, rowNotes, rowInstruments);
}
}
public int mute(final int chn, final int status) {
return Xmp.mute(chn, status);
}
public boolean hasComment() {
return Xmp.getComment() != null;
}
// File management
public boolean deleteFile() {
Log.i(TAG, "Delete file " + fileName);
return InfoCache.delete(fileName);
}
// Callback
public void registerCallback(final PlayerCallback callback) {
if (callback != null) {
callbacks.register(callback);
}
}
public void unregisterCallback(final PlayerCallback callback) {
if (callback != null) {
callbacks.unregister(callback);
}
}
};
// for Telephony
public boolean autoPause(final boolean pause) {
Log.i(TAG, "Auto pause changed to " + pause + ", previously " + autoPaused);
if (pause) {
previousPaused = paused;
autoPaused = true;
paused = false; // set to complement, flip on doPause()
doPauseAndNotify();
} else {
if (autoPaused && !headsetPause) {
autoPaused = false;
paused = !previousPaused; // set to complement, flip on doPause()
doPauseAndNotify();
}
}
return autoPaused;
}
}
| UTF-8 | Java | 17,954 | java | PlayerService.java | Java | []
| null | []
| package org.helllabs.android.xmp.service;
import org.helllabs.android.xmp.Xmp;
import org.helllabs.android.xmp.preferences.Preferences;
import org.helllabs.android.xmp.service.receiver.HeadsetPlugReceiver;
import org.helllabs.android.xmp.service.receiver.NotificationActionReceiver;
import org.helllabs.android.xmp.service.receiver.RemoteControlReceiver;
import org.helllabs.android.xmp.util.InfoCache;
import org.helllabs.android.xmp.util.Log;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
public final class PlayerService extends Service {
private static final String TAG = "PlayerService";
private static final int CMD_NONE = 0;
private static final int CMD_NEXT = 1;
private static final int CMD_PREV = 2;
private static final int CMD_STOP = 3;
private AudioTrack audio;
private Thread playThread;
private SharedPreferences prefs;
private Watchdog watchdog;
private int bufferSize;
private int sampleRate, sampleFormat;
private Notifier notifier;
private int cmd;
private boolean restart;
private boolean canRelease;
private boolean paused;
private boolean looped;
private int startIndex;
private boolean updateData;
private String fileName; // currently playing file
private QueueManager queue;
private final RemoteCallbackList<PlayerCallback> callbacks =
new RemoteCallbackList<PlayerCallback>();
private int sequenceNumber;
// Telephony autopause
private boolean autoPaused; // paused on phone call
private boolean previousPaused; // save previous pause state
// Headset autopause
private HeadsetPlugReceiver headsetPlugReceiver;
private boolean headsetPause;
// remote control
private MediaButtons mediaButtons;
public static boolean isAlive;
public static boolean isLoaded;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Create service");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(Preferences.HEADSET_PAUSE, true)) {
// For listening to headset changes, the broadcast receiver cannot be
// declared in the manifest, it must be dynamically registered.
headsetPlugReceiver = new HeadsetPlugReceiver();
registerReceiver(headsetPlugReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
}
final int bufferMs = prefs.getInt(Preferences.BUFFER_MS, 500);
sampleRate = Integer.parseInt(prefs.getString(Preferences.SAMPLING_RATE, "44100"));
sampleFormat = 0;
final boolean stereo = prefs.getBoolean(Preferences.STEREO, true);
if (!stereo) {
sampleFormat |= Xmp.FORMAT_MONO;
}
bufferSize = (sampleRate * (stereo ? 2 : 1) * 2 * bufferMs / 1000) & ~0x3;
final int channelConfig = stereo ?
AudioFormat.CHANNEL_OUT_STEREO :
AudioFormat.CHANNEL_OUT_MONO;
final int minSize = AudioTrack.getMinBufferSize(
sampleRate,
channelConfig,
AudioFormat.ENCODING_PCM_16BIT);
if (bufferSize < minSize) {
bufferSize = minSize;
}
audio = new AudioTrack(
AudioManager.STREAM_MUSIC, sampleRate,
channelConfig,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize,
AudioTrack.MODE_STREAM);
Xmp.init();
isAlive = false;
isLoaded = false;
paused = false;
notifier = new Notifier(this);
final XmpPhoneStateListener listener = new XmpPhoneStateListener(this);
final TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(listener, XmpPhoneStateListener.LISTEN_CALL_STATE);
mediaButtons = new MediaButtons(this);
mediaButtons.register();
watchdog = new Watchdog(5);
watchdog.setOnTimeoutListener(new Watchdog.OnTimeoutListener() {
public void onTimeout() {
Log.e(TAG, "Stopped by watchdog");
stopSelf();
}
});
watchdog.start();
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
if (headsetPlugReceiver != null) {
unregisterReceiver(headsetPlugReceiver);
}
mediaButtons.unregister();
watchdog.stop();
notifier.cancel();
end();
super.onDestroy();
}
@Override
public IBinder onBind(final Intent intent) {
return binder;
}
private void updateNotification() {
if (paused) {
notifier.pauseNotification(Xmp.getModName(), queue.getIndex());
} else {
notifier.unpauseNotification(Xmp.getModName(), queue.getIndex());
}
}
private void doPauseAndNotify() {
paused ^= true;
updateNotification();
}
private void actionStop() {
Xmp.stopModule();
paused = false;
cmd = CMD_STOP;
}
private void actionPause() {
doPauseAndNotify();
// Notify clients that we paused
final int numClients = callbacks.beginBroadcast();
for (int i = 0; i < numClients; i++) {
try {
callbacks.getBroadcastItem(i).pauseCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying pause to client");
}
}
callbacks.finishBroadcast();
}
private void actionPrev() {
if (Xmp.time() > 2000) {
Xmp.seek(0);
} else {
Xmp.stopModule();
cmd = CMD_PREV;
}
paused = false;
}
private void actionNext() {
Xmp.stopModule();
paused = false;
cmd = CMD_NEXT;
}
private void checkMediaButtons() {
final int key = RemoteControlReceiver.getKeyCode();
if (key != RemoteControlReceiver.NO_KEY) {
switch (key) {
case KeyEvent.KEYCODE_MEDIA_NEXT:
Log.i(TAG, "Handle KEYCODE_MEDIA_NEXT");
actionNext();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.i(TAG, "Handle KEYCODE_MEDIA_PREVIOUS");
actionPrev();
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
Log.i(TAG, "Handle KEYCODE_MEDIA_STOP");
actionStop();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
Log.i(TAG, "Handle KEYCODE_MEDIA_PLAY_PAUSE");
actionPause();
headsetPause = false;
break;
}
RemoteControlReceiver.setKeyCode(RemoteControlReceiver.NO_KEY);
}
}
private void checkNotificationButtons() {
final int key = NotificationActionReceiver.getKeyCode();
if (key != NotificationActionReceiver.NO_KEY) {
switch (key) {
case NotificationActionReceiver.STOP:
Log.i(TAG, "Handle notification stop");
actionStop();
break;
case NotificationActionReceiver.PAUSE:
Log.i(TAG, "Handle notification pause");
actionPause();
headsetPause = false;
break;
case NotificationActionReceiver.NEXT:
Log.i(TAG, "Handle notification next");
actionNext();
break;
}
NotificationActionReceiver.setKeyCode(NotificationActionReceiver.NO_KEY);
}
}
private void checkHeadsetState() {
final int state = HeadsetPlugReceiver.getState();
if (state != HeadsetPlugReceiver.NO_STATE) {
switch (state) {
case HeadsetPlugReceiver.HEADSET_UNPLUGGED:
Log.i(TAG, "Handle headset unplugged");
// If not already paused
if (!paused && !autoPaused) {
headsetPause = true;
actionPause();
} else {
Log.i(TAG, "Already paused");
}
break;
case HeadsetPlugReceiver.HEADSET_PLUGGED:
Log.i(TAG, "Handle headset plugged");
// If paused by headset unplug
if (headsetPause) {
// Don't unpause if we're paused due to phone call
if (!autoPaused) {
actionPause();
} else {
Log.i(TAG, "Paused by phone state, don't unpause");
}
headsetPause = false;
} else {
Log.i(TAG, "Manual pause, don't unpause");
}
break;
}
HeadsetPlugReceiver.setState(HeadsetPlugReceiver.NO_STATE);
}
}
private int playFrame() {
// Synchronize frame play with data gathering so we don't change playing variables
// in the middle of e.g. sample data reading, which results in a segfault in C code
synchronized (playThread) {
return Xmp.playFrame();
}
}
private void notifyNewSequence() {
final int numClients = callbacks.beginBroadcast();
for (int j = 0; j < numClients; j++) {
try {
callbacks.getBroadcastItem(j).newSequenceCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of module to client");
}
}
callbacks.finishBroadcast();
}
private class PlayRunnable implements Runnable {
public void run() {
final short buffer[] = new short[bufferSize];
cmd = CMD_NONE;
do {
fileName = queue.getFilename(); // Used in reconnection
// If this file is unrecognized, and we're going backwards, go to previous
if (fileName == null || !InfoCache.testModule(fileName)) {
Log.w(TAG, fileName + ": unrecognized format");
if (cmd == CMD_PREV) {
if (queue.getIndex() < 0) {
break;
}
queue.previous();
}
continue;
}
// Ditto if we can't load the module
Log.w(TAG, "Load " + fileName);
if (Xmp.loadModule(fileName) < 0) {
Log.e(TAG, "Error loading " + fileName);
if (cmd == CMD_PREV) {
if (queue.getIndex() < 0) {
break;
}
queue.previous();
}
continue;
}
cmd = CMD_NONE;
notifier.tickerNotification(Xmp.getModName(), queue.getIndex());
isLoaded = true;
// Unmute all channels
for (int i = 0; i < 64; i++) {
Xmp.mute(i, 0);
}
int numClients = callbacks.beginBroadcast();
for (int j = 0; j < numClients; j++) {
try {
callbacks.getBroadcastItem(j).newModCallback(fileName, Xmp.getInstruments());
} catch (RemoteException e) {
Log.e(TAG, "Error notifying new module to client");
}
}
callbacks.finishBroadcast();
final String volBoost = prefs.getString(Preferences.VOL_BOOST, "1");
final int[] interpTypes = { Xmp.INTERP_NEAREST, Xmp.INTERP_LINEAR, Xmp.INTERP_SPLINE };
final int temp = Integer.parseInt(prefs.getString(Preferences.INTERP_TYPE, "1"));
int interpType;
if (temp >= 1 && temp <= 2) {
interpType = interpTypes[temp];
} else {
interpType = Xmp.INTERP_LINEAR;
}
int dsp = 0;
if (prefs.getBoolean(Preferences.FILTER, true)) {
dsp |= Xmp.DSP_LOWPASS;
}
if (!prefs.getBoolean(Preferences.INTERPOLATE, true)) {
interpType = Xmp.INTERP_NEAREST;
}
audio.play();
Xmp.startPlayer(0, sampleRate, sampleFormat);
Xmp.setPlayer(Xmp.PLAYER_AMP, Integer.parseInt(volBoost));
Xmp.setPlayer(Xmp.PLAYER_MIX, prefs.getInt(Preferences.PAN_SEPARATION, 70));
Xmp.setPlayer(Xmp.PLAYER_INTERP, interpType);
Xmp.setPlayer(Xmp.PLAYER_DSP, dsp);
updateData = true;
int count;
int loopCount = 0;
sequenceNumber = 0;
boolean playNewSequence;
final boolean allSequences = prefs.getBoolean(Preferences.ALL_SEQUENCES, false);
Xmp.setSequence(sequenceNumber);
do {
while (playFrame() == 0) {
count = Xmp.getLoopCount();
if (!looped && count != loopCount) {
break;
}
loopCount = count;
final int size = Xmp.getBuffer(buffer);
audio.write(buffer, 0, size);
while (paused) {
audio.flush();
audio.pause();
watchdog.refresh();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
checkMediaButtons();
checkHeadsetState();
checkNotificationButtons();
}
audio.play();
watchdog.refresh();
checkMediaButtons();
checkHeadsetState();
checkNotificationButtons();
}
// Subsong explorer
// Do all this if we've exited normally and explorer is active
playNewSequence = false;
if (allSequences && cmd == CMD_NONE) {
sequenceNumber++;
loopCount = Xmp.getLoopCount();
Log.w(TAG, "Play sequence " + sequenceNumber);
if (Xmp.setSequence(sequenceNumber)) {
playNewSequence = true;
notifyNewSequence();
}
}
} while (playNewSequence);
Xmp.endPlayer();
isLoaded = false;
// notify end of module to our clients
numClients = callbacks.beginBroadcast();
if (numClients > 0) {
canRelease = false;
for (int j = 0; j < numClients; j++) {
try {
Log.w(TAG, "Call end of module callback");
callbacks.getBroadcastItem(j).endModCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of module to client");
}
}
callbacks.finishBroadcast();
// if we have clients, make sure we can release module
int timeout = 0;
try {
while (!canRelease && timeout < 20) {
Thread.sleep(100);
timeout++;
}
} catch (InterruptedException e) {
Log.e(TAG, "Sleep interrupted: " + e);
}
} else {
callbacks.finishBroadcast();
}
Log.w(TAG, "Release module");
Xmp.releaseModule();
audio.stop();
// Used when current files are replaced by a new set
if (restart) {
Log.i(TAG, "Restart");
queue.setIndex(startIndex - 1);
cmd = CMD_NONE;
restart = false;
continue;
} else if (cmd == CMD_PREV) {
queue.previous();
//returnToPrev = false;
continue;
}
} while (cmd != CMD_STOP && queue.next());
synchronized (playThread) {
updateData = false; // stop getChannelData update
}
watchdog.stop();
notifier.cancel();
//end();
Log.i(TAG, "Stop service");
stopSelf();
}
}
private void end() {
Log.i(TAG, "End service");
final int numClients = callbacks.beginBroadcast();
for (int i = 0; i < numClients; i++) {
try {
callbacks.getBroadcastItem(i).endPlayCallback();
} catch (RemoteException e) {
Log.e(TAG, "Error notifying end of play to client");
}
}
callbacks.finishBroadcast();
isAlive = false;
Xmp.stopModule();
paused = false;
Xmp.deinit();
audio.release();
}
private final ModInterface.Stub binder = new ModInterface.Stub() {
public void play(final String[] files, final int start, final boolean shuffle, final boolean loopList, final boolean keepFirst) {
queue = new QueueManager(files, start, shuffle, loopList, keepFirst);
notifier.setQueue(queue);
//notifier.clean();
cmd = CMD_NONE;
paused = false;
if (isAlive) {
Log.i(TAG, "Use existing player thread");
restart = true;
startIndex = keepFirst ? 0 : start;
nextSong();
} else {
Log.i(TAG, "Start player thread");
playThread = new Thread(new PlayRunnable());
playThread.start();
}
isAlive = true;
}
public void add(final String[] files) {
queue.add(files);
updateNotification();
//notifier.notification("Added to play queue");
}
public void stop() {
actionStop();
}
public void pause() {
doPauseAndNotify();
headsetPause = false;
}
public void getInfo(final int[] values) {
Xmp.getInfo(values);
}
public void seek(final int seconds) {
Xmp.seek(seconds);
}
public int time() {
return Xmp.time();
}
public void getModVars(final int[] vars) {
Xmp.getModVars(vars);
}
public String getModName() {
return Xmp.getModName();
}
public String getModType() {
return Xmp.getModType();
}
public void getChannelData(int[] volumes, int[] finalvols, int[] pans, int[] instruments, int[] keys, int[] periods) {
if (updateData) {
synchronized (playThread) {
Xmp.getChannelData(volumes, finalvols, pans, instruments, keys, periods);
}
}
}
public void getSampleData(boolean trigger, int ins, int key, int period, int chn, int width, byte[] buffer) {
if (updateData) {
synchronized (playThread) {
Xmp.getSampleData(trigger, ins, key, period, chn, width, buffer);
}
}
}
public void nextSong() {
Xmp.stopModule();
cmd = CMD_NEXT;
paused = false;
}
public void prevSong() {
Xmp.stopModule();
cmd = CMD_PREV;
paused = false;
}
public boolean toggleLoop() throws RemoteException {
looped ^= true;
return looped;
}
public boolean isPaused() {
return paused;
}
public boolean setSequence(int seq) {
final boolean ret = Xmp.setSequence(seq);
if (ret) {
sequenceNumber = seq;
notifyNewSequence();
}
return ret;
}
public void allowRelease() {
canRelease = true;
}
public void getSeqVars(final int[] vars) {
Xmp.getSeqVars(vars);
}
// for Reconnection
public String getFileName() {
return fileName;
}
public String[] getInstruments() {
return Xmp.getInstruments();
}
public void getPatternRow(final int pat, final int row, final byte[] rowNotes, final byte[] rowInstruments) {
if (isAlive) {
Xmp.getPatternRow(pat, row, rowNotes, rowInstruments);
}
}
public int mute(final int chn, final int status) {
return Xmp.mute(chn, status);
}
public boolean hasComment() {
return Xmp.getComment() != null;
}
// File management
public boolean deleteFile() {
Log.i(TAG, "Delete file " + fileName);
return InfoCache.delete(fileName);
}
// Callback
public void registerCallback(final PlayerCallback callback) {
if (callback != null) {
callbacks.register(callback);
}
}
public void unregisterCallback(final PlayerCallback callback) {
if (callback != null) {
callbacks.unregister(callback);
}
}
};
// for Telephony
public boolean autoPause(final boolean pause) {
Log.i(TAG, "Auto pause changed to " + pause + ", previously " + autoPaused);
if (pause) {
previousPaused = paused;
autoPaused = true;
paused = false; // set to complement, flip on doPause()
doPauseAndNotify();
} else {
if (autoPaused && !headsetPause) {
autoPaused = false;
paused = !previousPaused; // set to complement, flip on doPause()
doPauseAndNotify();
}
}
return autoPaused;
}
}
| 17,954 | 0.663418 | 0.65963 | 724 | 23.798342 | 21.750803 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.245856 | false | false | 1 |
1ad0b310ac68faf41fda0b243324ad6093daab3e | 20,289,425,572,718 | 9e16dec6a8edc067548bc67b07f6c1febf6b3a22 | /w3school/metodos/Perro.java | 6e0e5aff7f38dee42a08f59bfb440f8f695e6140 | [
"MIT"
]
| permissive | josevflores911/Java | https://github.com/josevflores911/Java | 9c74bbe917b171d6be9657876809f9b4c15ea981 | 79631c5caab2dc25f6ac3dda86d4075fb0b2d1a7 | refs/heads/main | 2023-03-02T23:47:56.668000 | 2021-11-19T21:51:15 | 2021-11-19T21:51:15 | 302,337,333 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Perro implements Accion{
@Override
public void habla(){
System.out.println("wow wow");
}
@Override
public void ataque(){
System.out.println("ladrido");
}
@Override
public void senha(){
System.out.println("123");
}
} | UTF-8 | Java | 246 | java | Perro.java | Java | [
{
"context": "e\n\tpublic void ataque(){\n\t\tSystem.out.println(\"ladrido\");\n\t}\n\n\t@Override\n\tpublic void senha(){\n\t\tSystem.",
"end": 171,
"score": 0.6982690691947937,
"start": 167,
"tag": "NAME",
"value": "rido"
}
]
| null | []
| public class Perro implements Accion{
@Override
public void habla(){
System.out.println("wow wow");
}
@Override
public void ataque(){
System.out.println("ladrido");
}
@Override
public void senha(){
System.out.println("123");
}
} | 246 | 0.674797 | 0.662602 | 16 | 14.4375 | 12.624227 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1875 | false | false | 1 |
00d612dde5dc88eb230ba8bf4f39484aa2fe769e | 1,683,627,194,768 | 75fcaceac02672555afe7eef5563d34baacb2cc3 | /src/main/java/com/google/code/gson/rpc/ServletInvocationContext.java | 38e548c96c905ca1e52a763aa608e87e34fd6a55 | []
| no_license | Korzi/gson-rpc | https://github.com/Korzi/gson-rpc | 2d97bebdb5bec4236bbca0e106fa168482f3629c | 27549705e352fdde1e2e9c235d0a1efeb78160b2 | refs/heads/master | 2016-08-12T19:07:46.532000 | 2011-01-17T09:04:09 | 2011-01-17T09:04:09 | 53,485,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.code.gson.rpc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author wangzijian
*
*/
public class ServletInvocationContext {
private static final ThreadLocal<HttpServletRequest> CURRENT_REQUEST = new ThreadLocal<HttpServletRequest>();
private static final ThreadLocal<HttpServletResponse> CURRENT_RESPONSE = new ThreadLocal<HttpServletResponse>();
private ServletInvocationContext() {
}
public static HttpServletRequest currentRequest() {
return CURRENT_REQUEST.get();
}
public static HttpServletResponse currentResponse() {
return CURRENT_RESPONSE.get();
}
static void set(HttpServletRequest request, HttpServletResponse response) {
CURRENT_REQUEST.set(request);
CURRENT_RESPONSE.set(response);
}
static void clear() {
CURRENT_REQUEST.set(null);
CURRENT_RESPONSE.set(null);
}
}
| UTF-8 | Java | 932 | java | ServletInvocationContext.java | Java | [
{
"context": ".http.HttpServletResponse;\r\n\r\n/**\r\n * \r\n * @author wangzijian\r\n * \r\n */\r\npublic class ServletInvocationContext ",
"end": 165,
"score": 0.9989365339279175,
"start": 155,
"tag": "USERNAME",
"value": "wangzijian"
}
]
| null | []
| package com.google.code.gson.rpc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author wangzijian
*
*/
public class ServletInvocationContext {
private static final ThreadLocal<HttpServletRequest> CURRENT_REQUEST = new ThreadLocal<HttpServletRequest>();
private static final ThreadLocal<HttpServletResponse> CURRENT_RESPONSE = new ThreadLocal<HttpServletResponse>();
private ServletInvocationContext() {
}
public static HttpServletRequest currentRequest() {
return CURRENT_REQUEST.get();
}
public static HttpServletResponse currentResponse() {
return CURRENT_RESPONSE.get();
}
static void set(HttpServletRequest request, HttpServletResponse response) {
CURRENT_REQUEST.set(request);
CURRENT_RESPONSE.set(response);
}
static void clear() {
CURRENT_REQUEST.set(null);
CURRENT_RESPONSE.set(null);
}
}
| 932 | 0.73927 | 0.73927 | 37 | 23.18919 | 29.078493 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.027027 | false | false | 1 |
a185a4a659d4fd3732af97c933722f244a71f772 | 17,197,049,064,775 | 5815ce1007a701fabc9a334c64e42ecbfdbd141f | /src/ShowEmployee.java | 69f69fb50628b377200ecbd726da984d06704d5f | []
| no_license | PrL327/Employee-Databases | https://github.com/PrL327/Employee-Databases | 5d714513e9c131e610bcc92bcfdf2493ed2729b0 | 83b2de303a520f54f9e915d43b9fa61389eb9a8f | refs/heads/master | 2021-01-21T10:08:43.217000 | 2017-02-28T03:17:56 | 2017-02-28T03:17:56 | 83,384,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Peter Laskai
* Employee DB: Creating a database full of employeer information
* Due 12/10/14
*/
import java.sql.*; // Needed for JDBC classes
/**
* This program demonstrates how to issue an SQL
* SELECT statement to a database using JDBC.
*/
public class ShowEmployee
{
public static void main(String[] args)
{
// Create a named constant for the URL.
// NOTE: This value is specific for Java DB.
final String DB_URL = "jdbc:derby:EmployeeDB";
try
{
// Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
// Create a statement object.
Statement stmt = conn.createStatement();
String sqlStatement =
"SELECT * Employee Information";
// Send the statement to the DBMS.
ResultSet result = stmt.executeQuery(sqlStatement);
// Display a header for the listing.
System.out.println("Employee Information");
System.out.println("------------------------------------------");
// Display the contents of the result set.
// The result set will have three columns.
while (result.next())
{
System.out.println(result.getString("Description") +
result.getString("EmpID") +
result.getString("Posistion")+
result.getDouble("Salary"));
}
// Close the connection
conn.close();
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
/*
PsuedoCode:
1.0 import database for JDBC classes
2.0 in CreateEmployeeDB.java create URL for Employee DB
3.0 Form Table in buildEmployeeTable method
4.0 or dropTable method if Table already exists.
5.0 add employee info including:
Name
EmployeeID
Posistion
Salary
6.0 or add to dropTable the same information
7.0 go to ShowEmploye.java which will intiate constructing the table
8.0 for table with given exception ex if caught
9.0 end
*/ | UTF-8 | Java | 1,949 | java | ShowEmployee.java | Java | [
{
"context": "/**\r\n * Peter Laskai\r\n * Employee DB: Creating a database full of empl",
"end": 20,
"score": 0.9998424649238586,
"start": 8,
"tag": "NAME",
"value": "Peter Laskai"
}
]
| null | []
| /**
* <NAME>
* Employee DB: Creating a database full of employeer information
* Due 12/10/14
*/
import java.sql.*; // Needed for JDBC classes
/**
* This program demonstrates how to issue an SQL
* SELECT statement to a database using JDBC.
*/
public class ShowEmployee
{
public static void main(String[] args)
{
// Create a named constant for the URL.
// NOTE: This value is specific for Java DB.
final String DB_URL = "jdbc:derby:EmployeeDB";
try
{
// Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
// Create a statement object.
Statement stmt = conn.createStatement();
String sqlStatement =
"SELECT * Employee Information";
// Send the statement to the DBMS.
ResultSet result = stmt.executeQuery(sqlStatement);
// Display a header for the listing.
System.out.println("Employee Information");
System.out.println("------------------------------------------");
// Display the contents of the result set.
// The result set will have three columns.
while (result.next())
{
System.out.println(result.getString("Description") +
result.getString("EmpID") +
result.getString("Posistion")+
result.getDouble("Salary"));
}
// Close the connection
conn.close();
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
/*
PsuedoCode:
1.0 import database for JDBC classes
2.0 in CreateEmployeeDB.java create URL for Employee DB
3.0 Form Table in buildEmployeeTable method
4.0 or dropTable method if Table already exists.
5.0 add employee info including:
Name
EmployeeID
Posistion
Salary
6.0 or add to dropTable the same information
7.0 go to ShowEmploye.java which will intiate constructing the table
8.0 for table with given exception ex if caught
9.0 end
*/ | 1,943 | 0.648538 | 0.636224 | 73 | 24.726027 | 21.157116 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.054795 | false | false | 1 |
9a8461e75cf1171a2504c5eb031807e37a4813c9 | 6,399,501,339,982 | 3a4fe2d29375e3264041657b6c90b219695b410e | /src/test/java/com.shpionkaz.automation.challenge/BaseTest.java | 246cb81771bea24c351e19515eeb38aea475dd21 | []
| no_license | shpionkaz/berlin-prague-trip | https://github.com/shpionkaz/berlin-prague-trip | 81d5b711738b0b195f8f7ab9db7a58744c23810b | ccb856130502ad14706f17bea36f9282f3f66617 | refs/heads/master | 2021-01-20T17:21:27.332000 | 2016-06-16T22:56:20 | 2016-06-16T22:56:20 | 61,320,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shpionkaz.automation.challenge;
import com.shpionkaz.automation.challenge.utils.TestUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BaseTest {
WebDriver driver;
public void setUp() throws Exception {
TestUtils.prepareChromeDriver();
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1024, 768));
}
public void tearDown() throws Exception {
driver.close();
}
public void deleteCookies() throws Exception {
driver.manage().deleteAllCookies();
}
}
| UTF-8 | Java | 655 | java | BaseTest.java | Java | []
| null | []
| package com.shpionkaz.automation.challenge;
import com.shpionkaz.automation.challenge.utils.TestUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BaseTest {
WebDriver driver;
public void setUp() throws Exception {
TestUtils.prepareChromeDriver();
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1024, 768));
}
public void tearDown() throws Exception {
driver.close();
}
public void deleteCookies() throws Exception {
driver.manage().deleteAllCookies();
}
}
| 655 | 0.703817 | 0.69313 | 25 | 25.08 | 21.404522 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 1 |
4be47cca3e8205cdf6df8ca8b78fe198bf905b92 | 841,813,657,610 | 92254d1244372c6de08619af5b57846c42517f6d | /com.ibfeifeng.mystring/src/mystring/User.java | 3c964c8dc6f4a42dc615dbe14a528738141950ad | []
| no_license | menglinlin/hadooop | https://github.com/menglinlin/hadooop | 747eda607b2215cadcf80a33586ed7bd0b4d0ec5 | d6f8794e969a44a45f414af2e11df598908c3b6c | refs/heads/master | 2021-01-17T18:35:24.829000 | 2016-10-21T09:19:39 | 2016-10-21T09:19:39 | 71,546,112 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mystring;
import java.io.Serializable;
public class User implements Serializable{
private String name;
private String sex;
private String ageString;
public User() {
super();
}
public User(String name, String sex, String ageString) {
super();
this.name = name;
this.sex = sex;
this.ageString = ageString;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAgeString() {
return ageString;
}
public void setAgeString(String ageString) {
this.ageString = ageString;
}
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", ageString=" + ageString
+ "]";
}
}
| UTF-8 | Java | 834 | java | User.java | Java | []
| null | []
| package mystring;
import java.io.Serializable;
public class User implements Serializable{
private String name;
private String sex;
private String ageString;
public User() {
super();
}
public User(String name, String sex, String ageString) {
super();
this.name = name;
this.sex = sex;
this.ageString = ageString;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAgeString() {
return ageString;
}
public void setAgeString(String ageString) {
this.ageString = ageString;
}
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", ageString=" + ageString
+ "]";
}
}
| 834 | 0.643885 | 0.643885 | 55 | 13.163636 | 16.023577 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.654545 | false | false | 1 |
4b1b2f978e1cb7272447ef6981a06c99d2b0699e | 6,476,810,703,266 | fa7ebe6d463b09bce7a3113dbf6f584ac9d00f04 | /design-pattern/src/test/java/com/study/design/pattern/principle/dependencyinversion/TomTest.java | 975041f9a842270fd54a8a58504c31336b66c72a | []
| no_license | song-qingwei/study | https://github.com/song-qingwei/study | b6c10e137d76306dfc3193e3e9d96da21cf78df0 | f659ed97491a45836ed70aadb8f6796367adac2d | refs/heads/master | 2021-02-09T07:36:55.317000 | 2020-03-02T03:32:48 | 2020-03-02T03:32:48 | 244,258,005 | 0 | 0 | null | false | 2020-10-13T19:59:10 | 2020-03-02T02:00:12 | 2020-03-02T03:38:49 | 2020-10-13T19:59:09 | 5 | 0 | 0 | 1 | Java | false | false | package com.study.design.pattern.principle.dependencyinversion;
/**
* {@link TomTest}
*
* @author SongQingWei
* @since 1.0.0
* 2020-03-02 10:44 周一
*/
class TomTest {
public static void main(String[] args) {
Tom tom = new Tom();
tom.setCourse(new StudyJavaCourse());
tom.study();
}
} | UTF-8 | Java | 326 | java | TomTest.java | Java | [
{
"context": "cyinversion;\n\n/**\n * {@link TomTest}\n *\n * @author SongQingWei\n * @since 1.0.0\n * 2020-03-02 10:44 周一\n */\nclass ",
"end": 113,
"score": 0.999671220779419,
"start": 102,
"tag": "NAME",
"value": "SongQingWei"
}
]
| null | []
| package com.study.design.pattern.principle.dependencyinversion;
/**
* {@link TomTest}
*
* @author SongQingWei
* @since 1.0.0
* 2020-03-02 10:44 周一
*/
class TomTest {
public static void main(String[] args) {
Tom tom = new Tom();
tom.setCourse(new StudyJavaCourse());
tom.study();
}
} | 326 | 0.614907 | 0.568323 | 17 | 18 | 17.816053 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 1 |
9234f9295143bd92810ae8bd94a92d8a04485875 | 34,308,198,821,317 | c35b3953b620fb382d9db1805275c5fa3925b3fd | /src/by/malinouski/hrace/filter/JspFilter.java | af6b930d51cc0a80a74330fd779c5bf04f27ac1a | []
| no_license | djnier/epam-final-races | https://github.com/djnier/epam-final-races | 3b11daf0648ddb780386cc68f8205f2fafd58f50 | 979035e05cfafa3843ebbd2b59c9512f5010ed63 | refs/heads/master | 2021-12-14T20:44:29.367000 | 2017-05-30T19:54:51 | 2017-05-30T19:54:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.malinouski.hrace.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import by.malinouski.hrace.constant.PathConsts;
import by.malinouski.hrace.constant.RequestConsts;
// TODO: Auto-generated Javadoc
/**
* Servlet Filter implementation class ProfileFilter.
*/
@WebFilter(filterName = "jsp")
public class JspFilter implements Filter {
/**
* Destroy.
*
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* Do filter.
*
* @param request the request
* @param response the response
* @param chain the chain
* @throws IOException Signals that an I/O exception has occurred.
* @throws ServletException the servlet exception
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getSession().getAttribute(RequestConsts.USER) != null ||
req.getRequestURI().endsWith(PathConsts.REGISTER)) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher(PathConsts.INDEX).forward(request, response);
}
}
/**
* Inits the.
*
* @param fConfig the f config
* @throws ServletException the servlet exception
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}
| UTF-8 | Java | 1,700 | java | JspFilter.java | Java | []
| null | []
| package by.malinouski.hrace.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import by.malinouski.hrace.constant.PathConsts;
import by.malinouski.hrace.constant.RequestConsts;
// TODO: Auto-generated Javadoc
/**
* Servlet Filter implementation class ProfileFilter.
*/
@WebFilter(filterName = "jsp")
public class JspFilter implements Filter {
/**
* Destroy.
*
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* Do filter.
*
* @param request the request
* @param response the response
* @param chain the chain
* @throws IOException Signals that an I/O exception has occurred.
* @throws ServletException the servlet exception
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getSession().getAttribute(RequestConsts.USER) != null ||
req.getRequestURI().endsWith(PathConsts.REGISTER)) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher(PathConsts.INDEX).forward(request, response);
}
}
/**
* Inits the.
*
* @param fConfig the f config
* @throws ServletException the servlet exception
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}
| 1,700 | 0.752941 | 0.752941 | 64 | 25.5625 | 23.376587 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15625 | false | false | 1 |
98f08bb50afccb3d34aefc3853424d07a3442d36 | 21,930,103,032,192 | 54b5d673bd063c7bdf3f542f8bf5be9448c438cf | /src/main/java/com/mybatiss/base/mysql/pojo/BinaryTree.java | 7c89cf7bf1e117e512c5152a4ae414641f832d5f | []
| no_license | eric3510/mybatis-agile-frame | https://github.com/eric3510/mybatis-agile-frame | a750c186bf91ca13bbf4d843c8f3cd3c4bf65d4b | d7d2bc457c049d9305128189d6eae61fce782d08 | refs/heads/master | 2020-04-01T14:06:04.657000 | 2018-10-16T12:30:18 | 2018-10-16T12:30:18 | 153,280,320 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mybatiss.base.mysql.pojo;
/***
* @author 王强 Email : eric3510@foxmail.com
* @version 创建时间:2018/2/2
* BinaryTree
*/
public class BinaryTree<T>{
/***
* 当前节点
*/
private T node;
/***
* 左节点
*/
private T leftNode;
/***
* 右节点
*/
private T rightNode;
}
| UTF-8 | Java | 351 | java | BinaryTree.java | Java | [
{
"context": "ge com.mybatiss.base.mysql.pojo;\n\n/***\n * @author 王强 Email : eric3510@foxmail.com\n * @version 创建时间:201",
"end": 57,
"score": 0.9988855123519897,
"start": 55,
"tag": "NAME",
"value": "王强"
},
{
"context": "tiss.base.mysql.pojo;\n\n/***\n * @author 王强 Email : eric3510@foxmail.com\n * @version 创建时间:2018/2/2\n * BinaryTree\n */\npubli",
"end": 86,
"score": 0.9999265670776367,
"start": 66,
"tag": "EMAIL",
"value": "eric3510@foxmail.com"
}
]
| null | []
| package com.mybatiss.base.mysql.pojo;
/***
* @author 王强 Email : <EMAIL>
* @version 创建时间:2018/2/2
* BinaryTree
*/
public class BinaryTree<T>{
/***
* 当前节点
*/
private T node;
/***
* 左节点
*/
private T leftNode;
/***
* 右节点
*/
private T rightNode;
}
| 338 | 0.523659 | 0.492114 | 23 | 12.782609 | 11.515421 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | false | false | 1 |
ea7ec5ea2eb9573bad360b83adf497db37f66096 | 35,296,041,292,530 | d51da2ce56bea433cffc6f063dc1204168a5f0cc | /app/src/main/java/com/awscherb/cardkeeper/ui/base/BaseFragment.java | c53627289d17b853b9b7a84d7974e96aa8167420 | [
"MIT"
]
| permissive | bunday/CardKeeper | https://github.com/bunday/CardKeeper | 80c43f0ea1c9c6b7f2ab74986540de331a497f4f | 5b82c9198d17ab81847a3f0c50ad08f325253e74 | refs/heads/master | 2020-12-03T04:02:52.706000 | 2017-05-05T01:21:39 | 2017-05-05T01:21:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.awscherb.cardkeeper.ui.base;
import com.trello.rxlifecycle.components.support.RxFragment;
public class BaseFragment extends RxFragment {
}
| UTF-8 | Java | 155 | java | BaseFragment.java | Java | []
| null | []
| package com.awscherb.cardkeeper.ui.base;
import com.trello.rxlifecycle.components.support.RxFragment;
public class BaseFragment extends RxFragment {
}
| 155 | 0.819355 | 0.819355 | 8 | 18.375 | 24.020498 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
7c9e54608ebdee70e071719ef123b313f942a140 | 33,629,593,996,106 | 4860d0f5f8e019753b088584c66b4b6e4a4fc1c1 | /app/src/main/java/sg/edu/np/imiapp/Chats_Page.java | 9e941311477b78e7f7f0b56a6f3d511ae7e49a06 | []
| no_license | leclerc162003/imi_app | https://github.com/leclerc162003/imi_app | 5abe1efb9a438951030cd244fb58eb1bccdb156d | 071f9fa2ffe22c8126ed515cbb2a267802484edf | refs/heads/main | 2023-06-27T21:53:33.561000 | 2021-08-01T04:05:11 | 2021-08-01T04:05:11 | 382,780,520 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sg.edu.np.imiapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Chats_Page extends AppCompatActivity {
public TextView noUsers;
//initialise firebase authentication
private FirebaseAuth mAuth;
//initialise firebase database
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance("https://imi-app-2a3ab-default-rtdb.asia-southeast1.firebasedatabase.app/");
DatabaseReference mDatabase = firebaseDatabase.getReference();
String currentuserID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_chatpage);
// using firebase to get the user uid
mAuth = FirebaseAuth.getInstance();
mAuth.getCurrentUser();
currentuserID = mAuth.getUid();
Log.d("Added user to list", mAuth.getUid());
//get intent from profile page
Intent receive = getIntent();
ArrayList<String> userInterests = receive.getStringArrayListExtra("userInterests");
RecyclerView rv = findViewById(R.id.userRV);
// set noUsers visibility to 0
noUsers = findViewById(R.id.noUSERS);
noUsers.setVisibility(View.GONE);
//if no users match display message
if (getUsers().size() == 0){
//add textview "try adding enw interests!!!"
noUsers.setVisibility(View.VISIBLE);
}
noUsers.setVisibility(View.GONE);
//display chat users using recyclerview
ChatsPageAdapter adapter = new ChatsPageAdapter(this, getUsers(),userInterests);
LinearLayoutManager lm = new LinearLayoutManager(this);
rv.setLayoutManager(lm);
rv.setAdapter(adapter);
}
public ArrayList<User> getUsers(){
//get users list from database
ArrayList<User> userList = new ArrayList<>();
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren() ) {
User user = postSnapshot.getValue(User.class);
if (user.getUID().contentEquals(mAuth.getUid()) != true) {
//userList.add(user);
Log.d("username from database", user.getUID());
Log.d("username from mAuth", mAuth.getUid());
Intent receive = getIntent();
//check if users interests match
List<String> userInterests = receive.getStringArrayListExtra("userInterests");
List<String> compareList = user.getInterests();
compareList.retainAll(userInterests);
if (compareList.size() != 0) {
userList.add(user);
}
}
}
}
@Override
public void onCancelled(DatabaseError error) {
System.out.println("The read failed");
// Failed to read value
}
});
return userList;
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences lastUserChatted = getSharedPreferences("lastUserChatted", MODE_PRIVATE);
String UID = lastUserChatted.getString("toID", "nouser");
String Name = lastUserChatted.getString("toNAME", "nouser");
lastUserChatted.edit().clear().commit();
}
} | UTF-8 | Java | 4,448 | java | Chats_Page.java | Java | []
| null | []
| package sg.edu.np.imiapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Chats_Page extends AppCompatActivity {
public TextView noUsers;
//initialise firebase authentication
private FirebaseAuth mAuth;
//initialise firebase database
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance("https://imi-app-2a3ab-default-rtdb.asia-southeast1.firebasedatabase.app/");
DatabaseReference mDatabase = firebaseDatabase.getReference();
String currentuserID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_chatpage);
// using firebase to get the user uid
mAuth = FirebaseAuth.getInstance();
mAuth.getCurrentUser();
currentuserID = mAuth.getUid();
Log.d("Added user to list", mAuth.getUid());
//get intent from profile page
Intent receive = getIntent();
ArrayList<String> userInterests = receive.getStringArrayListExtra("userInterests");
RecyclerView rv = findViewById(R.id.userRV);
// set noUsers visibility to 0
noUsers = findViewById(R.id.noUSERS);
noUsers.setVisibility(View.GONE);
//if no users match display message
if (getUsers().size() == 0){
//add textview "try adding enw interests!!!"
noUsers.setVisibility(View.VISIBLE);
}
noUsers.setVisibility(View.GONE);
//display chat users using recyclerview
ChatsPageAdapter adapter = new ChatsPageAdapter(this, getUsers(),userInterests);
LinearLayoutManager lm = new LinearLayoutManager(this);
rv.setLayoutManager(lm);
rv.setAdapter(adapter);
}
public ArrayList<User> getUsers(){
//get users list from database
ArrayList<User> userList = new ArrayList<>();
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren() ) {
User user = postSnapshot.getValue(User.class);
if (user.getUID().contentEquals(mAuth.getUid()) != true) {
//userList.add(user);
Log.d("username from database", user.getUID());
Log.d("username from mAuth", mAuth.getUid());
Intent receive = getIntent();
//check if users interests match
List<String> userInterests = receive.getStringArrayListExtra("userInterests");
List<String> compareList = user.getInterests();
compareList.retainAll(userInterests);
if (compareList.size() != 0) {
userList.add(user);
}
}
}
}
@Override
public void onCancelled(DatabaseError error) {
System.out.println("The read failed");
// Failed to read value
}
});
return userList;
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences lastUserChatted = getSharedPreferences("lastUserChatted", MODE_PRIVATE);
String UID = lastUserChatted.getString("toID", "nouser");
String Name = lastUserChatted.getString("toNAME", "nouser");
lastUserChatted.edit().clear().commit();
}
} | 4,448 | 0.645908 | 0.644559 | 119 | 36.386555 | 26.593456 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.596639 | false | false | 1 |
c66540a75e6b4f791ff45ed00746a954a0a8970d | 7,722,351,263,334 | 1d875b137e7f50acf7163ae8bceaafb52c636cb9 | /src/AddNewCustomer_UI/Data_Entry_UI.java | 275972592121102d607a7aa98938e986ea627f53 | []
| no_license | kusaldushmantha/OOSD_kusal | https://github.com/kusaldushmantha/OOSD_kusal | 064472f98f7ef20aa2fda3187fefdd3b29ed0051 | 1fb6b0827cdf534a8c993c122338416730a04bd3 | refs/heads/master | 2016-09-13T14:04:12.266000 | 2016-05-11T11:02:58 | 2016-05-11T11:02:58 | 58,386,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 AddNewCustomer_UI;
import Support.MathClass;
import Orders_Model.*;
import AddNewCustomer.CustomerTable;
import AddNewCustomer.NewCustomer_UIConnector;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Kusal
*/
public class Data_Entry_UI extends javax.swing.JFrame {
private OrderHandler orderHandler;
DefaultTableModel rightLenseModel;
DefaultTableModel leftLenseModel;
private NewCustomer_UIConnector customerUIconnector;
private CustomerTable table;
/**
* Creates new form NewCustomer_UI
*/
public Data_Entry_UI() {
initComponents();
customerUIconnector = new NewCustomer_UIConnector();
customerUIconnector.setNewCustomerUI(this);
customerUIconnector.setId();
//add Order handler
orderHandler=new OrderHandler();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btngrpOrderMethod = new javax.swing.ButtonGroup();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
lblcustomerid = new javax.swing.JLabel();
txtfirstname = new javax.swing.JTextField();
txtlastname = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtaddress = new javax.swing.JTextArea();
txtlandno = new javax.swing.JTextField();
txtmobileno = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
radiobtnNewOrder = new javax.swing.JRadioButton();
radiobtnRepairOrder = new javax.swing.JRadioButton();
jLabel8 = new javax.swing.JLabel();
lblDataEntry = new javax.swing.JLabel();
btnsubmitCustomer = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jPanelOrder = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
cmbRightDetailss = new javax.swing.JComboBox();
jLabel11 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
tblRightLense = new javax.swing.JTable();
chkBoxRightLense = new javax.swing.JCheckBox();
jPanel8 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
tblLeftLense = new javax.swing.JTable();
cmbLeftDetails = new javax.swing.JComboBox();
chkBoxLeftLense = new javax.swing.JCheckBox();
jPanel9 = new javax.swing.JPanel();
txtSegmentHeight = new javax.swing.JTextField();
txtPD = new javax.swing.JTextField();
cmbTint = new javax.swing.JComboBox();
jLabel9 = new javax.swing.JLabel();
txtRemark = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
txtSegmentSize = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
txtLenseSize = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
txtInsent = new javax.swing.JTextField();
jPanel10 = new javax.swing.JPanel();
jLabel18 = new javax.swing.JLabel();
txtFrameID = new javax.swing.JTextField();
txtFramePrice = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
btnChkPrice = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jPanel11 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
cmbFinished = new javax.swing.JComboBox();
jLabel21 = new javax.swing.JLabel();
lblExpired = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
lblOrderedDate = new javax.swing.JLabel();
lblExpiredDate = new javax.swing.JLabel();
jButton5 = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
jLabel24 = new javax.swing.JLabel();
txtOrderDesc = new javax.swing.JTextField();
btnCancelOrder = new javax.swing.JButton();
jPanel13 = new javax.swing.JPanel();
lblOrderID = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
lblOrderType = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tableCustomerDatabase = new javax.swing.JTable();
btnDeleteCustomer = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Customer ID : ");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("First Name :");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Last Name :");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Address :");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Contact Information");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("LandLine Number :");
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setText("Mobile Number :");
lblcustomerid.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtfirstname.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtlastname.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtaddress.setColumns(20);
txtaddress.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtaddress.setRows(5);
jScrollPane1.setViewportView(txtaddress);
txtlandno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtmobileno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Order Method", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
btngrpOrderMethod.add(radiobtnNewOrder);
radiobtnNewOrder.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
radiobtnNewOrder.setText("New Order");
radiobtnNewOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radiobtnNewOrderActionPerformed(evt);
}
});
btngrpOrderMethod.add(radiobtnRepairOrder);
radiobtnRepairOrder.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
radiobtnRepairOrder.setText("Repair Order");
radiobtnRepairOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radiobtnRepairOrderActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(radiobtnNewOrder)
.addGap(72, 72, 72)
.addComponent(radiobtnRepairOrder)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radiobtnNewOrder)
.addComponent(radiobtnRepairOrder))
.addContainerGap(23, Short.MAX_VALUE))
);
jLabel8.setText("Data Entry By :");
btnsubmitCustomer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnsubmitCustomer.setText("Submit Info");
btnsubmitCustomer.setToolTipText("");
btnsubmitCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnsubmitCustomerActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(143, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtlandno)
.addComponent(txtmobileno)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtlastname)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblcustomerid, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfirstname, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(78, 78, 78))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnsubmitCustomer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblDataEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(lblcustomerid, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtfirstname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtlastname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtlandno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txtmobileno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(lblDataEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(btnsubmitCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jTabbedPane1.addTab("Customer Information", jPanel1);
jPanel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanelOrder.setEnabled(false);
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lense Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Right Lense"));
cmbRightDetailss.setEnabled(false);
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel11.setText("Details:");
tblRightLense.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
tblRightLense.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{" DST", null, null, null},
{" READ", null, null, null}
},
new String [] {
"", "SPH", "CYL", "AXIS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblRightLense.setEnabled(false);
jScrollPane3.setViewportView(tblRightLense);
chkBoxRightLense.setText("Available");
chkBoxRightLense.setEnabled(false);
chkBoxRightLense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkBoxRightLenseActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbRightDetailss, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chkBoxRightLense)
.addGap(63, 63, 63))))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(cmbRightDetailss, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkBoxRightLense)))
);
jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Left lense"));
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel12.setText("Details:");
tblLeftLense.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
tblLeftLense.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{" DST", null, null, null},
{" READ", null, null, null}
},
new String [] {
"", "SPH", "CYL", "AXIS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblLeftLense.setEnabled(false);
jScrollPane4.setViewportView(tblLeftLense);
cmbLeftDetails.setEnabled(false);
cmbLeftDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbLeftDetailsActionPerformed(evt);
}
});
chkBoxLeftLense.setText("Available");
chkBoxLeftLense.setEnabled(false);
chkBoxLeftLense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkBoxLeftLenseActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbLeftDetails, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chkBoxLeftLense)
.addGap(66, 66, 66))))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(cmbLeftDetails, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkBoxLeftLense))
.addContainerGap())
);
jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Common"));
txtSegmentHeight.setEnabled(false);
txtSegmentHeight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSegmentHeightActionPerformed(evt);
}
});
txtPD.setEnabled(false);
txtPD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPDActionPerformed(evt);
}
});
cmbTint.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Tinted", "Normal" }));
cmbTint.setEnabled(false);
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel9.setText("Segment size :");
txtRemark.setEnabled(false);
txtRemark.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRemarkActionPerformed(evt);
}
});
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel10.setText("Tint status :");
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel13.setText("Lense size :");
jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel14.setText("Segment height :");
txtSegmentSize.setEnabled(false);
txtSegmentSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSegmentSizeActionPerformed(evt);
}
});
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel15.setText("Insent :");
jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel16.setText("Remark :");
txtLenseSize.setEnabled(false);
txtLenseSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtLenseSizeActionPerformed(evt);
}
});
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel17.setText("PD :");
txtInsent.setEnabled(false);
txtInsent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInsentActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtLenseSize)
.addComponent(cmbTint, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtSegmentHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtSegmentSize, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtRemark, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtInsent, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPD, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbTint, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(jLabel15)
.addComponent(txtInsent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(txtLenseSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17)
.addComponent(txtPD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel16)
.addComponent(txtRemark, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtSegmentSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel14)
.addComponent(txtSegmentHeight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Frame Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jLabel18.setText("Frame ID :");
txtFrameID.setEnabled(false);
txtFrameID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFrameIDActionPerformed(evt);
}
});
txtFramePrice.setText("0.00");
txtFramePrice.setEnabled(false);
jLabel19.setText("Frame price :");
btnChkPrice.setText("Check Price");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnChkPrice)
.addComponent(txtFrameID)
.addComponent(txtFramePrice, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE))
.addContainerGap())
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(txtFrameID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(txtFramePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnChkPrice)
.addContainerGap(38, Short.MAX_VALUE))
);
jButton1.setText("Payment details");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Customer details");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Order Status", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel20.setText("Finished :");
cmbFinished.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
cmbFinished.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "False", "True" }));
cmbFinished.setEnabled(false);
jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel21.setText("Expired :");
lblExpired.setForeground(new java.awt.Color(0, 153, 0));
lblExpired.setText("No");
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbFinished, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblExpired, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(cmbFinished, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel21)
.addComponent(lblExpired))
.addContainerGap())
);
jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel22.setText("Ordered date:");
jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel23.setText("Expired date:");
lblOrderedDate.setText("16/04/2016");
lblExpiredDate.setText("16/04/2018");
jButton5.setText("Edit");
jButton5.setEnabled(false);
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel12Layout.createSequentialGroup()
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblOrderedDate))
.addGroup(jPanel12Layout.createSequentialGroup()
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblExpiredDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel22)
.addComponent(lblOrderedDate)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(lblExpiredDate))
.addContainerGap(29, Short.MAX_VALUE))
);
btnEdit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnEdit.setText("Edit");
btnEdit.setEnabled(false);
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
btnSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
jLabel24.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel24.setText("Description :");
txtOrderDesc.setEnabled(false);
btnCancelOrder.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnCancelOrder.setText("Cancel Order");
btnCancelOrder.setEnabled(false);
btnCancelOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelOrderActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(175, 175, 175)
.addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancelOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtOrderDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 17, Short.MAX_VALUE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(20, 20, 20)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(2, 2, 2))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24))
.addComponent(txtOrderDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSave)
.addComponent(btnEdit)
.addComponent(btnCancelOrder))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13.setBackground(new java.awt.Color(153, 153, 153));
lblOrderID.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblOrderID.setText("0");
jLabel25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel25.setText("20/04/2016");
jLabel26.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel26.setText("Order ID :");
jLabel27.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel27.setText("2.00 PM");
lblOrderType.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblOrderType.setForeground(new java.awt.Color(204, 255, 255));
lblOrderType.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblOrderType.setText("New Order");
lblOrderType.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblOrderID, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59)
.addComponent(lblOrderType, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel25, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(lblOrderID)
.addComponent(lblOrderType))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel27)))
.addContainerGap())
);
javax.swing.GroupLayout jPanelOrderLayout = new javax.swing.GroupLayout(jPanelOrder);
jPanelOrder.setLayout(jPanelOrderLayout);
jPanelOrderLayout.setHorizontalGroup(
jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrderLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanelOrderLayout.setVerticalGroup(
jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrderLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Order Information", jPanel3);
jPanel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
tableCustomerDatabase.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(tableCustomerDatabase);
btnDeleteCustomer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnDeleteCustomer.setText("Delete Customer");
btnDeleteCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteCustomerActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 665, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(245, 245, 245)
.addComponent(btnDeleteCustomer)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 266, Short.MAX_VALUE)
.addComponent(btnDeleteCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41))
);
jTabbedPane1.addTab("Customer Database", jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnDeleteCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteCustomerActionPerformed
getTable().deleteEntry();
getTable().populateTable();
}//GEN-LAST:event_btnDeleteCustomerActionPerformed
private void radiobtnRepairOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radiobtnRepairOrderActionPerformed
}//GEN-LAST:event_radiobtnRepairOrderActionPerformed
private void radiobtnNewOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radiobtnNewOrderActionPerformed
}//GEN-LAST:event_radiobtnNewOrderActionPerformed
private void btnsubmitCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsubmitCustomerActionPerformed
boolean submitStatus= getUiConnector().getInfo();
getTable().populateTable();
//order related
if(submitStatus){
orderHandler.setCustomer(customerUIconnector.getCustomer());
if(radiobtnNewOrder.isSelected())orderHandler.setOrderState("NORMAL");
if(radiobtnRepairOrder.isSelected())orderHandler.setOrderState("REPAIR");
setModels();
this.orderHandler=orderHandler;
if(orderHandler.getOrderState()=="NEW")
{
lblOrderID.setText(String.valueOf(orderHandler.getNextID()));
lblOrderType.setText(orderHandler.getOrderType()+" ORDER");
setEnablity(true);
}
else
{
showOrderDetails();
setEnablity(false);
}
}
}//GEN-LAST:event_btnsubmitCustomerActionPerformed
private void chkBoxRightLenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkBoxRightLenseActionPerformed
if(chkBoxRightLense.isSelected()) tblRightLense.setEnabled(true);
else tblRightLense.setEnabled(false);
}//GEN-LAST:event_chkBoxRightLenseActionPerformed
private void cmbLeftDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbLeftDetailsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cmbLeftDetailsActionPerformed
private void chkBoxLeftLenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkBoxLeftLenseActionPerformed
if(chkBoxLeftLense.isSelected()) tblLeftLense.setEnabled(true);
else tblLeftLense.setEnabled(false);
}//GEN-LAST:event_chkBoxLeftLenseActionPerformed
private void txtSegmentHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSegmentHeightActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSegmentHeightActionPerformed
private void txtPDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPDActionPerformed
private void txtRemarkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRemarkActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRemarkActionPerformed
private void txtSegmentSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSegmentSizeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSegmentSizeActionPerformed
private void txtLenseSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLenseSizeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtLenseSizeActionPerformed
private void txtInsentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInsentActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtInsentActionPerformed
private void txtFrameIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFrameIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFrameIDActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
orderHandler.setOrderState("OLD");
setEnablity(true);
btnSave.setEnabled(true);
btnEdit.setEnabled(false);
}//GEN-LAST:event_btnEditActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
//functionality to save
if(orderHandler.getOrderState()=="NEW" && orderHandler.getOrderType()=="NORMAL")
{
orderHandler.addNormalOrder(txtFrameID.getText(), Float.valueOf(txtFramePrice.getText())
,getLenseCode("LEFT") , getLenseCode("RIGHT"), txtOrderDesc.getText(),
MathClass.boolString((String)cmbFinished.getSelectedItem()));
}
else if(orderHandler.getOrderState()=="NEW" && orderHandler.getOrderType()=="REPAIR")
{
orderHandler.addRepairOrder(txtOrderDesc.getText());
}
else if(orderHandler.getOrderState()=="OLD")
{
orderHandler.updateOrder(MathClass.boolString
((String)cmbFinished.getSelectedItem()));
}
setEnablity(false);
btnEdit.setEnabled(true);
btnCancelOrder.setEnabled(true);
btnSave.setEnabled(false);
}//GEN-LAST:event_btnSaveActionPerformed
private void btnCancelOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelOrderActionPerformed
if(orderHandler.cancelOrder())
{
JOptionPane.showMessageDialog(rootPane, "Order was canceled");
//closing
}
}//GEN-LAST:event_btnCancelOrderActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Data_Entry_UI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelOrder;
private javax.swing.JButton btnChkPrice;
private javax.swing.JButton btnDeleteCustomer;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnSave;
private javax.swing.ButtonGroup btngrpOrderMethod;
private javax.swing.JButton btnsubmitCustomer;
public javax.swing.JCheckBox chkBoxLeftLense;
public javax.swing.JCheckBox chkBoxRightLense;
public javax.swing.JComboBox cmbFinished;
public javax.swing.JComboBox cmbLeftDetails;
public javax.swing.JComboBox cmbRightDetailss;
public javax.swing.JComboBox cmbTint;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JPanel jPanelOrder;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel lblDataEntry;
public javax.swing.JLabel lblExpired;
public javax.swing.JLabel lblExpiredDate;
private javax.swing.JLabel lblOrderID;
private javax.swing.JLabel lblOrderType;
public javax.swing.JLabel lblOrderedDate;
private javax.swing.JLabel lblcustomerid;
private javax.swing.JRadioButton radiobtnNewOrder;
private javax.swing.JRadioButton radiobtnRepairOrder;
private javax.swing.JTable tableCustomerDatabase;
public javax.swing.JTable tblLeftLense;
public javax.swing.JTable tblRightLense;
public javax.swing.JTextField txtFrameID;
public javax.swing.JTextField txtFramePrice;
public javax.swing.JTextField txtInsent;
public javax.swing.JTextField txtLenseSize;
public javax.swing.JTextField txtOrderDesc;
public javax.swing.JTextField txtPD;
public javax.swing.JTextField txtRemark;
public javax.swing.JTextField txtSegmentHeight;
public javax.swing.JTextField txtSegmentSize;
private javax.swing.JTextArea txtaddress;
private javax.swing.JTextField txtfirstname;
private javax.swing.JTextField txtlandno;
private javax.swing.JTextField txtlastname;
private javax.swing.JTextField txtmobileno;
// End of variables declaration//GEN-END:variables
/**
* @return the txtaddress
*/
public JTextArea getTxtaddress() {
return txtaddress;
}
/**
* @param txtaddress the txtaddress to set
*/
public void setTxtaddress(String txtaddress) {
this.txtaddress.setText(txtaddress);
}
/**
* @return the txtfirstname
*/
public JTextField getTxtfirstname() {
return txtfirstname;
}
/**
* @param txtfirstname the txtfirstname to set
*/
public void setTxtfirstname(String txtfirstname) {
this.txtfirstname.setText(txtfirstname);
}
/**
* @return the txtlandno
*/
public JTextField getTxtlandno() {
return txtlandno;
}
public JTextField getTxtmobileno() {
return txtmobileno;
}
/**
* @param txtlandno the txtlandno to set
*/
public void setTxtlandno(String txtlandno) {
this.txtlandno.setText(txtlandno);
}
/**
* @return the txtlastname
*/
public JTextField getTxtlastname() {
return txtlastname;
}
/**
* @param txtlastname the txtlastname to set
*/
public void setTxtlastname(String txtlastname) {
this.txtlastname.setText(txtlastname);
}
/**
* @return the txtmobileno
*/
/**
* @param txtmobileno the txtmobileno to set
*/
public void setTxtmobileno(String txtmobileno) {
this.txtmobileno.setText(txtmobileno);
}
/**
* @return the jPanel3
*/
public javax.swing.JPanel getjPanel3() {
return jPanel3;
}
/**
* @param jPanel3 the jPanel3 to set
*/
public void setjPanel3(javax.swing.JPanel jPanel3) {
this.jPanel3 = jPanel3;
}
/**
* @return the lblcustomerid
*/
public String getLblcustomerid() {
return lblcustomerid.getText();
}
/**
* @param lblcustomerid the lblcustomerid to set
*/
public void setLblcustomerid(String id) {
this.lblcustomerid.setText(id);
}
/**
* @return the tableCustomerDatabase
*/
public javax.swing.JTable getTableCustomerDatabase() {
return tableCustomerDatabase;
}
/**
* @param tableCustomerDatabase the tableCustomerDatabase to set
*/
public void setTableCustomerDatabase(javax.swing.JTable tableCustomerDatabase) {
this.tableCustomerDatabase = tableCustomerDatabase;
}
/**
* @return the table
*/
public CustomerTable getTable() {
return table;
}
/**
* @param table the table to set
*/
public void setTable(CustomerTable table) {
this.table = table;
}
/**
* @return the customerUIconnector
*/
public NewCustomer_UIConnector getUiConnector() {
return customerUIconnector;
}
/**
* @param uiConnector the customerUIconnector to set
*/
public void setUiConnector(NewCustomer_UIConnector uiConnector) {
this.customerUIconnector = uiConnector;
}
/**
* @return the radiobtnNewOrder
*/
public javax.swing.JRadioButton getRadiobtnNewOrder() {
return radiobtnNewOrder;
}
/**
* @param radiobtnNewOrder the radiobtnNewOrder to set
*/
public void setRadiobtnNewOrder(javax.swing.JRadioButton radiobtnNewOrder) {
this.radiobtnNewOrder = radiobtnNewOrder;
}
/**
* @return the radiobtnRepairOrder
*/
public javax.swing.JRadioButton getRadiobtnRepairOrder() {
return radiobtnRepairOrder;
}
/**
* @param radiobtnRepairOrder the radiobtnRepairOrder to set
*/
public void setRadiobtnRepairOrder(javax.swing.JRadioButton radiobtnRepairOrder) {
this.radiobtnRepairOrder = radiobtnRepairOrder;
}
/**
* @return the btnsubmit
*/
public javax.swing.JButton getBtnsubmit() {
return btnsubmitCustomer;
}
/**
* @param btnsubmit the btnsubmit to set
*/
public void setBtnsubmit(javax.swing.JButton btnsubmit) {
this.btnsubmitCustomer = btnsubmit;
}
/**
* @return the lblDataEntry
*/
public javax.swing.JLabel getLblDataEntry() {
return lblDataEntry;
}
/**
* @param lblDataEntry the lblDataEntry to set
*/
public void setLblDataEntry(javax.swing.JLabel lblDataEntry) {
this.lblDataEntry = lblDataEntry;
}
/////////////////////order GUI
public void setModels()
{
leftLenseModel=(DefaultTableModel)tblLeftLense.getModel();
rightLenseModel=(DefaultTableModel)tblRightLense.getModel();
//System.out.println(rightLenseModel.getColumnCount());
}
public void setEnablity(boolean state) {
txtOrderDesc.setEnabled(state);
txtFrameID.setEnabled(state);
txtFramePrice.setEnabled(state);
chkBoxLeftLense.setEnabled(state);
chkBoxRightLense.setEnabled(state);
cmbRightDetailss.setEnabled(state);
cmbLeftDetails.setEnabled(state);
if(chkBoxLeftLense.isSelected())tblLeftLense.setEnabled(true);
if(chkBoxRightLense.isSelected())tblRightLense.setEnabled(true);
if(!state)
{
tblLeftLense.setEnabled(false);
tblRightLense.setEnabled(false);
}
cmbTint.setEnabled(state);
txtLenseSize.setEnabled(state);
txtSegmentSize.setEnabled(state);
txtSegmentHeight.setEnabled(state);
txtInsent.setEnabled(state);
txtPD.setEnabled(state);
txtRemark.setEnabled(state);
cmbFinished.setEnabled(state);
}
/*public void setLenseSpecificDetails(String rightLenseCode,String leftLenseCode)
{
//code=DST.SPH_DST.CYL_DST.AXIS_READ.SPH_READ.CYL_READ.AXIS
if(rightLenseCode==null){
chkBoxRightLense.setSelected(false);
}
else
{
chkBoxRightLense.setSelected(true);
String[] code=rightLenseCode.split("_");
rightLenseModel.setValueAt(Integer.parseInt(code[0]), 0, 1);
rightLenseModel.setValueAt(Integer.parseInt(code[1]), 0, 2);
rightLenseModel.setValueAt(Integer.parseInt(code[2]), 0, 3);
rightLenseModel.setValueAt(Integer.parseInt(code[3]), 1, 1);
rightLenseModel.setValueAt(Integer.parseInt(code[4]), 1, 2);
rightLenseModel.setValueAt(Integer.parseInt(code[5]), 1, 3);
}
if(leftLenseCode==null)
{
chkBoxLeftLense.setSelected(false);
}
else
{
chkBoxLeftLense.setSelected(true);
String[] code=rightLenseCode.split("_");
leftLenseModel.setValueAt(Integer.parseInt(code[0]), 0, 1);
leftLenseModel.setValueAt(Integer.parseInt(code[1]), 0, 2);
leftLenseModel.setValueAt(Integer.parseInt(code[2]), 0, 3);
leftLenseModel.setValueAt(Integer.parseInt(code[3]), 1, 1);
leftLenseModel.setValueAt(Integer.parseInt(code[4]), 1, 2);
leftLenseModel.setValueAt(Integer.parseInt(code[5]), 1, 3);
}
}*/
public void setLenseCommonDetails(String tint,int lenseSize,int segmentSize,
int segmentHeight,String insent,String PD,String remark)
{
//functionilty with correct data types
}
public void commonDetails(String orderedDate,String expiredDate,boolean finished)
{
lblOrderedDate.setText(orderedDate);
lblExpiredDate.setText(expiredDate);
cmbFinished.setSelectedItem(finished);
}
public String getLenseCode(String side)//side=left/right
{
DefaultTableModel tempTbl;
String lenseCode=null;
if(side=="LEFT" || side=="RIGHT")
{
if(side=="LEFT")tempTbl=leftLenseModel;
else tempTbl=rightLenseModel;
lenseCode=tempTbl.getValueAt(0, 1)+"_"+tempTbl.getValueAt(0, 2)+"_"
+tempTbl.getValueAt(0, 3)+"_"+tempTbl.getValueAt(1, 1)+"_"
+tempTbl.getValueAt(1, 2)+"_"+tempTbl.getValueAt(1, 3);
}
return lenseCode;
}
public void showOrderDetails()
{
Order order=orderHandler.getOrder();
lblOrderID.setText(String.valueOf(order.getOrder_id()));
lblOrderType.setText(order.getType()+" ORDER");
txtOrderDesc.setText(order.getDescription());
//txtFrameID.setText(order.getItems().get(0).getItem_id());
//txtFramePrice.setText(order.getItems().get(0).getPrice());
lblOrderedDate.setText(order.getDate());
//lblExpiredDate.setText(null);
cmbFinished.setSelectedIndex(MathClass.intBool(order.isFinished()));
lblExpired.setText(MathClass.stringBool(order.isExpired()));
// showLenseDetails((Lense)order.getItems().get(1));
// showLenseDetails((Lense)order.getItems().get(2));
}
public void showLenseDetails(int[][] arr,String side)
{
DefaultTableModel tempModel;
if(side=="LEFT")tempModel=leftLenseModel;
else tempModel=rightLenseModel;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
tempModel.setValueAt(arr[i][j], i, j);
}
}
}
}
| UTF-8 | Java | 84,035 | java | Data_Entry_UI.java | Java | [
{
"context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author Kusal\n */\npublic class Data_Entry_UI extends javax.swin",
"end": 508,
"score": 0.8461247682571411,
"start": 503,
"tag": "NAME",
"value": "Kusal"
}
]
| null | []
| /*
* 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 AddNewCustomer_UI;
import Support.MathClass;
import Orders_Model.*;
import AddNewCustomer.CustomerTable;
import AddNewCustomer.NewCustomer_UIConnector;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Kusal
*/
public class Data_Entry_UI extends javax.swing.JFrame {
private OrderHandler orderHandler;
DefaultTableModel rightLenseModel;
DefaultTableModel leftLenseModel;
private NewCustomer_UIConnector customerUIconnector;
private CustomerTable table;
/**
* Creates new form NewCustomer_UI
*/
public Data_Entry_UI() {
initComponents();
customerUIconnector = new NewCustomer_UIConnector();
customerUIconnector.setNewCustomerUI(this);
customerUIconnector.setId();
//add Order handler
orderHandler=new OrderHandler();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btngrpOrderMethod = new javax.swing.ButtonGroup();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
lblcustomerid = new javax.swing.JLabel();
txtfirstname = new javax.swing.JTextField();
txtlastname = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtaddress = new javax.swing.JTextArea();
txtlandno = new javax.swing.JTextField();
txtmobileno = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
radiobtnNewOrder = new javax.swing.JRadioButton();
radiobtnRepairOrder = new javax.swing.JRadioButton();
jLabel8 = new javax.swing.JLabel();
lblDataEntry = new javax.swing.JLabel();
btnsubmitCustomer = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jPanelOrder = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
cmbRightDetailss = new javax.swing.JComboBox();
jLabel11 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
tblRightLense = new javax.swing.JTable();
chkBoxRightLense = new javax.swing.JCheckBox();
jPanel8 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
tblLeftLense = new javax.swing.JTable();
cmbLeftDetails = new javax.swing.JComboBox();
chkBoxLeftLense = new javax.swing.JCheckBox();
jPanel9 = new javax.swing.JPanel();
txtSegmentHeight = new javax.swing.JTextField();
txtPD = new javax.swing.JTextField();
cmbTint = new javax.swing.JComboBox();
jLabel9 = new javax.swing.JLabel();
txtRemark = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
txtSegmentSize = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
txtLenseSize = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
txtInsent = new javax.swing.JTextField();
jPanel10 = new javax.swing.JPanel();
jLabel18 = new javax.swing.JLabel();
txtFrameID = new javax.swing.JTextField();
txtFramePrice = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
btnChkPrice = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jPanel11 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
cmbFinished = new javax.swing.JComboBox();
jLabel21 = new javax.swing.JLabel();
lblExpired = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
lblOrderedDate = new javax.swing.JLabel();
lblExpiredDate = new javax.swing.JLabel();
jButton5 = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
jLabel24 = new javax.swing.JLabel();
txtOrderDesc = new javax.swing.JTextField();
btnCancelOrder = new javax.swing.JButton();
jPanel13 = new javax.swing.JPanel();
lblOrderID = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
lblOrderType = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tableCustomerDatabase = new javax.swing.JTable();
btnDeleteCustomer = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Customer ID : ");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("First Name :");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Last Name :");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Address :");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Contact Information");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("LandLine Number :");
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setText("Mobile Number :");
lblcustomerid.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtfirstname.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtlastname.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtaddress.setColumns(20);
txtaddress.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtaddress.setRows(5);
jScrollPane1.setViewportView(txtaddress);
txtlandno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
txtmobileno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Order Method", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
btngrpOrderMethod.add(radiobtnNewOrder);
radiobtnNewOrder.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
radiobtnNewOrder.setText("New Order");
radiobtnNewOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radiobtnNewOrderActionPerformed(evt);
}
});
btngrpOrderMethod.add(radiobtnRepairOrder);
radiobtnRepairOrder.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
radiobtnRepairOrder.setText("Repair Order");
radiobtnRepairOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radiobtnRepairOrderActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(radiobtnNewOrder)
.addGap(72, 72, 72)
.addComponent(radiobtnRepairOrder)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radiobtnNewOrder)
.addComponent(radiobtnRepairOrder))
.addContainerGap(23, Short.MAX_VALUE))
);
jLabel8.setText("Data Entry By :");
btnsubmitCustomer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnsubmitCustomer.setText("Submit Info");
btnsubmitCustomer.setToolTipText("");
btnsubmitCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnsubmitCustomerActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(143, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtlandno)
.addComponent(txtmobileno)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtlastname)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblcustomerid, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfirstname, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(78, 78, 78))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnsubmitCustomer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblDataEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(lblcustomerid, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtfirstname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtlastname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtlandno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txtmobileno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(lblDataEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(btnsubmitCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jTabbedPane1.addTab("Customer Information", jPanel1);
jPanel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jPanelOrder.setEnabled(false);
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lense Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Right Lense"));
cmbRightDetailss.setEnabled(false);
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel11.setText("Details:");
tblRightLense.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
tblRightLense.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{" DST", null, null, null},
{" READ", null, null, null}
},
new String [] {
"", "SPH", "CYL", "AXIS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblRightLense.setEnabled(false);
jScrollPane3.setViewportView(tblRightLense);
chkBoxRightLense.setText("Available");
chkBoxRightLense.setEnabled(false);
chkBoxRightLense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkBoxRightLenseActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbRightDetailss, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chkBoxRightLense)
.addGap(63, 63, 63))))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(cmbRightDetailss, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkBoxRightLense)))
);
jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Left lense"));
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel12.setText("Details:");
tblLeftLense.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
tblLeftLense.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{" DST", null, null, null},
{" READ", null, null, null}
},
new String [] {
"", "SPH", "CYL", "AXIS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblLeftLense.setEnabled(false);
jScrollPane4.setViewportView(tblLeftLense);
cmbLeftDetails.setEnabled(false);
cmbLeftDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbLeftDetailsActionPerformed(evt);
}
});
chkBoxLeftLense.setText("Available");
chkBoxLeftLense.setEnabled(false);
chkBoxLeftLense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkBoxLeftLenseActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbLeftDetails, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chkBoxLeftLense)
.addGap(66, 66, 66))))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(cmbLeftDetails, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkBoxLeftLense))
.addContainerGap())
);
jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Common"));
txtSegmentHeight.setEnabled(false);
txtSegmentHeight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSegmentHeightActionPerformed(evt);
}
});
txtPD.setEnabled(false);
txtPD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPDActionPerformed(evt);
}
});
cmbTint.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Tinted", "Normal" }));
cmbTint.setEnabled(false);
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel9.setText("Segment size :");
txtRemark.setEnabled(false);
txtRemark.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRemarkActionPerformed(evt);
}
});
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel10.setText("Tint status :");
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel13.setText("Lense size :");
jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel14.setText("Segment height :");
txtSegmentSize.setEnabled(false);
txtSegmentSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSegmentSizeActionPerformed(evt);
}
});
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel15.setText("Insent :");
jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel16.setText("Remark :");
txtLenseSize.setEnabled(false);
txtLenseSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtLenseSizeActionPerformed(evt);
}
});
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel17.setText("PD :");
txtInsent.setEnabled(false);
txtInsent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInsentActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtLenseSize)
.addComponent(cmbTint, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtSegmentHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtSegmentSize, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtRemark, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtInsent, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPD, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbTint, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(jLabel15)
.addComponent(txtInsent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(txtLenseSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17)
.addComponent(txtPD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel16)
.addComponent(txtRemark, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtSegmentSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel14)
.addComponent(txtSegmentHeight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Frame Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jLabel18.setText("Frame ID :");
txtFrameID.setEnabled(false);
txtFrameID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFrameIDActionPerformed(evt);
}
});
txtFramePrice.setText("0.00");
txtFramePrice.setEnabled(false);
jLabel19.setText("Frame price :");
btnChkPrice.setText("Check Price");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnChkPrice)
.addComponent(txtFrameID)
.addComponent(txtFramePrice, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE))
.addContainerGap())
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(txtFrameID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(txtFramePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnChkPrice)
.addContainerGap(38, Short.MAX_VALUE))
);
jButton1.setText("Payment details");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Customer details");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Order Status", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel20.setText("Finished :");
cmbFinished.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
cmbFinished.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "False", "True" }));
cmbFinished.setEnabled(false);
jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel21.setText("Expired :");
lblExpired.setForeground(new java.awt.Color(0, 153, 0));
lblExpired.setText("No");
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbFinished, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblExpired, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(cmbFinished, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel21)
.addComponent(lblExpired))
.addContainerGap())
);
jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel22.setText("Ordered date:");
jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel23.setText("Expired date:");
lblOrderedDate.setText("16/04/2016");
lblExpiredDate.setText("16/04/2018");
jButton5.setText("Edit");
jButton5.setEnabled(false);
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel12Layout.createSequentialGroup()
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblOrderedDate))
.addGroup(jPanel12Layout.createSequentialGroup()
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblExpiredDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel22)
.addComponent(lblOrderedDate)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(lblExpiredDate))
.addContainerGap(29, Short.MAX_VALUE))
);
btnEdit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnEdit.setText("Edit");
btnEdit.setEnabled(false);
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
btnSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
jLabel24.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel24.setText("Description :");
txtOrderDesc.setEnabled(false);
btnCancelOrder.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnCancelOrder.setText("Cancel Order");
btnCancelOrder.setEnabled(false);
btnCancelOrder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelOrderActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(175, 175, 175)
.addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancelOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtOrderDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 17, Short.MAX_VALUE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(20, 20, 20)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(2, 2, 2))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24))
.addComponent(txtOrderDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSave)
.addComponent(btnEdit)
.addComponent(btnCancelOrder))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13.setBackground(new java.awt.Color(153, 153, 153));
lblOrderID.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblOrderID.setText("0");
jLabel25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel25.setText("20/04/2016");
jLabel26.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel26.setText("Order ID :");
jLabel27.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel27.setText("2.00 PM");
lblOrderType.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblOrderType.setForeground(new java.awt.Color(204, 255, 255));
lblOrderType.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblOrderType.setText("New Order");
lblOrderType.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblOrderID, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59)
.addComponent(lblOrderType, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel25, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(lblOrderID)
.addComponent(lblOrderType))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel27)))
.addContainerGap())
);
javax.swing.GroupLayout jPanelOrderLayout = new javax.swing.GroupLayout(jPanelOrder);
jPanelOrder.setLayout(jPanelOrderLayout);
jPanelOrderLayout.setHorizontalGroup(
jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrderLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanelOrderLayout.setVerticalGroup(
jPanelOrderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrderLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Order Information", jPanel3);
jPanel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
tableCustomerDatabase.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(tableCustomerDatabase);
btnDeleteCustomer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnDeleteCustomer.setText("Delete Customer");
btnDeleteCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteCustomerActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 665, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(245, 245, 245)
.addComponent(btnDeleteCustomer)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 266, Short.MAX_VALUE)
.addComponent(btnDeleteCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41))
);
jTabbedPane1.addTab("Customer Database", jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnDeleteCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteCustomerActionPerformed
getTable().deleteEntry();
getTable().populateTable();
}//GEN-LAST:event_btnDeleteCustomerActionPerformed
private void radiobtnRepairOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radiobtnRepairOrderActionPerformed
}//GEN-LAST:event_radiobtnRepairOrderActionPerformed
private void radiobtnNewOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radiobtnNewOrderActionPerformed
}//GEN-LAST:event_radiobtnNewOrderActionPerformed
private void btnsubmitCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsubmitCustomerActionPerformed
boolean submitStatus= getUiConnector().getInfo();
getTable().populateTable();
//order related
if(submitStatus){
orderHandler.setCustomer(customerUIconnector.getCustomer());
if(radiobtnNewOrder.isSelected())orderHandler.setOrderState("NORMAL");
if(radiobtnRepairOrder.isSelected())orderHandler.setOrderState("REPAIR");
setModels();
this.orderHandler=orderHandler;
if(orderHandler.getOrderState()=="NEW")
{
lblOrderID.setText(String.valueOf(orderHandler.getNextID()));
lblOrderType.setText(orderHandler.getOrderType()+" ORDER");
setEnablity(true);
}
else
{
showOrderDetails();
setEnablity(false);
}
}
}//GEN-LAST:event_btnsubmitCustomerActionPerformed
private void chkBoxRightLenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkBoxRightLenseActionPerformed
if(chkBoxRightLense.isSelected()) tblRightLense.setEnabled(true);
else tblRightLense.setEnabled(false);
}//GEN-LAST:event_chkBoxRightLenseActionPerformed
private void cmbLeftDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbLeftDetailsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cmbLeftDetailsActionPerformed
private void chkBoxLeftLenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkBoxLeftLenseActionPerformed
if(chkBoxLeftLense.isSelected()) tblLeftLense.setEnabled(true);
else tblLeftLense.setEnabled(false);
}//GEN-LAST:event_chkBoxLeftLenseActionPerformed
private void txtSegmentHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSegmentHeightActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSegmentHeightActionPerformed
private void txtPDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPDActionPerformed
private void txtRemarkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRemarkActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRemarkActionPerformed
private void txtSegmentSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSegmentSizeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSegmentSizeActionPerformed
private void txtLenseSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLenseSizeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtLenseSizeActionPerformed
private void txtInsentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInsentActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtInsentActionPerformed
private void txtFrameIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFrameIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFrameIDActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
orderHandler.setOrderState("OLD");
setEnablity(true);
btnSave.setEnabled(true);
btnEdit.setEnabled(false);
}//GEN-LAST:event_btnEditActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
//functionality to save
if(orderHandler.getOrderState()=="NEW" && orderHandler.getOrderType()=="NORMAL")
{
orderHandler.addNormalOrder(txtFrameID.getText(), Float.valueOf(txtFramePrice.getText())
,getLenseCode("LEFT") , getLenseCode("RIGHT"), txtOrderDesc.getText(),
MathClass.boolString((String)cmbFinished.getSelectedItem()));
}
else if(orderHandler.getOrderState()=="NEW" && orderHandler.getOrderType()=="REPAIR")
{
orderHandler.addRepairOrder(txtOrderDesc.getText());
}
else if(orderHandler.getOrderState()=="OLD")
{
orderHandler.updateOrder(MathClass.boolString
((String)cmbFinished.getSelectedItem()));
}
setEnablity(false);
btnEdit.setEnabled(true);
btnCancelOrder.setEnabled(true);
btnSave.setEnabled(false);
}//GEN-LAST:event_btnSaveActionPerformed
private void btnCancelOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelOrderActionPerformed
if(orderHandler.cancelOrder())
{
JOptionPane.showMessageDialog(rootPane, "Order was canceled");
//closing
}
}//GEN-LAST:event_btnCancelOrderActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Data_Entry_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Data_Entry_UI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelOrder;
private javax.swing.JButton btnChkPrice;
private javax.swing.JButton btnDeleteCustomer;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnSave;
private javax.swing.ButtonGroup btngrpOrderMethod;
private javax.swing.JButton btnsubmitCustomer;
public javax.swing.JCheckBox chkBoxLeftLense;
public javax.swing.JCheckBox chkBoxRightLense;
public javax.swing.JComboBox cmbFinished;
public javax.swing.JComboBox cmbLeftDetails;
public javax.swing.JComboBox cmbRightDetailss;
public javax.swing.JComboBox cmbTint;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JPanel jPanelOrder;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel lblDataEntry;
public javax.swing.JLabel lblExpired;
public javax.swing.JLabel lblExpiredDate;
private javax.swing.JLabel lblOrderID;
private javax.swing.JLabel lblOrderType;
public javax.swing.JLabel lblOrderedDate;
private javax.swing.JLabel lblcustomerid;
private javax.swing.JRadioButton radiobtnNewOrder;
private javax.swing.JRadioButton radiobtnRepairOrder;
private javax.swing.JTable tableCustomerDatabase;
public javax.swing.JTable tblLeftLense;
public javax.swing.JTable tblRightLense;
public javax.swing.JTextField txtFrameID;
public javax.swing.JTextField txtFramePrice;
public javax.swing.JTextField txtInsent;
public javax.swing.JTextField txtLenseSize;
public javax.swing.JTextField txtOrderDesc;
public javax.swing.JTextField txtPD;
public javax.swing.JTextField txtRemark;
public javax.swing.JTextField txtSegmentHeight;
public javax.swing.JTextField txtSegmentSize;
private javax.swing.JTextArea txtaddress;
private javax.swing.JTextField txtfirstname;
private javax.swing.JTextField txtlandno;
private javax.swing.JTextField txtlastname;
private javax.swing.JTextField txtmobileno;
// End of variables declaration//GEN-END:variables
/**
* @return the txtaddress
*/
public JTextArea getTxtaddress() {
return txtaddress;
}
/**
* @param txtaddress the txtaddress to set
*/
public void setTxtaddress(String txtaddress) {
this.txtaddress.setText(txtaddress);
}
/**
* @return the txtfirstname
*/
public JTextField getTxtfirstname() {
return txtfirstname;
}
/**
* @param txtfirstname the txtfirstname to set
*/
public void setTxtfirstname(String txtfirstname) {
this.txtfirstname.setText(txtfirstname);
}
/**
* @return the txtlandno
*/
public JTextField getTxtlandno() {
return txtlandno;
}
public JTextField getTxtmobileno() {
return txtmobileno;
}
/**
* @param txtlandno the txtlandno to set
*/
public void setTxtlandno(String txtlandno) {
this.txtlandno.setText(txtlandno);
}
/**
* @return the txtlastname
*/
public JTextField getTxtlastname() {
return txtlastname;
}
/**
* @param txtlastname the txtlastname to set
*/
public void setTxtlastname(String txtlastname) {
this.txtlastname.setText(txtlastname);
}
/**
* @return the txtmobileno
*/
/**
* @param txtmobileno the txtmobileno to set
*/
public void setTxtmobileno(String txtmobileno) {
this.txtmobileno.setText(txtmobileno);
}
/**
* @return the jPanel3
*/
public javax.swing.JPanel getjPanel3() {
return jPanel3;
}
/**
* @param jPanel3 the jPanel3 to set
*/
public void setjPanel3(javax.swing.JPanel jPanel3) {
this.jPanel3 = jPanel3;
}
/**
* @return the lblcustomerid
*/
public String getLblcustomerid() {
return lblcustomerid.getText();
}
/**
* @param lblcustomerid the lblcustomerid to set
*/
public void setLblcustomerid(String id) {
this.lblcustomerid.setText(id);
}
/**
* @return the tableCustomerDatabase
*/
public javax.swing.JTable getTableCustomerDatabase() {
return tableCustomerDatabase;
}
/**
* @param tableCustomerDatabase the tableCustomerDatabase to set
*/
public void setTableCustomerDatabase(javax.swing.JTable tableCustomerDatabase) {
this.tableCustomerDatabase = tableCustomerDatabase;
}
/**
* @return the table
*/
public CustomerTable getTable() {
return table;
}
/**
* @param table the table to set
*/
public void setTable(CustomerTable table) {
this.table = table;
}
/**
* @return the customerUIconnector
*/
public NewCustomer_UIConnector getUiConnector() {
return customerUIconnector;
}
/**
* @param uiConnector the customerUIconnector to set
*/
public void setUiConnector(NewCustomer_UIConnector uiConnector) {
this.customerUIconnector = uiConnector;
}
/**
* @return the radiobtnNewOrder
*/
public javax.swing.JRadioButton getRadiobtnNewOrder() {
return radiobtnNewOrder;
}
/**
* @param radiobtnNewOrder the radiobtnNewOrder to set
*/
public void setRadiobtnNewOrder(javax.swing.JRadioButton radiobtnNewOrder) {
this.radiobtnNewOrder = radiobtnNewOrder;
}
/**
* @return the radiobtnRepairOrder
*/
public javax.swing.JRadioButton getRadiobtnRepairOrder() {
return radiobtnRepairOrder;
}
/**
* @param radiobtnRepairOrder the radiobtnRepairOrder to set
*/
public void setRadiobtnRepairOrder(javax.swing.JRadioButton radiobtnRepairOrder) {
this.radiobtnRepairOrder = radiobtnRepairOrder;
}
/**
* @return the btnsubmit
*/
public javax.swing.JButton getBtnsubmit() {
return btnsubmitCustomer;
}
/**
* @param btnsubmit the btnsubmit to set
*/
public void setBtnsubmit(javax.swing.JButton btnsubmit) {
this.btnsubmitCustomer = btnsubmit;
}
/**
* @return the lblDataEntry
*/
public javax.swing.JLabel getLblDataEntry() {
return lblDataEntry;
}
/**
* @param lblDataEntry the lblDataEntry to set
*/
public void setLblDataEntry(javax.swing.JLabel lblDataEntry) {
this.lblDataEntry = lblDataEntry;
}
/////////////////////order GUI
public void setModels()
{
leftLenseModel=(DefaultTableModel)tblLeftLense.getModel();
rightLenseModel=(DefaultTableModel)tblRightLense.getModel();
//System.out.println(rightLenseModel.getColumnCount());
}
public void setEnablity(boolean state) {
txtOrderDesc.setEnabled(state);
txtFrameID.setEnabled(state);
txtFramePrice.setEnabled(state);
chkBoxLeftLense.setEnabled(state);
chkBoxRightLense.setEnabled(state);
cmbRightDetailss.setEnabled(state);
cmbLeftDetails.setEnabled(state);
if(chkBoxLeftLense.isSelected())tblLeftLense.setEnabled(true);
if(chkBoxRightLense.isSelected())tblRightLense.setEnabled(true);
if(!state)
{
tblLeftLense.setEnabled(false);
tblRightLense.setEnabled(false);
}
cmbTint.setEnabled(state);
txtLenseSize.setEnabled(state);
txtSegmentSize.setEnabled(state);
txtSegmentHeight.setEnabled(state);
txtInsent.setEnabled(state);
txtPD.setEnabled(state);
txtRemark.setEnabled(state);
cmbFinished.setEnabled(state);
}
/*public void setLenseSpecificDetails(String rightLenseCode,String leftLenseCode)
{
//code=DST.SPH_DST.CYL_DST.AXIS_READ.SPH_READ.CYL_READ.AXIS
if(rightLenseCode==null){
chkBoxRightLense.setSelected(false);
}
else
{
chkBoxRightLense.setSelected(true);
String[] code=rightLenseCode.split("_");
rightLenseModel.setValueAt(Integer.parseInt(code[0]), 0, 1);
rightLenseModel.setValueAt(Integer.parseInt(code[1]), 0, 2);
rightLenseModel.setValueAt(Integer.parseInt(code[2]), 0, 3);
rightLenseModel.setValueAt(Integer.parseInt(code[3]), 1, 1);
rightLenseModel.setValueAt(Integer.parseInt(code[4]), 1, 2);
rightLenseModel.setValueAt(Integer.parseInt(code[5]), 1, 3);
}
if(leftLenseCode==null)
{
chkBoxLeftLense.setSelected(false);
}
else
{
chkBoxLeftLense.setSelected(true);
String[] code=rightLenseCode.split("_");
leftLenseModel.setValueAt(Integer.parseInt(code[0]), 0, 1);
leftLenseModel.setValueAt(Integer.parseInt(code[1]), 0, 2);
leftLenseModel.setValueAt(Integer.parseInt(code[2]), 0, 3);
leftLenseModel.setValueAt(Integer.parseInt(code[3]), 1, 1);
leftLenseModel.setValueAt(Integer.parseInt(code[4]), 1, 2);
leftLenseModel.setValueAt(Integer.parseInt(code[5]), 1, 3);
}
}*/
public void setLenseCommonDetails(String tint,int lenseSize,int segmentSize,
int segmentHeight,String insent,String PD,String remark)
{
//functionilty with correct data types
}
public void commonDetails(String orderedDate,String expiredDate,boolean finished)
{
lblOrderedDate.setText(orderedDate);
lblExpiredDate.setText(expiredDate);
cmbFinished.setSelectedItem(finished);
}
public String getLenseCode(String side)//side=left/right
{
DefaultTableModel tempTbl;
String lenseCode=null;
if(side=="LEFT" || side=="RIGHT")
{
if(side=="LEFT")tempTbl=leftLenseModel;
else tempTbl=rightLenseModel;
lenseCode=tempTbl.getValueAt(0, 1)+"_"+tempTbl.getValueAt(0, 2)+"_"
+tempTbl.getValueAt(0, 3)+"_"+tempTbl.getValueAt(1, 1)+"_"
+tempTbl.getValueAt(1, 2)+"_"+tempTbl.getValueAt(1, 3);
}
return lenseCode;
}
public void showOrderDetails()
{
Order order=orderHandler.getOrder();
lblOrderID.setText(String.valueOf(order.getOrder_id()));
lblOrderType.setText(order.getType()+" ORDER");
txtOrderDesc.setText(order.getDescription());
//txtFrameID.setText(order.getItems().get(0).getItem_id());
//txtFramePrice.setText(order.getItems().get(0).getPrice());
lblOrderedDate.setText(order.getDate());
//lblExpiredDate.setText(null);
cmbFinished.setSelectedIndex(MathClass.intBool(order.isFinished()));
lblExpired.setText(MathClass.stringBool(order.isExpired()));
// showLenseDetails((Lense)order.getItems().get(1));
// showLenseDetails((Lense)order.getItems().get(2));
}
public void showLenseDetails(int[][] arr,String side)
{
DefaultTableModel tempModel;
if(side=="LEFT")tempModel=leftLenseModel;
else tempModel=rightLenseModel;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
tempModel.setValueAt(arr[i][j], i, j);
}
}
}
}
| 84,035 | 0.656893 | 0.641864 | 1,659 | 49.654007 | 40.294285 | 247 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.732369 | false | false | 1 |
021063fb4e83e5a3c5ffadf3d51e1807ad1c5b76 | 31,138,512,961,980 | 6363c31191518542d8191fa26c28eddac0200381 | /src/src/MainWindowController.java | 68ed0daf938aba4d6c1ce361bfc069fcf82c5c61 | []
| no_license | NabilAldihni/regex-builder | https://github.com/NabilAldihni/regex-builder | d727cd268b2434bd661a947d2d73661c60d01e3b | 33cedd2683b68483ab658736e50db74e3b1922c5 | refs/heads/main | 2023-09-05T06:30:46.804000 | 2021-11-20T18:47:33 | 2021-11-20T18:47:33 | 344,082,082 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import javafx.scene.image.Image ;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.regex.*;
public class MainWindowController {
// Non-FXML variables
private ArrayList<Expression> expressions;
private int selectedIndex;
// FXML Elements
public Label expressionLabel;
public TextField fullRegexField;
public ListView<Expression> expressionListView;
public Expression ex;
public Button addExpressionBtn;
public Button removeExpressionBtn;
public Button moveUpBtn;
public Button moveDownBtn;
public Button editExpressionBtn;
public Button helpBtn;
public CheckBox firstElementCheckBox;
public CheckBox lastElementCheckBox;
@FXML
/**
* Method called by FXML when the window is started
*/
public void initialize() {
// Updated mainWindowController in the StageConfig class so the editor window controller can later access it
StageConfig.setMainWindowController(this);
expressions = new ArrayList<Expression>();
selectedIndex = 0;
// Cell Factory to allow the ListView to store whole Expression objects while displaying a full description of the expression
expressionListView.setCellFactory(new Callback<ListView<Expression>, ListCell<Expression>>() {
@Override
public ListCell<Expression> call(ListView<Expression> listView) {
ListCell<Expression> cell = new ListCell<Expression>(){
@Override
protected void updateItem(Expression e, boolean empty){
super.updateItem(e, empty);
String fullDesc = "";
if (e != null) {
if (e.getGroup().getDesc().equals("")){
fullDesc += "Not a capture group\n";
}
else {
fullDesc += e.getGroup().getDesc() + " (" + e.getQuantifier().getDesc().toLowerCase() + ") containing:\n";
}
for (Element element : e.getElements()) {
fullDesc += "\t" + element.getDesc() + "\n";
fullDesc += "\t\t" + element.getQuantifier().getDesc() + "\n";
}
setText(fullDesc);
}
else {
setText("");
}
}
};
return cell;
}
});
}
/**
* Getter used to access the list of expressions
* @return arraylist of expressions
*/
public ArrayList<Expression> getExpressions() {
return expressions;
}
/**
* Used to change the current expressions in the list of expressions
* @param expressions
*/
public void setExpressions(ArrayList<Expression> expressions) {
this.expressions = expressions;
}
/**
* Getter used to access the selected item index
* @return the index
*/
public int getSelectedIndex() {
return selectedIndex;
}
/**
* Used to change the current selectedIndex in the list of expressions
* @param selectedIndex
*/
public void setSelectedIndex(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
/**
* Called every time a change is made to the expressions list. Updates the string in the textField
* @return A string with the full expression
*/
public String refreshExpression() {
fullRegexField.setText("");
String fullExp = "";
if (firstElementCheckBox.isSelected()) {
fullExp+="^";
}
for (Expression e : expressions) {
fullExp+=e.compileExpression();
}
if (lastElementCheckBox.isSelected()) {
fullExp+="$";
}
fullRegexField.setText(fullExp);
return fullExp;
}
/**
* Called when the add expression button is pressed (FXML event listener)
* @param actionEvent
*/
public void pressedAddExpression(ActionEvent actionEvent) {
// Stores the selected index so the created expression is added in the correct place
if (expressionListView.getSelectionModel().getSelectedIndex() == -1) {
selectedIndex = 0;
}
else {
selectedIndex = expressionListView.getSelectionModel().getSelectedIndex() + 1;
}
// Opens the Editor Window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/editorWindow.fxml"));
Stage editorStage = new Stage();
editorStage.setTitle("Regex builder - Expression editor");
editorStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
editorStage.initModality(Modality.APPLICATION_MODAL);
editorStage.setResizable(false);
editorStage.show();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
/**
* Removes selected expression from ListView and ArrayList
* @param actionEvent
*/
public void pressedRemoveExpression(ActionEvent actionEvent) {
int index = expressionListView.getSelectionModel().getSelectedIndex();
int size = expressionListView.getItems().size();
expressions.remove(expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().remove(expressionListView.getSelectionModel().getSelectedItem());
// Automatically selects the expression that takes its place or the last expression
if (index < size-1) {
expressionListView.getSelectionModel().select(index);
}
else {
expressionListView.getSelectionModel().select(index-1);
}
refreshExpression();
}
/**
* Moves the selected expression up in the list
* @param actionEvent
*/
public void pressedMoveUp(ActionEvent actionEvent) {
Expression item = expressionListView.getSelectionModel().getSelectedItem();
int index = expressionListView.getSelectionModel().getSelectedIndex();
if (index > 0) {
expressionListView.getItems().remove(index);
expressionListView.getItems().add(index-1, item);
expressionListView.getSelectionModel().select(index-1);
expressions.remove(index);
expressions.add(index-1, item);
}
refreshExpression();
}
/**
* Moves the selected expression down in the list
* @param actionEvent
*/
public void pressedMoveDown(ActionEvent actionEvent) {
Expression item = expressionListView.getSelectionModel().getSelectedItem();
int index = expressionListView.getSelectionModel().getSelectedIndex();
if (index < expressionListView.getItems().size() - 1) {
expressionListView.getItems().remove(index);
expressionListView.getItems().add(index+1, item);
expressionListView.getSelectionModel().select(index+1);
expressions.remove(index);
expressions.add(index+1, item);
}
refreshExpression();
}
/**
* Duplicates the selected expression
* @param actionEvent
*/
public void pressedDuplicateExpression(ActionEvent actionEvent) {
int index = expressionListView.getSelectionModel().getSelectedIndex();
// Creates a deep copy of the selected object (by value)
Expression e = new Expression((Expression) expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().add(index+1, e);
expressions.add(index+1, e);
expressionListView.getSelectionModel().select(index+1);
refreshExpression();
}
/**
* Opens the editor window and loads the selected expression's data
* @param actionEvent
*/
public void pressedEditExpression(ActionEvent actionEvent) {
// Stores the selected index so the created expression is added in the correct place
if (expressionListView.getSelectionModel().getSelectedIndex() == -1) {
selectedIndex = 0;
}
else {
selectedIndex = expressionListView.getSelectionModel().getSelectedIndex();
}
Expression item = expressionListView.getSelectionModel().getSelectedItem();
expressions.remove(expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().remove(expressionListView.getSelectionModel().getSelectedItem());
// Opens the Editor Window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/editorWindow.fxml"));
Stage editorStage = new Stage();
editorStage.setTitle("Regex builder - Expression editor");
editorStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
editorStage.initModality(Modality.APPLICATION_MODAL);
editorStage.setResizable(false);
editorStage.show();
// Loads all the appropriate data into the editor window
EditorWindowController editorController = StageConfig.getEditorWindowController();
for (Element e: item.getElements()) {
editorController.getElements().add(e);
editorController.getElementListView().getItems().add(e);
}
// Takes the quantifier from the expression
Quantifier q = item.getQuantifier();
editorController.setQuantifier(q);
// Creates patterns to match and find the numbers, if they exist
Pattern exactDigitPattern = Pattern.compile("\\{(\\d+)\\}");
Pattern rangeDigitPattern = Pattern.compile("\\{(\\d+),(\\d+)\\}");
Pattern minDigitPattern = Pattern.compile("\\{(\\d+),\\}");
Matcher mExactDigit = exactDigitPattern.matcher(q.getSymbol());
Matcher mRangeDigit = rangeDigitPattern.matcher(q.getSymbol());
Matcher mMinDigit = minDigitPattern.matcher(q.getSymbol());
// Loads the appropriate data into the quantifier radio buttons and text fields
if (q.getSymbol().equals("?")) {
editorController.opt0Or1.setSelected(true);
}
else if (q.getSymbol().equals("*")) {
editorController.opt0OrMore.setSelected(true);
}
else if (q.getSymbol().equals("+")) {
editorController.opt1OrMore.setSelected(true);
}
else if (mExactDigit.matches()) {
editorController.optExactly.setSelected(true);
editorController.quantifierExactlyField.setText(mExactDigit.group(1));
}
else if (mRangeDigit.matches()) {
editorController.optRange.setSelected(true);
editorController.quantifierRangeFirstField.setText(mRangeDigit.group(1));
editorController.quantifierRangeLastField.setText(mRangeDigit.group(2));
}
else if (mMinDigit.matches()) {
editorController.optMin.setSelected(true);
editorController.quantifierMinField.setText(mMinDigit.group(1));
}
else {
editorController.optOne.setSelected(true);
}
// Loads the appropriate data into the capture group radio buttons
Group g = item.getGroup();
editorController.setGroup(g);
if (g.getStartSymbol().equals("(")) {
editorController.optCapGroup.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?:")) {
editorController.optNonCapGroup.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?=")) {
editorController.optPosLookahead.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?!")) {
editorController.optNegLookahead.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
editorController.refreshExpression();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
/**
* Updates the expression when the checkbox for first element is pressed
* @param actionEvent
*/
public void firstElementPressed(ActionEvent actionEvent) {
refreshExpression();
}
/**
* Updates the expression when the checkbox for last element is pressed
* @param actionEvent
*/
public void lastElementPressed(ActionEvent actionEvent) {
refreshExpression();
}
/**
* Copies full expression to clipboard
* @param actionEvent
*/
public void copyFullExpression(ActionEvent actionEvent) {
StringSelection stringSelection = new StringSelection(fullRegexField.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
/**
* Called when the help button is pressed
* @param actionEvent
*/
public void pressedHelpBtn(ActionEvent actionEvent) {
// Opens the help window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/helpWindow.fxml"));
Stage helpStage = new Stage();
helpStage.setTitle("Regex builder - Help menu");
helpStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
helpStage.initModality(Modality.APPLICATION_MODAL);
helpStage.setResizable(false);
helpStage.show();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
}
| UTF-8 | Java | 16,033 | java | MainWindowController.java | Java | []
| null | []
| package src;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import javafx.scene.image.Image ;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.regex.*;
public class MainWindowController {
// Non-FXML variables
private ArrayList<Expression> expressions;
private int selectedIndex;
// FXML Elements
public Label expressionLabel;
public TextField fullRegexField;
public ListView<Expression> expressionListView;
public Expression ex;
public Button addExpressionBtn;
public Button removeExpressionBtn;
public Button moveUpBtn;
public Button moveDownBtn;
public Button editExpressionBtn;
public Button helpBtn;
public CheckBox firstElementCheckBox;
public CheckBox lastElementCheckBox;
@FXML
/**
* Method called by FXML when the window is started
*/
public void initialize() {
// Updated mainWindowController in the StageConfig class so the editor window controller can later access it
StageConfig.setMainWindowController(this);
expressions = new ArrayList<Expression>();
selectedIndex = 0;
// Cell Factory to allow the ListView to store whole Expression objects while displaying a full description of the expression
expressionListView.setCellFactory(new Callback<ListView<Expression>, ListCell<Expression>>() {
@Override
public ListCell<Expression> call(ListView<Expression> listView) {
ListCell<Expression> cell = new ListCell<Expression>(){
@Override
protected void updateItem(Expression e, boolean empty){
super.updateItem(e, empty);
String fullDesc = "";
if (e != null) {
if (e.getGroup().getDesc().equals("")){
fullDesc += "Not a capture group\n";
}
else {
fullDesc += e.getGroup().getDesc() + " (" + e.getQuantifier().getDesc().toLowerCase() + ") containing:\n";
}
for (Element element : e.getElements()) {
fullDesc += "\t" + element.getDesc() + "\n";
fullDesc += "\t\t" + element.getQuantifier().getDesc() + "\n";
}
setText(fullDesc);
}
else {
setText("");
}
}
};
return cell;
}
});
}
/**
* Getter used to access the list of expressions
* @return arraylist of expressions
*/
public ArrayList<Expression> getExpressions() {
return expressions;
}
/**
* Used to change the current expressions in the list of expressions
* @param expressions
*/
public void setExpressions(ArrayList<Expression> expressions) {
this.expressions = expressions;
}
/**
* Getter used to access the selected item index
* @return the index
*/
public int getSelectedIndex() {
return selectedIndex;
}
/**
* Used to change the current selectedIndex in the list of expressions
* @param selectedIndex
*/
public void setSelectedIndex(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
/**
* Called every time a change is made to the expressions list. Updates the string in the textField
* @return A string with the full expression
*/
public String refreshExpression() {
fullRegexField.setText("");
String fullExp = "";
if (firstElementCheckBox.isSelected()) {
fullExp+="^";
}
for (Expression e : expressions) {
fullExp+=e.compileExpression();
}
if (lastElementCheckBox.isSelected()) {
fullExp+="$";
}
fullRegexField.setText(fullExp);
return fullExp;
}
/**
* Called when the add expression button is pressed (FXML event listener)
* @param actionEvent
*/
public void pressedAddExpression(ActionEvent actionEvent) {
// Stores the selected index so the created expression is added in the correct place
if (expressionListView.getSelectionModel().getSelectedIndex() == -1) {
selectedIndex = 0;
}
else {
selectedIndex = expressionListView.getSelectionModel().getSelectedIndex() + 1;
}
// Opens the Editor Window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/editorWindow.fxml"));
Stage editorStage = new Stage();
editorStage.setTitle("Regex builder - Expression editor");
editorStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
editorStage.initModality(Modality.APPLICATION_MODAL);
editorStage.setResizable(false);
editorStage.show();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
/**
* Removes selected expression from ListView and ArrayList
* @param actionEvent
*/
public void pressedRemoveExpression(ActionEvent actionEvent) {
int index = expressionListView.getSelectionModel().getSelectedIndex();
int size = expressionListView.getItems().size();
expressions.remove(expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().remove(expressionListView.getSelectionModel().getSelectedItem());
// Automatically selects the expression that takes its place or the last expression
if (index < size-1) {
expressionListView.getSelectionModel().select(index);
}
else {
expressionListView.getSelectionModel().select(index-1);
}
refreshExpression();
}
/**
* Moves the selected expression up in the list
* @param actionEvent
*/
public void pressedMoveUp(ActionEvent actionEvent) {
Expression item = expressionListView.getSelectionModel().getSelectedItem();
int index = expressionListView.getSelectionModel().getSelectedIndex();
if (index > 0) {
expressionListView.getItems().remove(index);
expressionListView.getItems().add(index-1, item);
expressionListView.getSelectionModel().select(index-1);
expressions.remove(index);
expressions.add(index-1, item);
}
refreshExpression();
}
/**
* Moves the selected expression down in the list
* @param actionEvent
*/
public void pressedMoveDown(ActionEvent actionEvent) {
Expression item = expressionListView.getSelectionModel().getSelectedItem();
int index = expressionListView.getSelectionModel().getSelectedIndex();
if (index < expressionListView.getItems().size() - 1) {
expressionListView.getItems().remove(index);
expressionListView.getItems().add(index+1, item);
expressionListView.getSelectionModel().select(index+1);
expressions.remove(index);
expressions.add(index+1, item);
}
refreshExpression();
}
/**
* Duplicates the selected expression
* @param actionEvent
*/
public void pressedDuplicateExpression(ActionEvent actionEvent) {
int index = expressionListView.getSelectionModel().getSelectedIndex();
// Creates a deep copy of the selected object (by value)
Expression e = new Expression((Expression) expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().add(index+1, e);
expressions.add(index+1, e);
expressionListView.getSelectionModel().select(index+1);
refreshExpression();
}
/**
* Opens the editor window and loads the selected expression's data
* @param actionEvent
*/
public void pressedEditExpression(ActionEvent actionEvent) {
// Stores the selected index so the created expression is added in the correct place
if (expressionListView.getSelectionModel().getSelectedIndex() == -1) {
selectedIndex = 0;
}
else {
selectedIndex = expressionListView.getSelectionModel().getSelectedIndex();
}
Expression item = expressionListView.getSelectionModel().getSelectedItem();
expressions.remove(expressionListView.getSelectionModel().getSelectedItem());
expressionListView.getItems().remove(expressionListView.getSelectionModel().getSelectedItem());
// Opens the Editor Window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/editorWindow.fxml"));
Stage editorStage = new Stage();
editorStage.setTitle("Regex builder - Expression editor");
editorStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
editorStage.initModality(Modality.APPLICATION_MODAL);
editorStage.setResizable(false);
editorStage.show();
// Loads all the appropriate data into the editor window
EditorWindowController editorController = StageConfig.getEditorWindowController();
for (Element e: item.getElements()) {
editorController.getElements().add(e);
editorController.getElementListView().getItems().add(e);
}
// Takes the quantifier from the expression
Quantifier q = item.getQuantifier();
editorController.setQuantifier(q);
// Creates patterns to match and find the numbers, if they exist
Pattern exactDigitPattern = Pattern.compile("\\{(\\d+)\\}");
Pattern rangeDigitPattern = Pattern.compile("\\{(\\d+),(\\d+)\\}");
Pattern minDigitPattern = Pattern.compile("\\{(\\d+),\\}");
Matcher mExactDigit = exactDigitPattern.matcher(q.getSymbol());
Matcher mRangeDigit = rangeDigitPattern.matcher(q.getSymbol());
Matcher mMinDigit = minDigitPattern.matcher(q.getSymbol());
// Loads the appropriate data into the quantifier radio buttons and text fields
if (q.getSymbol().equals("?")) {
editorController.opt0Or1.setSelected(true);
}
else if (q.getSymbol().equals("*")) {
editorController.opt0OrMore.setSelected(true);
}
else if (q.getSymbol().equals("+")) {
editorController.opt1OrMore.setSelected(true);
}
else if (mExactDigit.matches()) {
editorController.optExactly.setSelected(true);
editorController.quantifierExactlyField.setText(mExactDigit.group(1));
}
else if (mRangeDigit.matches()) {
editorController.optRange.setSelected(true);
editorController.quantifierRangeFirstField.setText(mRangeDigit.group(1));
editorController.quantifierRangeLastField.setText(mRangeDigit.group(2));
}
else if (mMinDigit.matches()) {
editorController.optMin.setSelected(true);
editorController.quantifierMinField.setText(mMinDigit.group(1));
}
else {
editorController.optOne.setSelected(true);
}
// Loads the appropriate data into the capture group radio buttons
Group g = item.getGroup();
editorController.setGroup(g);
if (g.getStartSymbol().equals("(")) {
editorController.optCapGroup.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?:")) {
editorController.optNonCapGroup.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?=")) {
editorController.optPosLookahead.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
else if (g.getStartSymbol().equals("(?!")) {
editorController.optNegLookahead.setSelected(true);
editorController.quantifierPane.setDisable(false);
}
editorController.refreshExpression();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
/**
* Updates the expression when the checkbox for first element is pressed
* @param actionEvent
*/
public void firstElementPressed(ActionEvent actionEvent) {
refreshExpression();
}
/**
* Updates the expression when the checkbox for last element is pressed
* @param actionEvent
*/
public void lastElementPressed(ActionEvent actionEvent) {
refreshExpression();
}
/**
* Copies full expression to clipboard
* @param actionEvent
*/
public void copyFullExpression(ActionEvent actionEvent) {
StringSelection stringSelection = new StringSelection(fullRegexField.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
/**
* Called when the help button is pressed
* @param actionEvent
*/
public void pressedHelpBtn(ActionEvent actionEvent) {
// Opens the help window
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("src/helpWindow.fxml"));
Stage helpStage = new Stage();
helpStage.setTitle("Regex builder - Help menu");
helpStage.setScene(new Scene(root));
// APPLICATION_MODAL disables this window while the other one is open
helpStage.initModality(Modality.APPLICATION_MODAL);
helpStage.setResizable(false);
helpStage.show();
}
catch (IOException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("We could not open the window");
alert.setContentText("There was an error when opening the window, sorry about the inconvenience");
alert.showAndWait();
}
}
}
| 16,033 | 0.608121 | 0.606437 | 408 | 38.29657 | 28.69315 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 1 |
bc005977a83e2afeb960e2ce3c5b11b20ff229d0 | 31,138,512,965,409 | e89dd51b822dc82f84ce8709f4cc721bc7952ae0 | /src/main/java/com/servegame/bl4de/Animation/controller/AnimationController.java | 0fd389bd3e981502702efb556e8e1775f4bc6ec3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | TheCahyag/MinecraftAnimation | https://github.com/TheCahyag/MinecraftAnimation | e2c523924ec0752ddb904f61d7de08437c36487a | 087b068349c991d91517dd7050540c40ae4fd807 | refs/heads/sponge-api/7 | 2021-07-12T17:10:29.919000 | 2021-04-01T20:03:07 | 2021-04-01T20:03:07 | 97,891,240 | 5 | 0 | MIT | false | 2020-04-14T21:54:39 | 2017-07-21T01:07:44 | 2020-01-13T22:19:20 | 2020-04-14T21:54:38 | 585 | 2 | 0 | 4 | Java | false | false | package com.servegame.bl4de.Animation.controller;
import com.servegame.bl4de.Animation.AnimationPlugin;
import com.servegame.bl4de.Animation.data.PreparedStatements;
import com.servegame.bl4de.Animation.model.Animation;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static com.servegame.bl4de.Animation.util.Util.*;
/**
* File: AnimationController.java
*
* @author Brandon Bires-Navel (brandonnavel@outlook.com)
*/
public class AnimationController {
/**
* Stops all animations, usually ran when the server is shutting down.
*/
public static void stopAllAnimations(){
AnimationPlugin.taskManager.stopAllAnimations();
}
/**
* TODO
* @param animation
* @return
*/
public static Text linkToAnimationInfo(Animation animation){
return Text.builder()
.append(Text.of(NAME_COLOR, COMMAND_STYLE, animation.getAnimationName()))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " info"))
.build();
}
/**
* TODO
* @param animation
* @return
*/
public static Text getButtonsForAnimation(Animation animation){
return Text.builder()
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "DELETE",
PRIMARY_COLOR, "] "))
.onClick(TextActions.runCommand("/animate delete " + animation.getAnimationName()))
.build())
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "CREATE FRAME",
PRIMARY_COLOR, "] "))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " frame create"))
.build())
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "LIST FRAMES",
PRIMARY_COLOR, "] | "))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " frame list"))
.build())
.build();
}
/**
* Creates the buttons that appear at the bottom of /animate list
* @return Text representing a button that allows for creating animations
*/
public static Text getButtonsForList(){
return Text.builder()
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "CREATE",
PRIMARY_COLOR, "]"))
.onClick(TextActions.suggestCommand("/animate create <name>"))
.build())
.build();
}
// Most of these methods are just calls to the PreparedStatements class
public static boolean createAnimation(Animation animation){
return PreparedStatements.createAnimation(animation);
}
public static Optional<Animation> getAnimation(String name, UUID owner){
return PreparedStatements.getAnimation(name, owner);
}
public static Optional<Animation> getBareAnimation(String name, UUID owner){
return PreparedStatements.getBareAnimation(name, owner);
}
public static ArrayList<String> getAnimationsByOwner(UUID owner) {
return PreparedStatements.getAnimationsByOwner(owner);
}
public static boolean updateAnimationStatus(Animation animation, Animation.Status status){
return PreparedStatements.updateAnimationStatus(animation, status);
}
public static boolean saveAnimation(Animation animation){
return PreparedStatements.saveAnimation(animation);
}
public static boolean saveBareAnimation(Animation animation){
return PreparedStatements.saveBareAnimation(animation);
}
public static boolean deleteAnimation(Animation animation){
return PreparedStatements.deleteAnimation(animation);
}
public static boolean refreshAnimation(String name, UUID owner){
return PreparedStatements.refreshAnimation(name, owner);
}
public static boolean renameAnimation(Animation animation, String newName){
return PreparedStatements.renameAnimation(animation, newName);
}
public static Optional<Map<UUID, ArrayList<String>>> getAllAnimations(){
return Optional.of(PreparedStatements.getAnimations());
}
public static boolean overwriteWorldUUID(Animation animation, UUID newWorldUUID){
return PreparedStatements.overwriteWorldUUID(animation, newWorldUUID);
}
}
| UTF-8 | Java | 4,991 | java | AnimationController.java | Java | [
{
"context": "**\n * File: AnimationController.java\n *\n * @author Brandon Bires-Navel (brandonnavel@outlook.com)\n */\npublic class Anima",
"end": 546,
"score": 0.9998993873596191,
"start": 527,
"tag": "NAME",
"value": "Brandon Bires-Navel"
},
{
"context": "ontroller.java\n *\n * @author Brandon Bires-Navel (brandonnavel@outlook.com)\n */\npublic class AnimationController {\n\n /**\n",
"end": 572,
"score": 0.9999337792396545,
"start": 548,
"tag": "EMAIL",
"value": "brandonnavel@outlook.com"
}
]
| null | []
| package com.servegame.bl4de.Animation.controller;
import com.servegame.bl4de.Animation.AnimationPlugin;
import com.servegame.bl4de.Animation.data.PreparedStatements;
import com.servegame.bl4de.Animation.model.Animation;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static com.servegame.bl4de.Animation.util.Util.*;
/**
* File: AnimationController.java
*
* @author <NAME> (<EMAIL>)
*/
public class AnimationController {
/**
* Stops all animations, usually ran when the server is shutting down.
*/
public static void stopAllAnimations(){
AnimationPlugin.taskManager.stopAllAnimations();
}
/**
* TODO
* @param animation
* @return
*/
public static Text linkToAnimationInfo(Animation animation){
return Text.builder()
.append(Text.of(NAME_COLOR, COMMAND_STYLE, animation.getAnimationName()))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " info"))
.build();
}
/**
* TODO
* @param animation
* @return
*/
public static Text getButtonsForAnimation(Animation animation){
return Text.builder()
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "DELETE",
PRIMARY_COLOR, "] "))
.onClick(TextActions.runCommand("/animate delete " + animation.getAnimationName()))
.build())
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "CREATE FRAME",
PRIMARY_COLOR, "] "))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " frame create"))
.build())
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "LIST FRAMES",
PRIMARY_COLOR, "] | "))
.onClick(TextActions.runCommand("/animate " + animation.getAnimationName() + " frame list"))
.build())
.build();
}
/**
* Creates the buttons that appear at the bottom of /animate list
* @return Text representing a button that allows for creating animations
*/
public static Text getButtonsForList(){
return Text.builder()
.append(Text.builder()
.append(Text.of(PRIMARY_COLOR, "[",
ACTION_COLOR, COMMAND_HOVER, "CREATE",
PRIMARY_COLOR, "]"))
.onClick(TextActions.suggestCommand("/animate create <name>"))
.build())
.build();
}
// Most of these methods are just calls to the PreparedStatements class
public static boolean createAnimation(Animation animation){
return PreparedStatements.createAnimation(animation);
}
public static Optional<Animation> getAnimation(String name, UUID owner){
return PreparedStatements.getAnimation(name, owner);
}
public static Optional<Animation> getBareAnimation(String name, UUID owner){
return PreparedStatements.getBareAnimation(name, owner);
}
public static ArrayList<String> getAnimationsByOwner(UUID owner) {
return PreparedStatements.getAnimationsByOwner(owner);
}
public static boolean updateAnimationStatus(Animation animation, Animation.Status status){
return PreparedStatements.updateAnimationStatus(animation, status);
}
public static boolean saveAnimation(Animation animation){
return PreparedStatements.saveAnimation(animation);
}
public static boolean saveBareAnimation(Animation animation){
return PreparedStatements.saveBareAnimation(animation);
}
public static boolean deleteAnimation(Animation animation){
return PreparedStatements.deleteAnimation(animation);
}
public static boolean refreshAnimation(String name, UUID owner){
return PreparedStatements.refreshAnimation(name, owner);
}
public static boolean renameAnimation(Animation animation, String newName){
return PreparedStatements.renameAnimation(animation, newName);
}
public static Optional<Map<UUID, ArrayList<String>>> getAllAnimations(){
return Optional.of(PreparedStatements.getAnimations());
}
public static boolean overwriteWorldUUID(Animation animation, UUID newWorldUUID){
return PreparedStatements.overwriteWorldUUID(animation, newWorldUUID);
}
}
| 4,961 | 0.623322 | 0.62232 | 134 | 36.246269 | 31.506796 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507463 | false | false | 1 |
ca87e7348a5cac1ff433f78b7241b949f28cd26e | 15,960,098,541,586 | ad4e6d501a17df445c298078c54fce52a832b45c | /android/src/com/artack2/MainActivity.java | 1aaca6313983accaf63e5acc4a500b4406f1aa77 | []
| no_license | MrBlackDog/MBDartackOutDoor | https://github.com/MrBlackDog/MBDartackOutDoor | 8563c67be18592af43998e9a6f027f377ab538b1 | 931a55a1a80afe61d1e81556b1176389a0e0c69a | refs/heads/master | 2020-10-01T04:38:24.660000 | 2019-12-11T20:44:31 | 2019-12-11T20:44:31 | 227,457,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.artack2;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.TextView;
import com.badlogic.gdx.math.Vector3;
import com.google.location.lbs.gnss.gps.pseudorange.Ecef2LlaConverter;
import com.google.location.lbs.gnss.gps.pseudorange.Lla2EcefConverter;
import java.io.IOException;
//import androidx.annotation.NonNull;
//import androidx.core.app.ActivityCompat;
public class MainActivity extends Activity {
Ecef2LlaConverter.GeodeticLlaValues geodeticLlaValues;
int PERMISSION_REQUEST_CODE;
private Context mContext = this;
TextView tvEnabledGPS;
TextView tvStatusGPS;
TextView tvLocationGPS;
TextView tvEnabledNet;
TextView tvStatusNet;
TextView tvLocationNet;
private LocationManager locationManager;
StringBuilder sbGPS = new StringBuilder();
StringBuilder sbNet = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//checkPermission();
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
checkEnabled();
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (Cam.startPos != null) {
Intent intent = new Intent(mContext, AndroidLauncher.class);
mContext.startActivity(intent);
}
showLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
checkEnabled();
}
@Override
public void onProviderEnabled(String provider) {
checkEnabled();
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
showLocation(locationManager.getLastKnownLocation(provider));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
tvStatusGPS.setText("Status: " + String.valueOf(status));
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
tvStatusNet.setText("Status: " + String.valueOf(status));
}
}
};
private void showLocation(Location location) {
if (location == null)
return;
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
tvLocationGPS.setText(formatLocation(location));
} else if (location.getProvider().equals(
LocationManager.NETWORK_PROVIDER)) {
tvLocationNet.setText(formatLocation(location));
}
}
private String formatLocation(Location location) {
if (location == null)
return "";
geodeticLlaValues =new Ecef2LlaConverter.GeodeticLlaValues( Math.toRadians(location.getLatitude()), Math.toRadians(location.getLongitude()),location.getAltitude());
double[] positionEcefMeters = Lla2EcefConverter.convertFromLlaToEcefMeters(geodeticLlaValues);
// Cam.startPos = new Vector3( (float) positionEcefMeters[0], (float) positionEcefMeters[1], (float) positionEcefMeters[2]);
Cam.startPos = new Vector3( (float) positionEcefMeters[0], (float) positionEcefMeters[1], 0);
return String.format(
"Coordinates: x = %1$.4f, y = %2$.4f, z = %3$.4f",
positionEcefMeters[0], positionEcefMeters[1],positionEcefMeters[2]);
/* return String.format(
"Coordinates: lat = %1$.4, lon = %2$.4f, alt = %2$.4f",
location.getLatitude(), location.getLongitude(), location.getAltitude());*/
}
private void checkEnabled() {
tvEnabledGPS.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER));
tvEnabledNet.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
public void onClickLocationSettings(View view) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
};
/* public void checkPermission(){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
/* ||ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Permission request").setMessage(R.string.Request_Permission).setCancelable(false)
.setNegativeButton("ОК",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.permission();
}
});
AlertDialog alert = builder.create();
alert.show();
// perm();
}
}
// Permission has already been granted, continue
}
/* public void permission(){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Light_Dialog);
} else {
builder = new AlertDialog.Builder(this);
}
{
Log.e("PERMISSIONS", "NOT GRANTED");
// Permission не предоставлены
// Должны ли показать пользователю объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA) ||
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION) ||
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
builder.setTitle(R.string.Permission_Error); // заголовок
builder.setMessage(R.string.Permission_Explanation); // сообщение
builder.setPositiveButton("Agree", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
MainActivity.this.RequestPermission();
}
});
builder.setNegativeButton("Disagree", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
System.exit(0);
}
});
builder.setCancelable(false);
AlertDialog alert = builder.create();
alert.show();
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
Log.e("PERMISSIONS", "NOEXPLANATION");
// No explanation needed; request the permission
RequestPermission();
// REQUEST_RESULT is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
public void RequestPermission(){
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.CAMERA
// Manifest.permission.ACCESS_FINE_LOCATION,
//Manifest.permission.ACCESS_COARSE_LOCATION},
},PERMISSION_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) // Permissions получены
return;
else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA))
// Permissions не получены, закрываем приложение
permission();
else
System.exit(0);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults); }*/
} | UTF-8 | Java | 12,294 | java | MainActivity.java | Java | [
{
"context": "package com.artack2;\r\n\r\nimport android.Manifest;\r\nimport android.app",
"end": 18,
"score": 0.598369836807251,
"start": 15,
"tag": "USERNAME",
"value": "ack"
}
]
| null | []
| package com.artack2;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.TextView;
import com.badlogic.gdx.math.Vector3;
import com.google.location.lbs.gnss.gps.pseudorange.Ecef2LlaConverter;
import com.google.location.lbs.gnss.gps.pseudorange.Lla2EcefConverter;
import java.io.IOException;
//import androidx.annotation.NonNull;
//import androidx.core.app.ActivityCompat;
public class MainActivity extends Activity {
Ecef2LlaConverter.GeodeticLlaValues geodeticLlaValues;
int PERMISSION_REQUEST_CODE;
private Context mContext = this;
TextView tvEnabledGPS;
TextView tvStatusGPS;
TextView tvLocationGPS;
TextView tvEnabledNet;
TextView tvStatusNet;
TextView tvLocationNet;
private LocationManager locationManager;
StringBuilder sbGPS = new StringBuilder();
StringBuilder sbNet = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//checkPermission();
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
checkEnabled();
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (Cam.startPos != null) {
Intent intent = new Intent(mContext, AndroidLauncher.class);
mContext.startActivity(intent);
}
showLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
checkEnabled();
}
@Override
public void onProviderEnabled(String provider) {
checkEnabled();
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
showLocation(locationManager.getLastKnownLocation(provider));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
tvStatusGPS.setText("Status: " + String.valueOf(status));
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
tvStatusNet.setText("Status: " + String.valueOf(status));
}
}
};
private void showLocation(Location location) {
if (location == null)
return;
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
tvLocationGPS.setText(formatLocation(location));
} else if (location.getProvider().equals(
LocationManager.NETWORK_PROVIDER)) {
tvLocationNet.setText(formatLocation(location));
}
}
private String formatLocation(Location location) {
if (location == null)
return "";
geodeticLlaValues =new Ecef2LlaConverter.GeodeticLlaValues( Math.toRadians(location.getLatitude()), Math.toRadians(location.getLongitude()),location.getAltitude());
double[] positionEcefMeters = Lla2EcefConverter.convertFromLlaToEcefMeters(geodeticLlaValues);
// Cam.startPos = new Vector3( (float) positionEcefMeters[0], (float) positionEcefMeters[1], (float) positionEcefMeters[2]);
Cam.startPos = new Vector3( (float) positionEcefMeters[0], (float) positionEcefMeters[1], 0);
return String.format(
"Coordinates: x = %1$.4f, y = %2$.4f, z = %3$.4f",
positionEcefMeters[0], positionEcefMeters[1],positionEcefMeters[2]);
/* return String.format(
"Coordinates: lat = %1$.4, lon = %2$.4f, alt = %2$.4f",
location.getLatitude(), location.getLongitude(), location.getAltitude());*/
}
private void checkEnabled() {
tvEnabledGPS.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER));
tvEnabledNet.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
public void onClickLocationSettings(View view) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
};
/* public void checkPermission(){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
/* ||ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Permission request").setMessage(R.string.Request_Permission).setCancelable(false)
.setNegativeButton("ОК",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.permission();
}
});
AlertDialog alert = builder.create();
alert.show();
// perm();
}
}
// Permission has already been granted, continue
}
/* public void permission(){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Light_Dialog);
} else {
builder = new AlertDialog.Builder(this);
}
{
Log.e("PERMISSIONS", "NOT GRANTED");
// Permission не предоставлены
// Должны ли показать пользователю объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA) ||
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION) ||
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
builder.setTitle(R.string.Permission_Error); // заголовок
builder.setMessage(R.string.Permission_Explanation); // сообщение
builder.setPositiveButton("Agree", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
MainActivity.this.RequestPermission();
}
});
builder.setNegativeButton("Disagree", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
System.exit(0);
}
});
builder.setCancelable(false);
AlertDialog alert = builder.create();
alert.show();
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
Log.e("PERMISSIONS", "NOEXPLANATION");
// No explanation needed; request the permission
RequestPermission();
// REQUEST_RESULT is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
public void RequestPermission(){
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.CAMERA
// Manifest.permission.ACCESS_FINE_LOCATION,
//Manifest.permission.ACCESS_COARSE_LOCATION},
},PERMISSION_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) // Permissions получены
return;
else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA))
// Permissions не получены, закрываем приложение
permission();
else
System.exit(0);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults); }*/
} | 12,294 | 0.602101 | 0.597751 | 266 | 43.812031 | 36.855366 | 301 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.635338 | false | false | 1 |
c71c8412cdacec3d3b3649885dd40a707192f28a | 15,960,098,541,530 | 685b1e26af64321a29addeee9a8330004f30ca3f | /IdeaProjects/workspace/conference-demo/src/main/java/com/exam/conferencedemo/repositories/SpeakerRepository.java | 808733bad8a2990890eeceb926539fe247687675 | []
| no_license | navyashreegb99/web_projects | https://github.com/navyashreegb99/web_projects | 3bbc4d00c9f158f055de6429574c043f1b5d3222 | c576aae573d81cc2e258accf81386b911d4c9a2e | refs/heads/master | 2023-04-12T20:58:22.626000 | 2021-05-19T17:29:52 | 2021-05-19T17:38:30 | 364,818,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exam.conferencedemo.repositories;
import com.exam.conferencedemo.modules.Speaker;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SpeakerRepository extends JpaRepository<Speaker, Long> {
}
| UTF-8 | Java | 234 | java | SpeakerRepository.java | Java | []
| null | []
| package com.exam.conferencedemo.repositories;
import com.exam.conferencedemo.modules.Speaker;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SpeakerRepository extends JpaRepository<Speaker, Long> {
}
| 234 | 0.846154 | 0.846154 | 7 | 32.42857 | 29.090288 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 1 |
245c44496075ae2a56ee74d8ec478908c7fe7e5e | 2,379,411,882,119 | 3e75b2d852aa7e4746fd137fc4efd01bb5de8bf1 | /src/main/java/com/icodici/minicrypto/AbstractKey.java | 740b305d16973311f0539679c01f2ff9d05616ed | []
| no_license | UniversaBlockchain/minicrypto-java | https://github.com/UniversaBlockchain/minicrypto-java | 2ffaa2f3e7f302d223e244fc9195cee63d391db8 | 5f08ee291d14b63acb520ad6a4bdf9b95cdccb74 | refs/heads/master | 2020-04-05T16:20:09.155000 | 2019-07-02T03:55:20 | 2019-07-02T03:55:20 | 157,007,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2017 Sergey Chernov, iCodici S.n.C, All Rights Reserved
*
* Written by Sergey Chernov <real.net.sergeych@gmail.com>, August 2017.
*
*/
package com.icodici.minicrypto;
import com.icodici.minicrypto.digest.Digest;
import com.icodici.minicrypto.digest.HMAC;
import com.icodici.minicrypto.tools.Do;
import com.icodici.minicrypto.utils.Base64;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* All the functions that some key should be able to perform. The default implementation throws {@link
* UnsupportedOperationException} - this is a valid behaviour for the function that the key is not able to perform.
* Well, there could be keys that do nothing too. Just for ;)
* <p>
* Created by net.sergeych on 17.12.16.
*/
public abstract class AbstractKey implements KeyMatcher {
public static final int FINGERPRINT_SHA256 = 7;
public static final int FINGERPRINT_SHA384 = 8;
protected KeyInfo keyInfo;
public byte[] encrypt(byte[] plain) throws EncryptionError {
throw new UnsupportedOperationException("this key can't encrypt");
}
public byte[] decrypt(byte[] plain) throws EncryptionError {
throw new UnsupportedOperationException("this key can't decrypt");
}
public byte[] sign(InputStream input, HashType hashType) throws EncryptionError, IOException {
throw new UnsupportedOperationException("this key can't sign");
}
public byte[] sign(byte[] input, HashType hashType) throws EncryptionError {
try {
return sign(new ByteArrayInputStream(input), hashType);
} catch (IOException e) {
throw new RuntimeException("unexpected IO exception while signing", e);
}
}
public boolean verify(InputStream input, byte[] signature, HashType hashType) throws
EncryptionError, IOException {
throw new UnsupportedOperationException("this key can not verify signatures");
}
public boolean verify(byte[] input, byte[] signature, HashType hashType) throws
EncryptionError {
try {
return verify(new ByteArrayInputStream(input), signature, hashType);
} catch (IOException e) {
throw new RuntimeException("unexpected IO exception", e);
}
}
static Charset utf8 = Charset.forName("utf-8");
public boolean verify(String input, byte[] signature, HashType hashType) throws
EncryptionError {
return verify(input.getBytes(utf8), signature, hashType);
}
public KeyInfo info() {
return keyInfo;
}
public byte[] packedInfo() {
return info().pack();
}
public byte[] pack() {
throw new UnsupportedOperationException("not implemented");
}
public String packToBase64String() {
return Base64.encodeString(pack());
}
public void unpack(byte[] bytes) throws EncryptionError {
throw new UnsupportedOperationException("not implemented");
}
/**
* If it is an instance of the private key, it will return true, then {@link #getPublicKey()} must return valid
* key.
*
* @return
*/
public boolean canSign() {
return false;
}
public boolean isPublic() {
return false;
}
public boolean isPrivate() {
return false;
}
/**
* Return valid public key, for example self, or raise the exception. This implementation returns self if {@link
* #isPublic()} or throws an exception.
*
* @return
*/
public AbstractKey getPublicKey() {
if (isPublic())
return this;
throw new UnsupportedOperationException("this key can't provide public key");
}
public boolean matchType(AbstractKey other) {
return info().matchType(other.info());
}
public boolean matchTag(AbstractKey other) {
return info().matchTag(other.info());
}
public void setTag(String tag) {
try {
setTag(tag.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("utf8 is not supported?");
}
}
public void setTag(byte[] tag) {
info().setTag(tag);
}
@Override
public String toString() {
AbstractKey k = this instanceof PrivateKey ? getPublicKey() : this;
return info().toString() + ":" + info().getBase64Tag();
}
/**
* The fingerprint of the key is a uniqie sequence of bytes that matches the key without compromising it. In fact,
* only public keys can have it, for symmetric keys the fingerprint will compromise it.
* <p>
* Therefore, the private key fingerprint is its public key fingerprint. The public key fingerprint is calculated
* using some hash over it's parameters, see {@link PublicKey#fingerprint()}
*
* @return
*/
public byte[] fingerprint() {
throw new RuntimeException("this key does not support fingerprints");
}
/**
* Arbitrary fingerprint calculation. As the digest may be different adn it might be useful to include more
* information than a key to it, it is possible to update some digest instance with key data.
* <p>
* Create any digest you need and call this method to update it with a ket data.
* <p>
* This can and should be used to obtain higher-order composite fingerprints for high security setups.
*
* @return same digest instance (to chain calls)
*/
public Digest updateDigestWithKeyComponents(Digest digest) {
throw new RuntimeException("this key does not support fingerprints");
}
/**
* Create a random (e.g. every call a different) sequence of bytes that identidy this key. There can almost infinite
* number if anonynous ids for e key (more than 1.0E77), so it is really anonymous way to identify some key. The
* anonymousId for public and private keys are the same.
* <p>
* Anonymous ID size is 64 bytes: first are 32 random bytes, last are HMAC(key, sha256) of these random bytes.
* <p>
* The most important thing about anonymous ids is that every time this call generates new id for the same key,
* providing anonymous but exact identification of a key.
* <p>
* To check that the key matches some anonymousId, use {@link #matchAnonymousId(byte[])}.
* <p>
* Therefore, the private key fingerprint is its public key fingerprint. The public key fingerprint is calculated
* using some hash over it's parameters, see {@link PublicKey#fingerprint()}
*
* @return
*/
public byte[] createAnonymousId() {
byte[] rvector = Do.randomBytes(32);
HMAC hmac = new HMAC(fingerprint());
hmac.update(rvector);
byte[] result = new byte[64];
System.arraycopy(rvector, 0, result, 0, 32);
System.arraycopy(hmac.digest(), 0, result, 32, 32);
return result;
}
/**
* Check that the packed anonymousId matches current key. Use {@link #createAnonymousId()} to get a random anonymous
* id for this key.
*
* @param packedId
* @return true if it matches.
* @throws IOException
*/
public boolean matchAnonymousId(byte[] packedId) throws IOException {
assert (packedId.length == 64);
HMAC hmac = new HMAC(fingerprint());
hmac.update(packedId, 0, 32);
byte[] idDigest = Arrays.copyOfRange(packedId, 32, 64);
return Arrays.equals(hmac.digest(), idDigest);
}
/**
* Generate address for the key, see {@link KeyAddress} for more.
*
* @param useSha3_384 use SHA3-384 for hash, otherwise SHA3-256
* @param keyMark some data code in 0..15 range inclusive
* @return generated address
*/
public KeyAddress address(boolean useSha3_384, int keyMark) {
return new KeyAddress(this, keyMark, useSha3_384);
}
private KeyAddress shortAddress;
public final KeyAddress getShortAddress() {
if( shortAddress == null )
shortAddress = address(false, 0);
return shortAddress;
}
private KeyAddress longAddress;
public final KeyAddress getLongAddress() {
if( longAddress == null )
longAddress = address(true, 0);
return longAddress;
}
@Override
public boolean isMatchingKey(AbstractKey key) {
return getShortAddress().isMatchingKeyAddress(key.getShortAddress());
}
@Override
public final boolean isMatchingKeyAddress(KeyAddress other) {
return other.isLong() ?
getLongAddress().isMatchingKeyAddress(other) : getShortAddress().isMatchingKeyAddress(other);
}
}
| UTF-8 | Java | 8,834 | java | AbstractKey.java | Java | [
{
"context": "/*\n * Copyright (c) 2017 Sergey Chernov, iCodici S.n.C, All Rights Reserved\n *\n * Written",
"end": 39,
"score": 0.9998788833618164,
"start": 25,
"tag": "NAME",
"value": "Sergey Chernov"
},
{
"context": "Codici S.n.C, All Rights Reserved\n *\n * Written by Sergey Chernov <real.net.sergeych@gmail.com>, August 2017.\n *\n *",
"end": 107,
"score": 0.9998798966407776,
"start": 93,
"tag": "NAME",
"value": "Sergey Chernov"
},
{
"context": " Rights Reserved\n *\n * Written by Sergey Chernov <real.net.sergeych@gmail.com>, August 2017.\n *\n */\n\npackage com.icodici.minicr",
"end": 136,
"score": 0.9999346137046814,
"start": 109,
"tag": "EMAIL",
"value": "real.net.sergeych@gmail.com"
}
]
| null | []
| /*
* Copyright (c) 2017 <NAME>, iCodici S.n.C, All Rights Reserved
*
* Written by <NAME> <<EMAIL>>, August 2017.
*
*/
package com.icodici.minicrypto;
import com.icodici.minicrypto.digest.Digest;
import com.icodici.minicrypto.digest.HMAC;
import com.icodici.minicrypto.tools.Do;
import com.icodici.minicrypto.utils.Base64;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* All the functions that some key should be able to perform. The default implementation throws {@link
* UnsupportedOperationException} - this is a valid behaviour for the function that the key is not able to perform.
* Well, there could be keys that do nothing too. Just for ;)
* <p>
* Created by net.sergeych on 17.12.16.
*/
public abstract class AbstractKey implements KeyMatcher {
public static final int FINGERPRINT_SHA256 = 7;
public static final int FINGERPRINT_SHA384 = 8;
protected KeyInfo keyInfo;
public byte[] encrypt(byte[] plain) throws EncryptionError {
throw new UnsupportedOperationException("this key can't encrypt");
}
public byte[] decrypt(byte[] plain) throws EncryptionError {
throw new UnsupportedOperationException("this key can't decrypt");
}
public byte[] sign(InputStream input, HashType hashType) throws EncryptionError, IOException {
throw new UnsupportedOperationException("this key can't sign");
}
public byte[] sign(byte[] input, HashType hashType) throws EncryptionError {
try {
return sign(new ByteArrayInputStream(input), hashType);
} catch (IOException e) {
throw new RuntimeException("unexpected IO exception while signing", e);
}
}
public boolean verify(InputStream input, byte[] signature, HashType hashType) throws
EncryptionError, IOException {
throw new UnsupportedOperationException("this key can not verify signatures");
}
public boolean verify(byte[] input, byte[] signature, HashType hashType) throws
EncryptionError {
try {
return verify(new ByteArrayInputStream(input), signature, hashType);
} catch (IOException e) {
throw new RuntimeException("unexpected IO exception", e);
}
}
static Charset utf8 = Charset.forName("utf-8");
public boolean verify(String input, byte[] signature, HashType hashType) throws
EncryptionError {
return verify(input.getBytes(utf8), signature, hashType);
}
public KeyInfo info() {
return keyInfo;
}
public byte[] packedInfo() {
return info().pack();
}
public byte[] pack() {
throw new UnsupportedOperationException("not implemented");
}
public String packToBase64String() {
return Base64.encodeString(pack());
}
public void unpack(byte[] bytes) throws EncryptionError {
throw new UnsupportedOperationException("not implemented");
}
/**
* If it is an instance of the private key, it will return true, then {@link #getPublicKey()} must return valid
* key.
*
* @return
*/
public boolean canSign() {
return false;
}
public boolean isPublic() {
return false;
}
public boolean isPrivate() {
return false;
}
/**
* Return valid public key, for example self, or raise the exception. This implementation returns self if {@link
* #isPublic()} or throws an exception.
*
* @return
*/
public AbstractKey getPublicKey() {
if (isPublic())
return this;
throw new UnsupportedOperationException("this key can't provide public key");
}
public boolean matchType(AbstractKey other) {
return info().matchType(other.info());
}
public boolean matchTag(AbstractKey other) {
return info().matchTag(other.info());
}
public void setTag(String tag) {
try {
setTag(tag.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("utf8 is not supported?");
}
}
public void setTag(byte[] tag) {
info().setTag(tag);
}
@Override
public String toString() {
AbstractKey k = this instanceof PrivateKey ? getPublicKey() : this;
return info().toString() + ":" + info().getBase64Tag();
}
/**
* The fingerprint of the key is a uniqie sequence of bytes that matches the key without compromising it. In fact,
* only public keys can have it, for symmetric keys the fingerprint will compromise it.
* <p>
* Therefore, the private key fingerprint is its public key fingerprint. The public key fingerprint is calculated
* using some hash over it's parameters, see {@link PublicKey#fingerprint()}
*
* @return
*/
public byte[] fingerprint() {
throw new RuntimeException("this key does not support fingerprints");
}
/**
* Arbitrary fingerprint calculation. As the digest may be different adn it might be useful to include more
* information than a key to it, it is possible to update some digest instance with key data.
* <p>
* Create any digest you need and call this method to update it with a ket data.
* <p>
* This can and should be used to obtain higher-order composite fingerprints for high security setups.
*
* @return same digest instance (to chain calls)
*/
public Digest updateDigestWithKeyComponents(Digest digest) {
throw new RuntimeException("this key does not support fingerprints");
}
/**
* Create a random (e.g. every call a different) sequence of bytes that identidy this key. There can almost infinite
* number if anonynous ids for e key (more than 1.0E77), so it is really anonymous way to identify some key. The
* anonymousId for public and private keys are the same.
* <p>
* Anonymous ID size is 64 bytes: first are 32 random bytes, last are HMAC(key, sha256) of these random bytes.
* <p>
* The most important thing about anonymous ids is that every time this call generates new id for the same key,
* providing anonymous but exact identification of a key.
* <p>
* To check that the key matches some anonymousId, use {@link #matchAnonymousId(byte[])}.
* <p>
* Therefore, the private key fingerprint is its public key fingerprint. The public key fingerprint is calculated
* using some hash over it's parameters, see {@link PublicKey#fingerprint()}
*
* @return
*/
public byte[] createAnonymousId() {
byte[] rvector = Do.randomBytes(32);
HMAC hmac = new HMAC(fingerprint());
hmac.update(rvector);
byte[] result = new byte[64];
System.arraycopy(rvector, 0, result, 0, 32);
System.arraycopy(hmac.digest(), 0, result, 32, 32);
return result;
}
/**
* Check that the packed anonymousId matches current key. Use {@link #createAnonymousId()} to get a random anonymous
* id for this key.
*
* @param packedId
* @return true if it matches.
* @throws IOException
*/
public boolean matchAnonymousId(byte[] packedId) throws IOException {
assert (packedId.length == 64);
HMAC hmac = new HMAC(fingerprint());
hmac.update(packedId, 0, 32);
byte[] idDigest = Arrays.copyOfRange(packedId, 32, 64);
return Arrays.equals(hmac.digest(), idDigest);
}
/**
* Generate address for the key, see {@link KeyAddress} for more.
*
* @param useSha3_384 use SHA3-384 for hash, otherwise SHA3-256
* @param keyMark some data code in 0..15 range inclusive
* @return generated address
*/
public KeyAddress address(boolean useSha3_384, int keyMark) {
return new KeyAddress(this, keyMark, useSha3_384);
}
private KeyAddress shortAddress;
public final KeyAddress getShortAddress() {
if( shortAddress == null )
shortAddress = address(false, 0);
return shortAddress;
}
private KeyAddress longAddress;
public final KeyAddress getLongAddress() {
if( longAddress == null )
longAddress = address(true, 0);
return longAddress;
}
@Override
public boolean isMatchingKey(AbstractKey key) {
return getShortAddress().isMatchingKeyAddress(key.getShortAddress());
}
@Override
public final boolean isMatchingKeyAddress(KeyAddress other) {
return other.isLong() ?
getLongAddress().isMatchingKeyAddress(other) : getShortAddress().isMatchingKeyAddress(other);
}
}
| 8,798 | 0.657799 | 0.647272 | 264 | 32.46212 | 33.116737 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462121 | false | false | 1 |
4e285dc83cd03a224784c5745f8b2ddbe16c2ec5 | 4,922,032,524,199 | 7a9058870ce78b15648a828f690c9b1ea53bf09a | /sv-modules/venta-cotizaciones/src/main/java/cl/bbr/vte/cotizaciones/exception/CotizacionesDAOException.java | 3e081906935c4a9e9eb609edac3a8cdafd7ca805 | []
| no_license | dontyvir/POC_JUMBO | https://github.com/dontyvir/POC_JUMBO | dae924b40d3e4c9e4b48afd8035689cd7ca520f3 | f2db7c5c57301f09dca709e6a8239038ade0eb17 | refs/heads/master | 2021-01-17T18:07:18.722000 | 2016-10-16T13:38:31 | 2016-10-16T13:38:31 | 71,052,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cl.bbr.vte.cotizaciones.exception;
/**
* Excepción que es lanzada en caso de error en la capa de DAO.
*
* @author BBR e-commerce & retail
*
*/
public class CotizacionesDAOException extends java.lang.Exception {
/**
* Constructor
*/
public CotizacionesDAOException() {
super("Exception, CotizacionesDAOException Detectada!!!...");
}
/**
* Constructor
*
* @param throwable
*/
public CotizacionesDAOException(Throwable throwable) {
super(throwable);
}
/**
* Constructor
*
* @param message Mensaje de exepción
*/
public CotizacionesDAOException(String message) {
super(message);
}
/**
* Constructor
*
* @param message Mensaje de exepción
* @param throwable
*/
public CotizacionesDAOException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructor
*
* @param e Excepción
*/
public CotizacionesDAOException(Exception e) {
super(e.getMessage());
}
}
| ISO-8859-1 | Java | 1,026 | java | CotizacionesDAOException.java | Java | []
| null | []
| package cl.bbr.vte.cotizaciones.exception;
/**
* Excepción que es lanzada en caso de error en la capa de DAO.
*
* @author BBR e-commerce & retail
*
*/
public class CotizacionesDAOException extends java.lang.Exception {
/**
* Constructor
*/
public CotizacionesDAOException() {
super("Exception, CotizacionesDAOException Detectada!!!...");
}
/**
* Constructor
*
* @param throwable
*/
public CotizacionesDAOException(Throwable throwable) {
super(throwable);
}
/**
* Constructor
*
* @param message Mensaje de exepción
*/
public CotizacionesDAOException(String message) {
super(message);
}
/**
* Constructor
*
* @param message Mensaje de exepción
* @param throwable
*/
public CotizacionesDAOException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructor
*
* @param e Excepción
*/
public CotizacionesDAOException(Exception e) {
super(e.getMessage());
}
}
| 1,026 | 0.639922 | 0.639922 | 55 | 16.581818 | 20.044216 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 1 |
826012228bf4155727dc3b105a93f7494ab7a3dd | 3,564,822,859,292 | 59b7a43cc846ef6d7150a5b37ff96d8f65ae2d56 | /java/src/main/java/libsvm/Kernel.java | 8805efdeb27cd568e371928463ca3df41e9ef746 | [
"BSD-3-Clause"
]
| permissive | GWASpi/libsvm | https://github.com/GWASpi/libsvm | 98f43388aad1e317fe51fbbe9b36fc1f658fc4e9 | 8448970162ba93a98c60ce7bbaef3f9b311c4e67 | refs/heads/master | 2021-01-24T15:43:35.083000 | 2016-04-21T07:44:09 | 2016-04-21T07:44:09 | 56,752,716 | 0 | 0 | null | true | 2016-04-21T07:39:41 | 2016-04-21T07:39:41 | 2016-04-21T06:48:01 | 2016-03-19T01:34:19 | 6,512 | 0 | 0 | 0 | null | null | null | package libsvm;
abstract class Kernel extends QMatrix
{
private svm_node[][] x;
/**
* The sample serial numbers.
* <code>x[i][0] with i=0...(len-1)</code>.
* This is only used in case of a precomputed kernel.
* This is merely a cache, which brings us a huge speedup,
* because we spare ourselves the repeated float2int conversion,
* and we enhance array access locality.
*/
private int[] sampleSerialNumbers;
private final double[] x_square;
// svm_parameter
private final int kernel_type;
private final int degree;
private final double gamma;
private final double coef0;
@Override
abstract float[] get_Q(int column, int len);
@Override
abstract double[] get_QD();
@Override
void swap_index(int i, int j)
{
{ // swap(svm_node[], x[i], x[j]);
svm_node[] tmp = x[i];
x[i] = x[j];
x[j] = tmp;
if (kernel_type == svm_parameter.PRECOMPUTED) {
// also swap the cached index
final int tmpIndex = sampleSerialNumbers[i];
sampleSerialNumbers[i] = sampleSerialNumbers[j];
sampleSerialNumbers[j] = tmpIndex;
}
}
if(x_square != null)
{ // swap(double, x_square[i], x_square[j]);
double tmp = x_square[i];
x_square[i] = x_square[j];
x_square[j] = tmp;
}
}
private static double powi(double base, int times)
{
double tmp = base, ret = 1.0;
for(int t=times; t>0; t/=2)
{
if(t%2==1) ret*=tmp;
tmp = tmp * tmp;
}
return ret;
}
double kernel_function(int i, int j)
{
switch(kernel_type)
{
case svm_parameter.LINEAR:
return dot(x[i],x[j]);
case svm_parameter.POLY:
return powi(gamma*dot(x[i],x[j])+coef0,degree);
case svm_parameter.RBF:
return Math.exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
case svm_parameter.SIGMOID:
return Math.tanh(gamma*dot(x[i],x[j])+coef0);
case svm_parameter.PRECOMPUTED:
return x[i][sampleSerialNumbers[j]].value;
default:
return 0; // java
}
}
/**
* Prepares to calculate the l*l kernel matrix
*/
Kernel(int l, svm_node[][] x_, svm_parameter param)
{
this.kernel_type = param.kernel_type;
this.degree = param.degree;
this.gamma = param.gamma;
this.coef0 = param.coef0;
x = x_.clone();
// extract the sample serial numbers from x
if(kernel_type == svm_parameter.PRECOMPUTED)
{
sampleSerialNumbers = new int[x.length];
for (int i = 0; i < x.length; i++) {
sampleSerialNumbers[i] = (int) x[i][0].value;
}
}
if(kernel_type == svm_parameter.RBF)
{
x_square = new double[l];
for(int i=0;i<l;i++)
x_square[i] = dot(x[i],x[i]);
}
else x_square = null;
}
static double dot(svm_node[] x, svm_node[] y)
{
double sum = 0;
int xlen = x.length;
int ylen = y.length;
int i = 0;
int j = 0;
while(i < xlen && j < ylen)
{
if(x[i].index == y[j].index)
sum += x[i++].value * y[j++].value;
else
{
if(x[i].index > y[j].index)
++j;
else
++i;
}
}
return sum;
}
/**
* For doing single kernel evaluation
*/
static double k_function(svm_node[] x, svm_node[] y,
svm_parameter param)
{
switch(param.kernel_type)
{
case svm_parameter.LINEAR:
return dot(x,y);
case svm_parameter.POLY:
return powi(param.gamma*dot(x,y)+param.coef0,param.degree);
case svm_parameter.RBF:
{
double sum = 0;
int xlen = x.length;
int ylen = y.length;
int i = 0;
int j = 0;
while(i < xlen && j < ylen)
{
if(x[i].index == y[j].index)
{
double d = x[i++].value - y[j++].value;
sum += d*d;
}
else if(x[i].index > y[j].index)
{
sum += y[j].value * y[j].value;
++j;
}
else
{
sum += x[i].value * x[i].value;
++i;
}
}
while(i < xlen)
{
sum += x[i].value * x[i].value;
++i;
}
while(j < ylen)
{
sum += y[j].value * y[j].value;
++j;
}
return Math.exp(-param.gamma*sum);
}
case svm_parameter.SIGMOID:
return Math.tanh(param.gamma*dot(x,y)+param.coef0);
case svm_parameter.PRECOMPUTED:
return x[(int)(y[0].value)].value;
default:
return 0; // java
}
}
}
| UTF-8 | Java | 4,113 | java | Kernel.java | Java | []
| null | []
| package libsvm;
abstract class Kernel extends QMatrix
{
private svm_node[][] x;
/**
* The sample serial numbers.
* <code>x[i][0] with i=0...(len-1)</code>.
* This is only used in case of a precomputed kernel.
* This is merely a cache, which brings us a huge speedup,
* because we spare ourselves the repeated float2int conversion,
* and we enhance array access locality.
*/
private int[] sampleSerialNumbers;
private final double[] x_square;
// svm_parameter
private final int kernel_type;
private final int degree;
private final double gamma;
private final double coef0;
@Override
abstract float[] get_Q(int column, int len);
@Override
abstract double[] get_QD();
@Override
void swap_index(int i, int j)
{
{ // swap(svm_node[], x[i], x[j]);
svm_node[] tmp = x[i];
x[i] = x[j];
x[j] = tmp;
if (kernel_type == svm_parameter.PRECOMPUTED) {
// also swap the cached index
final int tmpIndex = sampleSerialNumbers[i];
sampleSerialNumbers[i] = sampleSerialNumbers[j];
sampleSerialNumbers[j] = tmpIndex;
}
}
if(x_square != null)
{ // swap(double, x_square[i], x_square[j]);
double tmp = x_square[i];
x_square[i] = x_square[j];
x_square[j] = tmp;
}
}
private static double powi(double base, int times)
{
double tmp = base, ret = 1.0;
for(int t=times; t>0; t/=2)
{
if(t%2==1) ret*=tmp;
tmp = tmp * tmp;
}
return ret;
}
double kernel_function(int i, int j)
{
switch(kernel_type)
{
case svm_parameter.LINEAR:
return dot(x[i],x[j]);
case svm_parameter.POLY:
return powi(gamma*dot(x[i],x[j])+coef0,degree);
case svm_parameter.RBF:
return Math.exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
case svm_parameter.SIGMOID:
return Math.tanh(gamma*dot(x[i],x[j])+coef0);
case svm_parameter.PRECOMPUTED:
return x[i][sampleSerialNumbers[j]].value;
default:
return 0; // java
}
}
/**
* Prepares to calculate the l*l kernel matrix
*/
Kernel(int l, svm_node[][] x_, svm_parameter param)
{
this.kernel_type = param.kernel_type;
this.degree = param.degree;
this.gamma = param.gamma;
this.coef0 = param.coef0;
x = x_.clone();
// extract the sample serial numbers from x
if(kernel_type == svm_parameter.PRECOMPUTED)
{
sampleSerialNumbers = new int[x.length];
for (int i = 0; i < x.length; i++) {
sampleSerialNumbers[i] = (int) x[i][0].value;
}
}
if(kernel_type == svm_parameter.RBF)
{
x_square = new double[l];
for(int i=0;i<l;i++)
x_square[i] = dot(x[i],x[i]);
}
else x_square = null;
}
static double dot(svm_node[] x, svm_node[] y)
{
double sum = 0;
int xlen = x.length;
int ylen = y.length;
int i = 0;
int j = 0;
while(i < xlen && j < ylen)
{
if(x[i].index == y[j].index)
sum += x[i++].value * y[j++].value;
else
{
if(x[i].index > y[j].index)
++j;
else
++i;
}
}
return sum;
}
/**
* For doing single kernel evaluation
*/
static double k_function(svm_node[] x, svm_node[] y,
svm_parameter param)
{
switch(param.kernel_type)
{
case svm_parameter.LINEAR:
return dot(x,y);
case svm_parameter.POLY:
return powi(param.gamma*dot(x,y)+param.coef0,param.degree);
case svm_parameter.RBF:
{
double sum = 0;
int xlen = x.length;
int ylen = y.length;
int i = 0;
int j = 0;
while(i < xlen && j < ylen)
{
if(x[i].index == y[j].index)
{
double d = x[i++].value - y[j++].value;
sum += d*d;
}
else if(x[i].index > y[j].index)
{
sum += y[j].value * y[j].value;
++j;
}
else
{
sum += x[i].value * x[i].value;
++i;
}
}
while(i < xlen)
{
sum += x[i].value * x[i].value;
++i;
}
while(j < ylen)
{
sum += y[j].value * y[j].value;
++j;
}
return Math.exp(-param.gamma*sum);
}
case svm_parameter.SIGMOID:
return Math.tanh(param.gamma*dot(x,y)+param.coef0);
case svm_parameter.PRECOMPUTED:
return x[(int)(y[0].value)].value;
default:
return 0; // java
}
}
}
| 4,113 | 0.5823 | 0.575006 | 193 | 20.310881 | 17.162035 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.015544 | false | false | 1 |
b489912a365688820a80b6a91ea09901d9eef395 | 29,523,605,195,756 | f4898ec6d18aab900cb409d392095995517efca1 | /src/main/java/net/sf/balm/common/domain/range/DateTimeRange.java | 8077fa91bf925947fd88051aaf8690a5be489044 | [
"Apache-2.0"
]
| permissive | xuxiaowei007/balm | https://github.com/xuxiaowei007/balm | fc5a81e46767795c1c5e02a9b79c818413a092a8 | a7e563b2b0da289920d173b3742df33598f78a5c | refs/heads/master | 2020-02-29T11:47:36.002000 | 2009-11-17T12:59:34 | 2009-11-17T12:59:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.sf.balm.common.domain.range;
import java.util.Date;
/**
* Range模式,来自Martin Fowler之分析模式
*/
public class DateTimeRange {
private Date from, to;
public DateTimeRange() {
// 默认的构造器,hibernate初始化对象的时候使用
}
public DateTimeRange(Date from, Date to) {
if ((null == from) && (null == to)) {
throw new IllegalArgumentException("至少有一个参数不能为空!");
}
this.from = from;
this.to = to;
}
/**
* @hibernate.property access = "field" column = "begin"
* @return
*/
public Date getFrom() {
return this.from;
}
/**
* @hibernate.property access = "field" column = "end"
* @return
*/
public Date getTo() {
return this.to;
}
public boolean isInTheRange(Date object) {
if (null == object)
throw new IllegalArgumentException("Null object not allowed!");
if (null == from) {
return (object.compareTo(to) <= 0);
}
if (null == to) {
return (object.compareTo(from) >= 0);
}
return (object.compareTo(from) >= 0) && (object.compareTo(to) <= 0);
}
}
| UTF-8 | Java | 1,273 | java | DateTimeRange.java | Java | [
{
"context": ".range;\n\nimport java.util.Date;\n\n/**\n * Range模式,来自Martin Fowler之分析模式\n */\npublic class DateTimeRange {\n \n pr",
"end": 96,
"score": 0.9992772936820984,
"start": 83,
"tag": "NAME",
"value": "Martin Fowler"
}
]
| null | []
| package net.sf.balm.common.domain.range;
import java.util.Date;
/**
* Range模式,来自<NAME>之分析模式
*/
public class DateTimeRange {
private Date from, to;
public DateTimeRange() {
// 默认的构造器,hibernate初始化对象的时候使用
}
public DateTimeRange(Date from, Date to) {
if ((null == from) && (null == to)) {
throw new IllegalArgumentException("至少有一个参数不能为空!");
}
this.from = from;
this.to = to;
}
/**
* @hibernate.property access = "field" column = "begin"
* @return
*/
public Date getFrom() {
return this.from;
}
/**
* @hibernate.property access = "field" column = "end"
* @return
*/
public Date getTo() {
return this.to;
}
public boolean isInTheRange(Date object) {
if (null == object)
throw new IllegalArgumentException("Null object not allowed!");
if (null == from) {
return (object.compareTo(to) <= 0);
}
if (null == to) {
return (object.compareTo(from) >= 0);
}
return (object.compareTo(from) >= 0) && (object.compareTo(to) <= 0);
}
}
| 1,266 | 0.527151 | 0.52381 | 52 | 22.01923 | 20.282135 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 1 |
07ad7b50cacd9d535de53467484b8d2a641cf33c | 22,488,448,768,124 | 847b5c8d2d43ba2cb5b4ca12f5c819bff23adfc6 | /sqa-052-rest-demo-template/sqa-052-rest-demo-template/src/test/java/com/sqa/github/RetrofitDemoTest.java | a2e07c2c3dcd53fcacc84dc1f2cde8e9d1688ec5 | []
| no_license | Denisss90/restAssured-LuxTraining | https://github.com/Denisss90/restAssured-LuxTraining | 93e92c35fbce784d564d1d48551c8c7b48262fae | 47b5849e4779076ad964ac6d21ae1386b92d969f | refs/heads/main | 2023-08-23T12:52:09.250000 | 2021-10-26T08:51:14 | 2021-10-26T08:51:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sqa.github;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sqa.model.github.Issue;
import com.sqa.services.GitHubService;
import com.sqa.services.GorestService;
import com.sqa.services.LoggingInterceptor;
import com.sqa.utils.TestLogger;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import java.io.IOException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class RetrofitDemoTest implements TestLogger {
private Retrofit retrofitGit;
private Retrofit retrofitGorest;
private GitHubService gitHubService;
private GorestService gorestService;
private static final String GIT_HUB_URL = "https://api.github.com/";
private static final String GOREST_URL = "https://gorest.co.in/";
private String issueTitle = String.format("issue %s", RandomStringUtils.randomAlphabetic(5));
private String issueDescription = "Description of new issue";
public RetrofitDemoTest() {
// Базовая инициализация, сам порядок
/* HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
//.addInterceptor(new LoggingInterceptor())
.addInterceptor(interceptor)
.readTimeout(Duration.of(5, ChronoUnit.SECONDS))
.build();*/
// Json builder for line '.addConverterFactory(GsonConverterFactory.create())
Gson gson = new GsonBuilder()
.setLenient()
.create();
this.retrofitGit= new Retrofit.Builder()
.baseUrl(GIT_HUB_URL)
//This is converter only for string
.addConverterFactory(ScalarsConverterFactory.create())
// This is converter only for JSON
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
this.gitHubService = retrofitGit.create(GitHubService.class);
}
/*
01. Проверяем, что приходит 200 код в ответ на простой GET
*/
@Test
public void verifyHealthcheckTest() throws IOException {
Response<String> response=gitHubService.getZen().execute();
assertEquals(response.code(),201);
//assertEquals(gitHubService.getZen().execute().code(),200,"response code 200")
}
/*
02. Проверяем, что приходит непустое тело ответа на простой GET
*/
@Test
public void verifyDefunktBodyTest() throws IOException {
assertFalse(gitHubService.getDefunkt().execute().body().isEmpty());
}
/*
03. Проверяем, что тело ответа содержит поле, равное значению
*/
@Test
public void verifyIssuesContainNoAuthTest() throws IOException {
Response<String> response=gitHubService.getIssuesNoAuth("ilyademchenko").execute();
log(response.raw().message());
// for 2.9 version of retrofit.
assertTrue(response.errorBody().string().contains("Not Found"));
// for 2.5 version of retrofit.
//assertTrue(response.raw().message().contains("Not Found"));
}
/*
04. Проверяем, что тело ответа содержит поле после авторизации
*/
@Test
public void verifyIssuesAuthorized() throws IOException {
Response<List<Issue>> response =
gitHubService.getUsersIssues(
"Bearer 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",
"ilyademchenko"
).execute();
assertTrue(response.body().stream()
.anyMatch(issue-> issue.getTitle().equals("lux-training Vladimir")));
}
/*
05. Проверяем, что тело ответа содержит ошибку и 403 код
*/
@Test
public void verifyIssuesNoUserAgent() throws IOException {
/* Response<List<Issue>> response =
gitHubService.getUsersIssuesWithAcceptHeader(
"application/xml",
"Bearer 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",
"ilyademchenko"
).execute();
assertEquals(response.code(),200);*/
Response<List<Issue>> response =
gitHubService.getUsersIssuesWithAcceptHeader(
"application/xml",
"Bearer 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",
"ilyademchenko"
).execute();
assertEquals(response.code(),415);
}
/*
06. Проверяем, что ишью публикуется
*/
@Test
public void verifyPostIssues() throws IOException {
String body = "{\n" +
" \"title\":\"lux-training 09\",\n" +
" \"body\": \"Description of issue\"\n" +
"}";
Response<String> response =
gitHubService.postIssue(
"application/json",
"Bearer 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",
"ilyademchenko",
body)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertTrue(response.body().contains("lux-training 09"))
);
}
/*
07. Проверяем, что тело ответа содержит ошибку и 403 код
*/
@Test
public void verifyPostIssuesUrlParam() throws IOException {
}
/*
08. Проверяем, что ишью публикуется (тело запроса в POJO)
*/
@Test
public void verifyPostPojo() throws IOException {
Issue requestIssue = new Issue();
requestIssue
.setTitle(issueTitle)
.setBody(issueDescription);
Response<Issue> response =
gitHubService.postIssuePojo(
"application/json",
"Bearer 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",
"ilyademchenko",
requestIssue)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertEquals(issueTitle, response.body().getTitle()),
() -> assertEquals(issueDescription, response.body().getBody())
);
}
/*
09. Проверяем, что ишью публикуется (тело запроса в Map)
*/
@Test
public void verifyPostMap() throws IOException {
Map<String, Object> requestBody = new LinkedHashMap<>();
requestBody.put("title", issueTitle);
requestBody.put("body", issueDescription);
Response<Map<String, Object>> response =
gitHubService.postIssueMap(
"application/json",
"Bearer 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",
"ilyademchenko",
requestBody)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertEquals(issueTitle, response.body().get("title")),
() -> assertEquals(issueDescription, response.body().get("body"))
);
}
}
| UTF-8 | Java | 8,106 | java | RetrofitDemoTest.java | Java | [
{
"context": "e<String> response=gitHubService.getIssuesNoAuth(\"ilyademchenko\").execute();\n log(response.raw().message()",
"end": 3289,
"score": 0.9997599720954895,
"start": 3276,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "BJ3IKDqtGb0DKnZh2rELZi\",\n \"ilyademchenko\"\n ).execute();\n assertTrue(",
"end": 3932,
"score": 0.999770998954773,
"start": 3919,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "BJ3IKDqtGb0DKnZh2rELZi\",\n \"ilyademchenko\"\n ).execute();\n assertEqual",
"end": 4516,
"score": 0.9996614456176758,
"start": 4503,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "BJ3IKDqtGb0DKnZh2rELZi\",\n \"ilyademchenko\"\n ).execute();\n assertEqual",
"end": 4852,
"score": 0.9996474981307983,
"start": 4839,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "Gb0DKnZh2rELZi\",\n \"ilyademchenko\",\n body)\n ",
"end": 5485,
"score": 0.9996398687362671,
"start": 5472,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "Gb0DKnZh2rELZi\",\n \"ilyademchenko\",\n requestIssue)\n ",
"end": 6448,
"score": 0.99952232837677,
"start": 6435,
"tag": "USERNAME",
"value": "ilyademchenko"
},
{
"context": "Gb0DKnZh2rELZi\",\n \"ilyademchenko\",\n requestBody)\n ",
"end": 7365,
"score": 0.9995132684707642,
"start": 7352,
"tag": "USERNAME",
"value": "ilyademchenko"
}
]
| null | []
| package com.sqa.github;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sqa.model.github.Issue;
import com.sqa.services.GitHubService;
import com.sqa.services.GorestService;
import com.sqa.services.LoggingInterceptor;
import com.sqa.utils.TestLogger;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import java.io.IOException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class RetrofitDemoTest implements TestLogger {
private Retrofit retrofitGit;
private Retrofit retrofitGorest;
private GitHubService gitHubService;
private GorestService gorestService;
private static final String GIT_HUB_URL = "https://api.github.com/";
private static final String GOREST_URL = "https://gorest.co.in/";
private String issueTitle = String.format("issue %s", RandomStringUtils.randomAlphabetic(5));
private String issueDescription = "Description of new issue";
public RetrofitDemoTest() {
// Базовая инициализация, сам порядок
/* HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
//.addInterceptor(new LoggingInterceptor())
.addInterceptor(interceptor)
.readTimeout(Duration.of(5, ChronoUnit.SECONDS))
.build();*/
// Json builder for line '.addConverterFactory(GsonConverterFactory.create())
Gson gson = new GsonBuilder()
.setLenient()
.create();
this.retrofitGit= new Retrofit.Builder()
.baseUrl(GIT_HUB_URL)
//This is converter only for string
.addConverterFactory(ScalarsConverterFactory.create())
// This is converter only for JSON
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
this.gitHubService = retrofitGit.create(GitHubService.class);
}
/*
01. Проверяем, что приходит 200 код в ответ на простой GET
*/
@Test
public void verifyHealthcheckTest() throws IOException {
Response<String> response=gitHubService.getZen().execute();
assertEquals(response.code(),201);
//assertEquals(gitHubService.getZen().execute().code(),200,"response code 200")
}
/*
02. Проверяем, что приходит непустое тело ответа на простой GET
*/
@Test
public void verifyDefunktBodyTest() throws IOException {
assertFalse(gitHubService.getDefunkt().execute().body().isEmpty());
}
/*
03. Проверяем, что тело ответа содержит поле, равное значению
*/
@Test
public void verifyIssuesContainNoAuthTest() throws IOException {
Response<String> response=gitHubService.getIssuesNoAuth("ilyademchenko").execute();
log(response.raw().message());
// for 2.9 version of retrofit.
assertTrue(response.errorBody().string().contains("Not Found"));
// for 2.5 version of retrofit.
//assertTrue(response.raw().message().contains("Not Found"));
}
/*
04. Проверяем, что тело ответа содержит поле после авторизации
*/
@Test
public void verifyIssuesAuthorized() throws IOException {
Response<List<Issue>> response =
gitHubService.getUsersIssues(
"Bearer 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",
"ilyademchenko"
).execute();
assertTrue(response.body().stream()
.anyMatch(issue-> issue.getTitle().equals("lux-training Vladimir")));
}
/*
05. Проверяем, что тело ответа содержит ошибку и 403 код
*/
@Test
public void verifyIssuesNoUserAgent() throws IOException {
/* Response<List<Issue>> response =
gitHubService.getUsersIssuesWithAcceptHeader(
"application/xml",
"Bearer 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",
"ilyademchenko"
).execute();
assertEquals(response.code(),200);*/
Response<List<Issue>> response =
gitHubService.getUsersIssuesWithAcceptHeader(
"application/xml",
"Bearer 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",
"ilyademchenko"
).execute();
assertEquals(response.code(),415);
}
/*
06. Проверяем, что ишью публикуется
*/
@Test
public void verifyPostIssues() throws IOException {
String body = "{\n" +
" \"title\":\"lux-training 09\",\n" +
" \"body\": \"Description of issue\"\n" +
"}";
Response<String> response =
gitHubService.postIssue(
"application/json",
"Bearer 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",
"ilyademchenko",
body)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertTrue(response.body().contains("lux-training 09"))
);
}
/*
07. Проверяем, что тело ответа содержит ошибку и 403 код
*/
@Test
public void verifyPostIssuesUrlParam() throws IOException {
}
/*
08. Проверяем, что ишью публикуется (тело запроса в POJO)
*/
@Test
public void verifyPostPojo() throws IOException {
Issue requestIssue = new Issue();
requestIssue
.setTitle(issueTitle)
.setBody(issueDescription);
Response<Issue> response =
gitHubService.postIssuePojo(
"application/json",
"Bearer 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",
"ilyademchenko",
requestIssue)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertEquals(issueTitle, response.body().getTitle()),
() -> assertEquals(issueDescription, response.body().getBody())
);
}
/*
09. Проверяем, что ишью публикуется (тело запроса в Map)
*/
@Test
public void verifyPostMap() throws IOException {
Map<String, Object> requestBody = new LinkedHashMap<>();
requestBody.put("title", issueTitle);
requestBody.put("body", issueDescription);
Response<Map<String, Object>> response =
gitHubService.postIssueMap(
"application/json",
"Bearer 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",
"ilyademchenko",
requestBody)
.execute();
assertAll(
() -> assertEquals(201, response.code()),
() -> assertEquals(issueTitle, response.body().get("title")),
() -> assertEquals(issueDescription, response.body().get("body"))
);
}
}
| 8,106 | 0.591334 | 0.577841 | 225 | 33.257778 | 26.563723 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493333 | false | false | 1 |
8c0246b1ad9bbccc9339b828ba341101da5c0b97 | 21,517,786,221,999 | d58b5c46fc1085b57afa53b3104c2ae2b18f351d | /Amazon/src/test/java/com/amazon/footertest/FooterPageTest.java | a02fec1803cd8e023cea55630393417a05c199af | []
| no_license | TanzinaLaskar/WebAutomationBootcamp | https://github.com/TanzinaLaskar/WebAutomationBootcamp | 5b24f7fe5b479fc62a2ba791d66b1690fecad370 | 5a95602cff862606859fd6e46be056930e500c21 | refs/heads/master | 2023-06-27T05:16:28.656000 | 2021-07-12T23:21:17 | 2021-07-12T23:21:17 | 381,613,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amazon.footertest;
import com.amazon.footerpage.FooterPage;
import common.TestBase;
import org.apache.log4j.Logger;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import reporting.ExtentTestManager;
public class FooterPageTest extends TestBase {
private static final Logger logger = Logger.getLogger(FooterPageTest.class);
FooterPage footerPage;
@Test(priority = 1)
public void usersCanValidateUserCanClickCareerLink(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
footerPage.careersLink();
ExtentTestManager.log("click CareerLink properly",logger);
}
@Test(priority = 2)
public void usersCanValidateCareerLinkTitle(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
String expected = footerPage.careersLinkText();
String actual = "Amazon.jobs: Help us build Earth’s most customer-centric company.";
Assert.assertEquals(expected,actual,"Title did not Match properly");
ExtentTestManager.log("Title Find as Expected",logger);
}
@Test(priority = 2)
public void usersCanValidateBlogLinkTitle(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
String expected = footerPage.blogLinkTitle();
String actual = "About Amazon";
Assert.assertEquals(expected,actual,"Title did not Match properly");
ExtentTestManager.log("Title Find as Expected",logger);
}
}
| UTF-8 | Java | 1,547 | java | FooterPageTest.java | Java | []
| null | []
| package com.amazon.footertest;
import com.amazon.footerpage.FooterPage;
import common.TestBase;
import org.apache.log4j.Logger;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import reporting.ExtentTestManager;
public class FooterPageTest extends TestBase {
private static final Logger logger = Logger.getLogger(FooterPageTest.class);
FooterPage footerPage;
@Test(priority = 1)
public void usersCanValidateUserCanClickCareerLink(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
footerPage.careersLink();
ExtentTestManager.log("click CareerLink properly",logger);
}
@Test(priority = 2)
public void usersCanValidateCareerLinkTitle(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
String expected = footerPage.careersLinkText();
String actual = "Amazon.jobs: Help us build Earth’s most customer-centric company.";
Assert.assertEquals(expected,actual,"Title did not Match properly");
ExtentTestManager.log("Title Find as Expected",logger);
}
@Test(priority = 2)
public void usersCanValidateBlogLinkTitle(){
footerPage = PageFactory.initElements(driver, FooterPage.class);
String expected = footerPage.blogLinkTitle();
String actual = "About Amazon";
Assert.assertEquals(expected,actual,"Title did not Match properly");
ExtentTestManager.log("Title Find as Expected",logger);
}
}
| 1,547 | 0.724919 | 0.72233 | 46 | 32.586956 | 28.243179 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717391 | false | false | 1 |
e01f3e9619da2222fe86fd6097387800a71787d8 | 21,517,786,223,632 | 6974055f8fda72b6110f8d4fc30aec0fc289dd14 | /iox-ili-master/src/main/java/ch/interlis/iox_j/validator/LinkPoolKey.java | 48180cead79888b5d8fdfa26a544c33247b2c7af | [
"MIT"
]
| permissive | edigonzales/ilivalidator-benchmark | https://github.com/edigonzales/ilivalidator-benchmark | c85e53b3258bf5c15551dbdacf78c1071565dc42 | 31454a6f1fbe397cc997e74991e3f9a00543b56b | refs/heads/master | 2022-11-24T14:37:08.192000 | 2020-07-29T15:49:28 | 2020-07-29T15:49:28 | 283,233,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch.interlis.iox_j.validator;
public class LinkPoolKey {
private String oid;
private String className;
private String roleName;
private LinkPoolKey() {}
public LinkPoolKey(String oid, String className, String roleName){
super();
this.oid = oid;
this.className = className;
this.roleName = roleName;
}
public String getOid() {
return oid;
}
public String getClassName() {
return className;
}
public String getRoleName() {
return roleName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((oid == null) ? 0 : oid.hashCode());
result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
if(className!=null){
result = prime * result + ((className == null) ? 0 : className.hashCode());
}
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LinkPoolKey other = (LinkPoolKey) obj;
if (oid == null) {
if (other.oid != null)
return false;
} else if (!oid.equals(other.oid))
return false;
if (roleName == null) {
if (other.roleName != null)
return false;
} else if (!roleName.equals(other.roleName))
return false;
return true;
}
} | UTF-8 | Java | 1,322 | java | LinkPoolKey.java | Java | []
| null | []
| package ch.interlis.iox_j.validator;
public class LinkPoolKey {
private String oid;
private String className;
private String roleName;
private LinkPoolKey() {}
public LinkPoolKey(String oid, String className, String roleName){
super();
this.oid = oid;
this.className = className;
this.roleName = roleName;
}
public String getOid() {
return oid;
}
public String getClassName() {
return className;
}
public String getRoleName() {
return roleName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((oid == null) ? 0 : oid.hashCode());
result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
if(className!=null){
result = prime * result + ((className == null) ? 0 : className.hashCode());
}
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LinkPoolKey other = (LinkPoolKey) obj;
if (oid == null) {
if (other.oid != null)
return false;
} else if (!oid.equals(other.oid))
return false;
if (roleName == null) {
if (other.roleName != null)
return false;
} else if (!roleName.equals(other.roleName))
return false;
return true;
}
} | 1,322 | 0.645991 | 0.641452 | 61 | 20.688524 | 17.666807 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.131148 | false | false | 1 |
8ab5a2c76faab5628f50830eed72ad6e02d0a237 | 2,207,613,226,282 | a3fa41c1fb3d8d54bda9d112b7da9eccaaaf5c32 | /src/com/argility/centralpages/dao/mapper/SwitchingTranMapper.java | 9dc432c6c3e0cf7fdf5e86e5407c4ce9035bd349 | []
| no_license | Okram1/CentralPages | https://github.com/Okram1/CentralPages | 2ff3864f4bed8bd783c0ad10ed9273cb3dab5385 | ed55a91579a327ce520b57ed8baf1e4362ce7b45 | refs/heads/master | 2020-06-07T07:54:28.932000 | 2011-06-24T21:10:45 | 2011-06-24T21:10:45 | 1,933,290 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.argility.centralpages.dao.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.argility.centralpages.data.SwitchingTran;
public class SwitchingTranMapper<T> implements RowMapper<SwitchingTran> {
public static final String SELECT_COL_SQL = "SELECT sw_audit_Ctrl.sw_aud_id, " +
"sw_audit_ctrl.br_Cde, " +
"sw_audit_ctrl.aud_id, " +
"sw_audit_ctrl.obo_br_Cde, " +
"aud_ts, " +
"act_typ, " +
"act_desc, " +
"sw_aud_dte " +
" FROM sw_audit_Ctrl " +
" JOIN sw_audit USING (sw_aud_id) " +
" JOIN action_typ USING (act_Typ)";
public SwitchingTran mapRow(ResultSet rs, int arg1) throws SQLException {
SwitchingTran tran = new SwitchingTran();
tran.setSwAudId(rs.getInt("sw_aud_id"));
tran.setBrCde(rs.getString("br_cde"));
tran.setAudId(rs.getInt("aud_id"));
tran.setAudTs(rs.getTimestamp("aud_ts"));
tran.setOboBrCde(rs.getString("obo_br_cde"));
tran.setActTyp(rs.getInt("act_typ"));
tran.setActDesc(rs.getString("act_desc"));
tran.setSwAudDte(rs.getTimestamp("sw_aud_dte"));
return tran;
}
}
| UTF-8 | Java | 1,174 | java | SwitchingTranMapper.java | Java | []
| null | []
| package com.argility.centralpages.dao.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.argility.centralpages.data.SwitchingTran;
public class SwitchingTranMapper<T> implements RowMapper<SwitchingTran> {
public static final String SELECT_COL_SQL = "SELECT sw_audit_Ctrl.sw_aud_id, " +
"sw_audit_ctrl.br_Cde, " +
"sw_audit_ctrl.aud_id, " +
"sw_audit_ctrl.obo_br_Cde, " +
"aud_ts, " +
"act_typ, " +
"act_desc, " +
"sw_aud_dte " +
" FROM sw_audit_Ctrl " +
" JOIN sw_audit USING (sw_aud_id) " +
" JOIN action_typ USING (act_Typ)";
public SwitchingTran mapRow(ResultSet rs, int arg1) throws SQLException {
SwitchingTran tran = new SwitchingTran();
tran.setSwAudId(rs.getInt("sw_aud_id"));
tran.setBrCde(rs.getString("br_cde"));
tran.setAudId(rs.getInt("aud_id"));
tran.setAudTs(rs.getTimestamp("aud_ts"));
tran.setOboBrCde(rs.getString("obo_br_cde"));
tran.setActTyp(rs.getInt("act_typ"));
tran.setActDesc(rs.getString("act_desc"));
tran.setSwAudDte(rs.getTimestamp("sw_aud_dte"));
return tran;
}
}
| 1,174 | 0.665247 | 0.664395 | 39 | 28.102564 | 22.340942 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.179487 | false | false | 1 |
c20d32bb0603dd8bd0863b89dc2dd3a3a9064ab1 | 3,856,880,650,345 | 363ef510c99fe6109818d02fe3fa29a6b5d45750 | /src/main/java/com/fourquality/mandata/domain/Tabela.java | ca43ea971dc5cd9bade8a68dd81650650d2fe982 | []
| no_license | Andersonfls/mandata | https://github.com/Andersonfls/mandata | 1fc5af29f31acfe82088104312c19ffdfb174585 | df03a47c74bf1203a8b5a8963d231bcfa7c18240 | refs/heads/main | 2023-05-01T20:21:07.961000 | 2021-05-05T23:32:24 | 2021-05-05T23:32:24 | 364,723,873 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fourquality.mandata.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A Tabela.
*/
@Entity
@Table(name = "tabela")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Tabela implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 100)
@Column(name = "descricao", length = 100)
private String descricao;
@Column(name = "cliente_id")
private Long clienteId;
@Column(name = "data_criacao")
private LocalDate dataCriacao;
@Column(name = "atual")
private Boolean atual;
@Column(name = "status")
private Boolean status;
@ManyToOne
@JsonIgnoreProperties("tipo_tabela_id")
private TipoTabela tipoTabela;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public Tabela descricao(String descricao) {
this.descricao = descricao;
return this;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Long getClienteId() {
return clienteId;
}
public Tabela clienteId(Long clienteId) {
this.clienteId = clienteId;
return this;
}
public void setClienteId(Long clienteId) {
this.clienteId = clienteId;
}
public LocalDate getDataCriacao() {
return dataCriacao;
}
public Tabela dataCriacao(LocalDate dataCriacao) {
this.dataCriacao = dataCriacao;
return this;
}
public void setDataCriacao(LocalDate dataCriacao) {
this.dataCriacao = dataCriacao;
}
public Boolean isAtual() {
return atual;
}
public Tabela atual(Boolean atual) {
this.atual = atual;
return this;
}
public void setAtual(Boolean atual) {
this.atual = atual;
}
public Boolean isStatus() {
return status;
}
public Tabela status(Boolean status) {
this.status = status;
return this;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Boolean getAtual() {
return atual;
}
public Boolean getStatus() {
return status;
}
public TipoTabela getTipoTabela() {
return tipoTabela;
}
public void setTipoTabela(TipoTabela tipoTabela) {
this.tipoTabela = tipoTabela;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tabela tabela = (Tabela) o;
if (tabela.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), tabela.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Tabela{" +
"id=" + getId() +
", descricao='" + getDescricao() + "'" +
", clienteId=" + getClienteId() +
", dataCriacao='" + getDataCriacao() + "'" +
", atual='" + isAtual() + "'" +
", status='" + isStatus() + "'" +
"}";
}
}
| UTF-8 | Java | 3,936 | java | Tabela.java | Java | []
| null | []
| package com.fourquality.mandata.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A Tabela.
*/
@Entity
@Table(name = "tabela")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Tabela implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 100)
@Column(name = "descricao", length = 100)
private String descricao;
@Column(name = "cliente_id")
private Long clienteId;
@Column(name = "data_criacao")
private LocalDate dataCriacao;
@Column(name = "atual")
private Boolean atual;
@Column(name = "status")
private Boolean status;
@ManyToOne
@JsonIgnoreProperties("tipo_tabela_id")
private TipoTabela tipoTabela;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public Tabela descricao(String descricao) {
this.descricao = descricao;
return this;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Long getClienteId() {
return clienteId;
}
public Tabela clienteId(Long clienteId) {
this.clienteId = clienteId;
return this;
}
public void setClienteId(Long clienteId) {
this.clienteId = clienteId;
}
public LocalDate getDataCriacao() {
return dataCriacao;
}
public Tabela dataCriacao(LocalDate dataCriacao) {
this.dataCriacao = dataCriacao;
return this;
}
public void setDataCriacao(LocalDate dataCriacao) {
this.dataCriacao = dataCriacao;
}
public Boolean isAtual() {
return atual;
}
public Tabela atual(Boolean atual) {
this.atual = atual;
return this;
}
public void setAtual(Boolean atual) {
this.atual = atual;
}
public Boolean isStatus() {
return status;
}
public Tabela status(Boolean status) {
this.status = status;
return this;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Boolean getAtual() {
return atual;
}
public Boolean getStatus() {
return status;
}
public TipoTabela getTipoTabela() {
return tipoTabela;
}
public void setTipoTabela(TipoTabela tipoTabela) {
this.tipoTabela = tipoTabela;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tabela tabela = (Tabela) o;
if (tabela.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), tabela.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Tabela{" +
"id=" + getId() +
", descricao='" + getDescricao() + "'" +
", clienteId=" + getClienteId() +
", dataCriacao='" + getDataCriacao() + "'" +
", atual='" + isAtual() + "'" +
", status='" + isStatus() + "'" +
"}";
}
}
| 3,936 | 0.602642 | 0.600864 | 174 | 21.620689 | 19.573463 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.373563 | false | false | 1 |
e25130b21b33bf8b13bfb6319a47d922372e637e | 3,856,880,650,946 | 1074d6f1504188a5837f11fbdf753263fdf9e1b2 | /src/test/java/com/dxb/tdd/mockito/CapturingArgsTest.java | dbddbb12a0bcbf23005f7a0173489a45785baafb | []
| no_license | dxb350352/tddtest | https://github.com/dxb350352/tddtest | 912acbf292ddac37fdc2445ccbbd817ef5dbef8a | fc8088e1c7bd5ec212a3f33302ec176e49754a08 | refs/heads/master | 2021-07-24T18:00:44.190000 | 2020-03-12T14:33:02 | 2020-03-12T14:33:02 | 224,860,703 | 0 | 2 | null | false | 2020-10-13T17:51:06 | 2019-11-29T13:35:38 | 2020-03-12T14:33:15 | 2020-10-13T17:51:05 | 26,263 | 0 | 0 | 1 | JavaScript | false | false | package com.dxb.tdd.mockito;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* User: dxb
* Date: 2019/11/29
* Description: When I wrote this, only God and I understood what I was doing. Now, God only knows
* 捕获参数来进一步断言
* 较复杂的参数匹配器会降低代码的可读性,有些地方使用参数捕获器更加合适
*/
public class CapturingArgsTest {
@Test
public void capturing_args() {
PersonDao personDao = mock(PersonDao.class);
PersonService personService = new PersonService(personDao);
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
personService.update(1, "jack");
verify(personDao).update(argument.capture());
assertEquals(1, argument.getValue().getId());
assertEquals("jack", argument.getValue().getName());
}
class Person {
private int id;
private String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
interface PersonDao {
public void update(Person person);
}
class PersonService {
private PersonDao personDao;
PersonService(PersonDao personDao) {
this.personDao = personDao;
}
public void update(int id, String name) {
personDao.update(new Person(id, name));
}
}
}
| UTF-8 | Java | 1,669 | java | CapturingArgsTest.java | Java | [
{
"context": "t static org.mockito.Mockito.verify;\n\n/**\n * User: dxb\n * Date: 2019/11/29\n * Description: When I wrote ",
"end": 233,
"score": 0.9996569156646729,
"start": 230,
"tag": "USERNAME",
"value": "dxb"
},
{
"context": "s(Person.class);\n personService.update(1, \"jack\");\n verify(personDao).update(argument.capt",
"end": 727,
"score": 0.9910851120948792,
"start": 723,
"tag": "NAME",
"value": "jack"
},
{
"context": "gument.getValue().getId());\n assertEquals(\"jack\", argument.getValue().getName());\n }\n\n clas",
"end": 865,
"score": 0.9684600234031677,
"start": 861,
"tag": "NAME",
"value": "jack"
}
]
| null | []
| package com.dxb.tdd.mockito;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* User: dxb
* Date: 2019/11/29
* Description: When I wrote this, only God and I understood what I was doing. Now, God only knows
* 捕获参数来进一步断言
* 较复杂的参数匹配器会降低代码的可读性,有些地方使用参数捕获器更加合适
*/
public class CapturingArgsTest {
@Test
public void capturing_args() {
PersonDao personDao = mock(PersonDao.class);
PersonService personService = new PersonService(personDao);
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
personService.update(1, "jack");
verify(personDao).update(argument.capture());
assertEquals(1, argument.getValue().getId());
assertEquals("jack", argument.getValue().getName());
}
class Person {
private int id;
private String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
interface PersonDao {
public void update(Person person);
}
class PersonService {
private PersonDao personDao;
PersonService(PersonDao personDao) {
this.personDao = personDao;
}
public void update(int id, String name) {
personDao.update(new Person(id, name));
}
}
}
| 1,669 | 0.622391 | 0.616066 | 64 | 23.703125 | 21.873699 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484375 | false | false | 1 |
bdf9f3cbdadbd08aa144d4317709cf5bac4b82d6 | 2,250,562,890,195 | b24a739f0cc5a38290fc15b920388d6a7ffd7156 | /src/main/java/com/frozen/myblog/service/implement/UserServiceImpl.java | 732242003659954ec05b7dd134708bd62f9473ba | []
| no_license | cjz14/Blog | https://github.com/cjz14/Blog | 7067f802fc3bbf87d91aa9226c2f1fa1213f4574 | 688c9dcf37eb99c47e2b977ead687cb0bce5d0e3 | refs/heads/master | 2023-05-26T07:28:16.156000 | 2018-11-12T08:33:05 | 2018-11-12T08:33:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.frozen.myblog.service.implement;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.frozen.myblog.mapper.UserMapper;
import com.frozen.myblog.pojo.User;
import com.frozen.myblog.service.UserService;
import com.frozen.myblog.util.BlogException;
import com.frozen.myblog.util.MyUtils;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper um;
@Resource(name="redisTemplate")
private RedisTemplate<String, Object> rt;
@Override
public User login(User user) throws BlogException {
// 先从redis中查看该用户是否存在
ValueOperations<String, Object> ops = rt.opsForValue();
User t_user = (User) ops.get("username:" + user.getUsername());
// 不存在,从数据库中查找,再存入redis
if (t_user == null) {
t_user = um.queryUserByUsername(user.getUsername());
}
// 找不到该用户
if (t_user == null) {
throw new BlogException("用户名不存在");
} else {
// 无论t_user是在redis中还是数据库中查到,覆盖过期时间,10天过期。
ops.set("username:" + t_user.getUsername(), t_user, 10, TimeUnit.DAYS);
// 校验密码
if (t_user.getPassword().equals(user.getPassword())) {
return t_user;
} else {
throw new BlogException("用户名或密码错误");
}
}
}
@Override
public void register(User user) throws BlogException {
boolean isExit = existUsername(user.getUsername());
if (isExit) {
// 若数据库中已存在该用户名,抛出异常
throw new BlogException("用户名已存在");
}
// 无该用户,正常注册
try {
um.saveUser(user);
} catch (Exception e) {
e.printStackTrace();
throw new BlogException("注册异常");
}
}
// 校验用户名是否存在
@Override
public boolean existUsername(String username) throws BlogException {
if (MyUtils.checkempty(username)) {
throw new BlogException("用户名不能为空");
} else {
// 先从redis中查看用户名是否存在
ValueOperations<String, Object> ops = rt.opsForValue();
User user = (User) ops.get("username:" + username);
if (user != null)
return true;
// 不存在,再去查找数据库
Integer i = um.query1ByUsername(username);
// 若ID不存在,用户不存在,返回false
if (i == null)
return false;
// 否则 返回true
return true;
}
}
@Override
public User addVisitor(String username) {
User user = new User();
user.setUsername(username);
// 确认该游客名是否存在,存在就使用,不存在则创建
Integer i=um.query1ByUsername(username);
if (i == null)
um.saveVisitor(username);
return user;
}
//查找用户总数量
@Override
public Integer queryUserCount() {
return um.queryCount();
}
}
| UTF-8 | Java | 3,095 | java | UserServiceImpl.java | Java | []
| null | []
| package com.frozen.myblog.service.implement;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.frozen.myblog.mapper.UserMapper;
import com.frozen.myblog.pojo.User;
import com.frozen.myblog.service.UserService;
import com.frozen.myblog.util.BlogException;
import com.frozen.myblog.util.MyUtils;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper um;
@Resource(name="redisTemplate")
private RedisTemplate<String, Object> rt;
@Override
public User login(User user) throws BlogException {
// 先从redis中查看该用户是否存在
ValueOperations<String, Object> ops = rt.opsForValue();
User t_user = (User) ops.get("username:" + user.getUsername());
// 不存在,从数据库中查找,再存入redis
if (t_user == null) {
t_user = um.queryUserByUsername(user.getUsername());
}
// 找不到该用户
if (t_user == null) {
throw new BlogException("用户名不存在");
} else {
// 无论t_user是在redis中还是数据库中查到,覆盖过期时间,10天过期。
ops.set("username:" + t_user.getUsername(), t_user, 10, TimeUnit.DAYS);
// 校验密码
if (t_user.getPassword().equals(user.getPassword())) {
return t_user;
} else {
throw new BlogException("用户名或密码错误");
}
}
}
@Override
public void register(User user) throws BlogException {
boolean isExit = existUsername(user.getUsername());
if (isExit) {
// 若数据库中已存在该用户名,抛出异常
throw new BlogException("用户名已存在");
}
// 无该用户,正常注册
try {
um.saveUser(user);
} catch (Exception e) {
e.printStackTrace();
throw new BlogException("注册异常");
}
}
// 校验用户名是否存在
@Override
public boolean existUsername(String username) throws BlogException {
if (MyUtils.checkempty(username)) {
throw new BlogException("用户名不能为空");
} else {
// 先从redis中查看用户名是否存在
ValueOperations<String, Object> ops = rt.opsForValue();
User user = (User) ops.get("username:" + username);
if (user != null)
return true;
// 不存在,再去查找数据库
Integer i = um.query1ByUsername(username);
// 若ID不存在,用户不存在,返回false
if (i == null)
return false;
// 否则 返回true
return true;
}
}
@Override
public User addVisitor(String username) {
User user = new User();
user.setUsername(username);
// 确认该游客名是否存在,存在就使用,不存在则创建
Integer i=um.query1ByUsername(username);
if (i == null)
um.saveVisitor(username);
return user;
}
//查找用户总数量
@Override
public Integer queryUserCount() {
return um.queryCount();
}
}
| 3,095 | 0.683205 | 0.681 | 102 | 24.67647 | 19.642471 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.176471 | false | false | 1 |
b2c8f6b3d415e19e8ca5fdf100bd1c12f5fea118 | 6,442,450,957,172 | 430893063d83cf01907c3239b6bfe5556237eb7b | /perfume/src/fp/admin/models/service/AdminService.java | f1bbb2f3a9de6959678871cd1332f90eb86b87cb | []
| no_license | Lee-Wonjoon/Twenty-Second | https://github.com/Lee-Wonjoon/Twenty-Second | 9ddd5b198b7fba6060610d1e94d00f2a7109e8bc | fc675a5dfd5c359c516016ac9be98c956e90e4a6 | refs/heads/master | 2020-09-04T01:30:12.157000 | 2020-04-16T11:39:59 | 2020-04-16T11:39:59 | 219,629,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fp.admin.models.service;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import fp.CS.models.vo.Question;
import fp.admin.models.dao.AdminDao;
import fp.admin.models.vo.PageData;
import fp.common.JDBCTemplate;
import fp.member.model.vo.Member;
import fp.notice.models.vo.Notice;
import fp.payment.models.dao.PaymentDao;
import fp.payment.models.vo.Payment;
import fp.payment.models.vo.PaymentInfo;
import fp.perfume.model.vo.Perfume;
import fp.review.model.vo.Review;
public class AdminService {
public PageData memberList(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountMember(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListMember(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/memberAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/memberAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/memberAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Member member = (Member)m;
System.out.println(member.getMemberNo()+"\t" + member.getMemberNickname());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deletePerfume(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deletePerfume(conn, perfumeNo);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData perfumeListAdmin(int reqPage ) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountPerfume(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListPerfume(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/listAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/listAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/listAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public Perfume updatePerfumeAdmin(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Perfume p = dao.getPerfume(conn, perfumeNo);
JDBCTemplate.close(conn);
return p;
}
public int updatePerfumeFinishAdmin(int perfumeNo, String perfumeName, int perfumePrice, String perfumePhotoname,
String perfumePhotopath, String perfumeDetail) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updatePerfumeFinishAdmin(conn, perfumeNo, perfumeName, perfumePrice, perfumePhotoname, perfumePhotopath, perfumeDetail);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public int validMemberAdmin(int memberNo, String memberValid) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.validMemberAdmin(conn, memberNo, memberValid);
JDBCTemplate.close(conn);
return result;
}
public PageData getReviewAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountReview(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListReview(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deleteReviewAdmin(int reviewNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deleteReviewAdmin(conn, reviewNo);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData questionListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountQuestion(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListQuestion(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/questionAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/questionAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/questionAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Question member = (Question)m;
System.out.println(member.getQuestionNo()+"\t" + member.getQuestionWriter());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int readQuestionAdmin(int questionNo, String to) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.readQuestionAdmin(conn, questionNo, to);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Question getQuestion(int questionNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Question q = dao.getQuestion(conn, questionNo);
JDBCTemplate.close(conn);
return q;
}
public int answerQuestionAdmin(int questionNo, String questionContent, String filename, String filepath) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.answerQuestionAdmin(conn, questionNo, questionContent, filename, filepath);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Question getQuestionAnswer(int questionNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Question q = dao.getQuestionAnswer(conn, questionNo);
JDBCTemplate.close(conn);
return q;
}
public PageData noticeListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountNotice(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListNotice(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Notice member = (Notice)m;
System.out.println(member.getNoticeNo()+"\t" + member.getNoticeWriter());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deleteNoticeAdmin(int noticeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deleteNoticeAdmin(conn, noticeNo);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Notice getNoticeAdmin(int noticeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Notice n = dao.getNoticeAdmin(conn, noticeNo);
JDBCTemplate.close(conn);
return n;
}
public int updateNoticeAdmin(Notice n) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updateNoticeAdmin(conn, n);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData getTradeListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountTrade(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListTrade(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Payment member = (Payment)m;
System.out.println(member.getPaymentNo()+"\t" + member.getPaymentMemberNo());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int insertNoticeSubmit(Notice n) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.insertNoticeAdmin(conn, n);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData getListAdmin(int reqPage, String table, String area, String value, String location) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalSearchCount(conn, table, area, value);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectSearchListAdmin(conn,start,end,table, area, value);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
pageNavi += "<form action='/searchAdmin' method='post'>";
pageNavi += "<input type='hidden' name='table' value='"+table+"'>";
pageNavi += "<input type='hidden' name='area' value='"+area+"'>";
pageNavi += "<input type='hidden' name='value' value='"+value+"'>";
pageNavi += "<input type='hidden' name='location' value='"+location+"'>";
if(pageNo!=1) {
pageNavi += "<button class='btn' style='color:#888888; ' href='/"+location+"?reqPage="+(pageNo-1)+"'>이전</button>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<input type='submit' class ='btn' style='color:#888888;' name='reqPage' value='"+pageNo+"'>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<button class='btn' style='color:#888888;' href='/"+location+"?reqPage="+(pageNo)+"'>다음</button>";
}
pageNavi += "</form>";
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public HashMap<String, Integer> getTMB() {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
ArrayList<Perfume> list = dao.getAllPerfume(conn);
ArrayList<String> toplist = new ArrayList<String>();
for(Perfume p : list) {
String top = p.getPerfumeBase();
StringTokenizer st = new StringTokenizer(top, ",");
while(st.hasMoreTokens()) {
toplist.add(st.nextToken());
}
}
HashMap<String, Integer> topmap = new HashMap<String, Integer>();
for(String top : toplist) {
if(topmap.containsKey(top)) {
topmap.put(top, topmap.get(top)+1);
}else {
topmap.put(top, 1);
}
}
System.out.println(topmap);
return topmap;
}
public int updateStockAdmin(int amount, String type, int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updateStockAdmin(conn,amount,type,perfumeNo);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public int getStockAmount(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int amount = dao.getAmount(conn, perfumeNo);
JDBCTemplate.close(conn);
return amount;
}
public ArrayList<PaymentInfo> tradeInfoAdmin(int paymentInfoPaymentNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
ArrayList<PaymentInfo> list = dao.tradeInfoAdmin(conn, paymentInfoPaymentNo);
/*for(PaymentInfo p : list) {
System.out.println(p);
}*/
JDBCTemplate.close(conn);
return list;
}
public int changePaymentStatus(int paymentNo, String status) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.changePaymentStatus(conn,paymentNo,status);
if(result>0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData perstaListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountPersta(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListPersta(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int delPerstaAdmin(String reviewNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.delPerstaAdmin(conn, reviewNo);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
}
| UTF-8 | Java | 19,705 | java | AdminService.java | Java | []
| null | []
| package fp.admin.models.service;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import fp.CS.models.vo.Question;
import fp.admin.models.dao.AdminDao;
import fp.admin.models.vo.PageData;
import fp.common.JDBCTemplate;
import fp.member.model.vo.Member;
import fp.notice.models.vo.Notice;
import fp.payment.models.dao.PaymentDao;
import fp.payment.models.vo.Payment;
import fp.payment.models.vo.PaymentInfo;
import fp.perfume.model.vo.Perfume;
import fp.review.model.vo.Review;
public class AdminService {
public PageData memberList(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountMember(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListMember(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/memberAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/memberAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/memberAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Member member = (Member)m;
System.out.println(member.getMemberNo()+"\t" + member.getMemberNickname());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deletePerfume(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deletePerfume(conn, perfumeNo);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData perfumeListAdmin(int reqPage ) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountPerfume(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListPerfume(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/listAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/listAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/listAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public Perfume updatePerfumeAdmin(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Perfume p = dao.getPerfume(conn, perfumeNo);
JDBCTemplate.close(conn);
return p;
}
public int updatePerfumeFinishAdmin(int perfumeNo, String perfumeName, int perfumePrice, String perfumePhotoname,
String perfumePhotopath, String perfumeDetail) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updatePerfumeFinishAdmin(conn, perfumeNo, perfumeName, perfumePrice, perfumePhotoname, perfumePhotopath, perfumeDetail);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public int validMemberAdmin(int memberNo, String memberValid) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.validMemberAdmin(conn, memberNo, memberValid);
JDBCTemplate.close(conn);
return result;
}
public PageData getReviewAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountReview(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListReview(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/reviewAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deleteReviewAdmin(int reviewNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deleteReviewAdmin(conn, reviewNo);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData questionListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountQuestion(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListQuestion(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/questionAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/questionAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/questionAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Question member = (Question)m;
System.out.println(member.getQuestionNo()+"\t" + member.getQuestionWriter());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int readQuestionAdmin(int questionNo, String to) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.readQuestionAdmin(conn, questionNo, to);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Question getQuestion(int questionNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Question q = dao.getQuestion(conn, questionNo);
JDBCTemplate.close(conn);
return q;
}
public int answerQuestionAdmin(int questionNo, String questionContent, String filename, String filepath) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.answerQuestionAdmin(conn, questionNo, questionContent, filename, filepath);
if(result!=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Question getQuestionAnswer(int questionNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Question q = dao.getQuestionAnswer(conn, questionNo);
JDBCTemplate.close(conn);
return q;
}
public PageData noticeListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountNotice(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListNotice(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/noticeAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Notice member = (Notice)m;
System.out.println(member.getNoticeNo()+"\t" + member.getNoticeWriter());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int deleteNoticeAdmin(int noticeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.deleteNoticeAdmin(conn, noticeNo);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public Notice getNoticeAdmin(int noticeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
Notice n = dao.getNoticeAdmin(conn, noticeNo);
JDBCTemplate.close(conn);
return n;
}
public int updateNoticeAdmin(Notice n) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updateNoticeAdmin(conn, n);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData getTradeListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountTrade(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListTrade(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/tradeAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
/*for (Object m : list) {
Payment member = (Payment)m;
System.out.println(member.getPaymentNo()+"\t" + member.getPaymentMemberNo());
}*/
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int insertNoticeSubmit(Notice n) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.insertNoticeAdmin(conn, n);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData getListAdmin(int reqPage, String table, String area, String value, String location) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalSearchCount(conn, table, area, value);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectSearchListAdmin(conn,start,end,table, area, value);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
pageNavi += "<form action='/searchAdmin' method='post'>";
pageNavi += "<input type='hidden' name='table' value='"+table+"'>";
pageNavi += "<input type='hidden' name='area' value='"+area+"'>";
pageNavi += "<input type='hidden' name='value' value='"+value+"'>";
pageNavi += "<input type='hidden' name='location' value='"+location+"'>";
if(pageNo!=1) {
pageNavi += "<button class='btn' style='color:#888888; ' href='/"+location+"?reqPage="+(pageNo-1)+"'>이전</button>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<input type='submit' class ='btn' style='color:#888888;' name='reqPage' value='"+pageNo+"'>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<button class='btn' style='color:#888888;' href='/"+location+"?reqPage="+(pageNo)+"'>다음</button>";
}
pageNavi += "</form>";
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public HashMap<String, Integer> getTMB() {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
ArrayList<Perfume> list = dao.getAllPerfume(conn);
ArrayList<String> toplist = new ArrayList<String>();
for(Perfume p : list) {
String top = p.getPerfumeBase();
StringTokenizer st = new StringTokenizer(top, ",");
while(st.hasMoreTokens()) {
toplist.add(st.nextToken());
}
}
HashMap<String, Integer> topmap = new HashMap<String, Integer>();
for(String top : toplist) {
if(topmap.containsKey(top)) {
topmap.put(top, topmap.get(top)+1);
}else {
topmap.put(top, 1);
}
}
System.out.println(topmap);
return topmap;
}
public int updateStockAdmin(int amount, String type, int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.updateStockAdmin(conn,amount,type,perfumeNo);
if(result !=0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public int getStockAmount(int perfumeNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int amount = dao.getAmount(conn, perfumeNo);
JDBCTemplate.close(conn);
return amount;
}
public ArrayList<PaymentInfo> tradeInfoAdmin(int paymentInfoPaymentNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
ArrayList<PaymentInfo> list = dao.tradeInfoAdmin(conn, paymentInfoPaymentNo);
/*for(PaymentInfo p : list) {
System.out.println(p);
}*/
JDBCTemplate.close(conn);
return list;
}
public int changePaymentStatus(int paymentNo, String status) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.changePaymentStatus(conn,paymentNo,status);
if(result>0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
public PageData perstaListAdmin(int reqPage) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int numPerPage = 10;
int totalCount = dao.totalCountPersta(conn);
int totalPage=(totalCount%numPerPage==0)?(totalPage = totalCount/numPerPage):(totalPage = totalCount/numPerPage)+1; //총 페이지
int start = (reqPage-1)*numPerPage+1;
int end = reqPage*numPerPage;
ArrayList<Object> list = dao.selectListPersta(conn,start,end);
/* for(Notice n : list) {
System.out.println(n);
}*/
String pageNavi = "";
int pageNaviSize= 5;
int pageNo;
if(reqPage<3) {
pageNo = 1;
}else if(reqPage+2>totalPage){
if(totalPage-4 > 0) {
pageNo= totalPage-4;
}else {
pageNo=1;
}
}else {
pageNo = reqPage-2;
}
if(pageNo!=1) {
pageNavi += "<a class='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+(pageNo-1)+"'>이전</a>";
}
int i=1;
while(!(i++>pageNaviSize || pageNo>totalPage)) {
if(reqPage==pageNo) {
pageNavi +="<span class ='selectPage' style='color:black;'>"+pageNo+"</span>";
}else {
pageNavi +="<a class ='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+pageNo+"'>"+pageNo+"</a>";
}
pageNo++;
}
if(pageNo<= totalPage) {
pageNavi += "<a class='btn' style='color:#888888;' href='/perstaAdmin?reqPage="+(pageNo)+"'>다음</a>";
}
PageData pd = new PageData(list, pageNavi);
JDBCTemplate.close(conn);
return pd;
}
public int delPerstaAdmin(String reviewNo) {
Connection conn = JDBCTemplate.getConnection();
AdminDao dao = new AdminDao();
int result = dao.delPerstaAdmin(conn, reviewNo);
if(result != 0) {
JDBCTemplate.commit(conn);
}else {
JDBCTemplate.rollback(conn);
}
JDBCTemplate.close(conn);
return result;
}
}
| 19,705 | 0.666854 | 0.651479 | 670 | 28.219402 | 27.684219 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.743284 | false | false | 1 |
d240a5531b2d032f100cd2aca3ab8032c30a1120 | 39,702,677,690,400 | 332c12da8b61bd4497e9050b7e8c2e1a84dd896e | /src/main/java/com/ruimin/ifs/pmp/sysConf/process/bean/PassInfoVO.java | 1458b559995c4a0835dfcb1038380524cde9197c | []
| no_license | zhanght86/ifsp-pmp | https://github.com/zhanght86/ifsp-pmp | 76d25c873c8d36ebeb95486ae9a8b7829f611956 | 8f6702426af5ddc452142063084274192e35ede8 | refs/heads/master | 2020-03-07T08:53:14.157000 | 2018-02-06T01:54:13 | 2018-02-06T01:54:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ruimin.ifs.pmp.sysConf.process.bean;
import com.ruimin.ifs.rql.annotation.Id;
import com.ruimin.ifs.rql.annotation.Table;
@Table("CHL_PASS_BASE_INFO")
public class PassInfoVO {
@Id
private String passNo; // 通道编号
private String passName; // 通道名称
private String passStat; // 通道状态
private String openDate; // 开通日期
private String passAccessType; // 接入方式
private String passSeltMode; // 清算类型
private String passSetlCycle; // 清算周期
private String passSetlAcct; // 清算账户
private String passseltTime; // 清算时间
private String remark; // 备注
private String crtTlr; // 创建柜员
private String crtDateTime; // 创建日期时间
private String lastUpdTlr; // 最近更新柜员
private String lastUpdDateTime; // 最近更新日期时间
/**
* @return the passNo
*/
public String getPassNo() {
return passNo;
}
/**
* @param passNo
* the passNo to set
*/
public void setPassNo(String passNo) {
this.passNo = passNo;
}
/**
* @return the passName
*/
public String getPassName() {
return passName;
}
/**
* @param passName
* the passName to set
*/
public void setPassName(String passName) {
this.passName = passName;
}
/**
* @return the passStat
*/
public String getPassStat() {
return passStat;
}
/**
* @param passStat
* the passStat to set
*/
public void setPassStat(String passStat) {
this.passStat = passStat;
}
/**
* @return the openDate
*/
public String getOpenDate() {
return openDate;
}
/**
* @param openDate
* the openDate to set
*/
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
/**
* @return the passAccessType
*/
public String getPassAccessType() {
return passAccessType;
}
/**
* @param passAccessType
* the passAccessType to set
*/
public void setPassAccessType(String passAccessType) {
this.passAccessType = passAccessType;
}
/**
* @return the passSeltMode
*/
public String getPassSeltMode() {
return passSeltMode;
}
/**
* @param passSeltMode
* the passSeltMode to set
*/
public void setPassSeltMode(String passSeltMode) {
this.passSeltMode = passSeltMode;
}
/**
* @return the passSetlCycle
*/
public String getPassSetlCycle() {
return passSetlCycle;
}
/**
* @param passSetlCycle
* the passSetlCycle to set
*/
public void setPassSetlCycle(String passSetlCycle) {
this.passSetlCycle = passSetlCycle;
}
/**
* @return the passSetlAcct
*/
public String getPassSetlAcct() {
return passSetlAcct;
}
/**
* @param passSetlAcct
* the passSetlAcct to set
*/
public void setPassSetlAcct(String passSetlAcct) {
this.passSetlAcct = passSetlAcct;
}
/**
* @return the passseltTime
*/
public String getPassseltTime() {
return passseltTime;
}
/**
* @param passseltTime
* the passseltTime to set
*/
public void setPassseltTime(String passseltTime) {
this.passseltTime = passseltTime;
}
/**
* @return the remark
*/
public String getRemark() {
return remark;
}
/**
* @param remark
* the remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* @return the crtTlr
*/
public String getCrtTlr() {
return crtTlr;
}
/**
* @param crtTlr
* the crtTlr to set
*/
public void setCrtTlr(String crtTlr) {
this.crtTlr = crtTlr;
}
/**
* @return the crtDateTime
*/
public String getCrtDateTime() {
return crtDateTime;
}
/**
* @param crtDateTime
* the crtDateTime to set
*/
public void setCrtDateTime(String crtDateTime) {
this.crtDateTime = crtDateTime;
}
/**
* @return the lastUpdTlr
*/
public String getLastUpdTlr() {
return lastUpdTlr;
}
/**
* @param lastUpdTlr
* the lastUpdTlr to set
*/
public void setLastUpdTlr(String lastUpdTlr) {
this.lastUpdTlr = lastUpdTlr;
}
/**
* @return the lastUpdDateTime
*/
public String getLastUpdDateTime() {
return lastUpdDateTime;
}
/**
* @param lastUpdDateTime
* the lastUpdDateTime to set
*/
public void setLastUpdDateTime(String lastUpdDateTime) {
this.lastUpdDateTime = lastUpdDateTime;
}
}
| UTF-8 | Java | 4,316 | java | PassInfoVO.java | Java | []
| null | []
| package com.ruimin.ifs.pmp.sysConf.process.bean;
import com.ruimin.ifs.rql.annotation.Id;
import com.ruimin.ifs.rql.annotation.Table;
@Table("CHL_PASS_BASE_INFO")
public class PassInfoVO {
@Id
private String passNo; // 通道编号
private String passName; // 通道名称
private String passStat; // 通道状态
private String openDate; // 开通日期
private String passAccessType; // 接入方式
private String passSeltMode; // 清算类型
private String passSetlCycle; // 清算周期
private String passSetlAcct; // 清算账户
private String passseltTime; // 清算时间
private String remark; // 备注
private String crtTlr; // 创建柜员
private String crtDateTime; // 创建日期时间
private String lastUpdTlr; // 最近更新柜员
private String lastUpdDateTime; // 最近更新日期时间
/**
* @return the passNo
*/
public String getPassNo() {
return passNo;
}
/**
* @param passNo
* the passNo to set
*/
public void setPassNo(String passNo) {
this.passNo = passNo;
}
/**
* @return the passName
*/
public String getPassName() {
return passName;
}
/**
* @param passName
* the passName to set
*/
public void setPassName(String passName) {
this.passName = passName;
}
/**
* @return the passStat
*/
public String getPassStat() {
return passStat;
}
/**
* @param passStat
* the passStat to set
*/
public void setPassStat(String passStat) {
this.passStat = passStat;
}
/**
* @return the openDate
*/
public String getOpenDate() {
return openDate;
}
/**
* @param openDate
* the openDate to set
*/
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
/**
* @return the passAccessType
*/
public String getPassAccessType() {
return passAccessType;
}
/**
* @param passAccessType
* the passAccessType to set
*/
public void setPassAccessType(String passAccessType) {
this.passAccessType = passAccessType;
}
/**
* @return the passSeltMode
*/
public String getPassSeltMode() {
return passSeltMode;
}
/**
* @param passSeltMode
* the passSeltMode to set
*/
public void setPassSeltMode(String passSeltMode) {
this.passSeltMode = passSeltMode;
}
/**
* @return the passSetlCycle
*/
public String getPassSetlCycle() {
return passSetlCycle;
}
/**
* @param passSetlCycle
* the passSetlCycle to set
*/
public void setPassSetlCycle(String passSetlCycle) {
this.passSetlCycle = passSetlCycle;
}
/**
* @return the passSetlAcct
*/
public String getPassSetlAcct() {
return passSetlAcct;
}
/**
* @param passSetlAcct
* the passSetlAcct to set
*/
public void setPassSetlAcct(String passSetlAcct) {
this.passSetlAcct = passSetlAcct;
}
/**
* @return the passseltTime
*/
public String getPassseltTime() {
return passseltTime;
}
/**
* @param passseltTime
* the passseltTime to set
*/
public void setPassseltTime(String passseltTime) {
this.passseltTime = passseltTime;
}
/**
* @return the remark
*/
public String getRemark() {
return remark;
}
/**
* @param remark
* the remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* @return the crtTlr
*/
public String getCrtTlr() {
return crtTlr;
}
/**
* @param crtTlr
* the crtTlr to set
*/
public void setCrtTlr(String crtTlr) {
this.crtTlr = crtTlr;
}
/**
* @return the crtDateTime
*/
public String getCrtDateTime() {
return crtDateTime;
}
/**
* @param crtDateTime
* the crtDateTime to set
*/
public void setCrtDateTime(String crtDateTime) {
this.crtDateTime = crtDateTime;
}
/**
* @return the lastUpdTlr
*/
public String getLastUpdTlr() {
return lastUpdTlr;
}
/**
* @param lastUpdTlr
* the lastUpdTlr to set
*/
public void setLastUpdTlr(String lastUpdTlr) {
this.lastUpdTlr = lastUpdTlr;
}
/**
* @return the lastUpdDateTime
*/
public String getLastUpdDateTime() {
return lastUpdDateTime;
}
/**
* @param lastUpdDateTime
* the lastUpdDateTime to set
*/
public void setLastUpdDateTime(String lastUpdDateTime) {
this.lastUpdDateTime = lastUpdDateTime;
}
}
| 4,316 | 0.65124 | 0.65124 | 235 | 16.838299 | 15.937091 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.148936 | false | false | 1 |
241979de1586d13afbdc84a2277d77ff216c080e | 12,790,412,608,164 | bc93d67f1ada9b8174f5f9cafd6e7d8db7616d86 | /app/src/main/java/com/example/goose/buttonclickapp/MainActivity.java | 00702728f4e0cdc2f571ba32f4e5a9c5fd71816d | []
| no_license | gmartinez31/AndroidButtonCounterApp | https://github.com/gmartinez31/AndroidButtonCounterApp | 84580843e49904f44487ffb8badda436be3c9b36 | fc3afb39cf7aeb0fc55358cec6873fe1c36db4b6 | refs/heads/master | 2020-03-20T03:34:16.586000 | 2018-06-23T20:37:54 | 2018-06-23T20:37:54 | 137,150,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.goose.buttonclickapp;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText userInput;
private TextView textView;
private static final String TAG = "MainActivity";
private final String TEXT_CONTENTS = "TextContents";
private ArrayList<Loot> inventory;
public ArrayList<Loot> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Loot> inventory) {
this.inventory = inventory;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: in");
inventory = new ArrayList<>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is how you map the layout view you have to the variables declared here
userInput = (EditText) findViewById(R.id.editText);
userInput.setText("");
Button button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
textView.setText("");
textView.setMovementMethod(new ScrollingMovementMethod()); // this is how you add scrolling capabilities
View.OnClickListener theOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String result = userInput.getText().toString();
// or
//Editable e = userInput.getText();
//String result = e.toString();
result += "\n";
textView.append(result);
userInput.setText("");
}
};
button.setOnClickListener(theOnClickListener);
Log.d(TAG, "onCreate: out");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
@Override
protected void onStart() {
Log.d(TAG, "onStart: in");
super.onStart();
Log.d(TAG, "onStart: out");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onRestoreInstanceState: in");
super.onRestoreInstanceState(savedInstanceState);
textView.setText(savedInstanceState.getString(TEXT_CONTENTS)); // or
// String savedString = savedInstanceState.getString(TEXT_CONTENTS);
// textView.setText(savedString);
Log.d(TAG, "onRestoreInstanceState: out");
}
@Override
protected void onPostResume() {
Log.d(TAG, "onPostResume: in");
super.onPostResume();
Log.d(TAG, "onPostResume: out");
}
@Override
protected void onPause() {
Log.d(TAG, "onPause: in");
super.onPause();
Log.d(TAG, "onPause: out");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState: in");
// the line below saves the current value in the textView into that bundle; also, the reason why we are inserting the line before the super call is so that we can save anything prior to super
// being called since it actually does the actual saving
outState.putString(TEXT_CONTENTS, textView.getText().toString());
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState: out");
}
@Override
protected void onStop() {
Log.d(TAG, "onStop: in");
super.onStop();
Log.d(TAG, "onStop: out");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: in");
super.onDestroy();
Log.d(TAG, "onDestroy: out");
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart: in");
super.onRestart();
Log.d(TAG, "onRestart: out");
}
}
| UTF-8 | Java | 4,249 | java | MainActivity.java | Java | []
| null | []
| package com.example.goose.buttonclickapp;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText userInput;
private TextView textView;
private static final String TAG = "MainActivity";
private final String TEXT_CONTENTS = "TextContents";
private ArrayList<Loot> inventory;
public ArrayList<Loot> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Loot> inventory) {
this.inventory = inventory;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: in");
inventory = new ArrayList<>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is how you map the layout view you have to the variables declared here
userInput = (EditText) findViewById(R.id.editText);
userInput.setText("");
Button button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
textView.setText("");
textView.setMovementMethod(new ScrollingMovementMethod()); // this is how you add scrolling capabilities
View.OnClickListener theOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String result = userInput.getText().toString();
// or
//Editable e = userInput.getText();
//String result = e.toString();
result += "\n";
textView.append(result);
userInput.setText("");
}
};
button.setOnClickListener(theOnClickListener);
Log.d(TAG, "onCreate: out");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
@Override
protected void onStart() {
Log.d(TAG, "onStart: in");
super.onStart();
Log.d(TAG, "onStart: out");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onRestoreInstanceState: in");
super.onRestoreInstanceState(savedInstanceState);
textView.setText(savedInstanceState.getString(TEXT_CONTENTS)); // or
// String savedString = savedInstanceState.getString(TEXT_CONTENTS);
// textView.setText(savedString);
Log.d(TAG, "onRestoreInstanceState: out");
}
@Override
protected void onPostResume() {
Log.d(TAG, "onPostResume: in");
super.onPostResume();
Log.d(TAG, "onPostResume: out");
}
@Override
protected void onPause() {
Log.d(TAG, "onPause: in");
super.onPause();
Log.d(TAG, "onPause: out");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState: in");
// the line below saves the current value in the textView into that bundle; also, the reason why we are inserting the line before the super call is so that we can save anything prior to super
// being called since it actually does the actual saving
outState.putString(TEXT_CONTENTS, textView.getText().toString());
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState: out");
}
@Override
protected void onStop() {
Log.d(TAG, "onStop: in");
super.onStop();
Log.d(TAG, "onStop: out");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: in");
super.onDestroy();
Log.d(TAG, "onDestroy: out");
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart: in");
super.onRestart();
Log.d(TAG, "onRestart: out");
}
}
| 4,249 | 0.640857 | 0.640621 | 134 | 30.708956 | 27.708187 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671642 | false | false | 1 |
c9437c341e71a11152703f47be011f5558163156 | 19,043,885,027,333 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_e2108c3bf6e4bf2c441de92331a83f07ac0dc698/ApMessageFilter/2_e2108c3bf6e4bf2c441de92331a83f07ac0dc698_ApMessageFilter_s.java | eb56c265931e5bedd3e7a629b17d260f87a5cc9b | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package org.nhcham.ahoy;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import android.content.*;
import android.content.res.*;
import android.util.*;
public class ApMessageFilter
{
final static String SSID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final static String AHOY_PREFIX_CHAR = "a";
final static int MAX_BITS = 178;
final static String TAG = "ApMessageFilter";
public HashMap<Integer, ILanguagePack> languagePacks;
BigInteger radix = new BigInteger("62");
public ApMessageFilter(Context context)
{
languagePacks = new HashMap<Integer, ILanguagePack>();
try
{
BufferedReader r = new BufferedReader(new InputStreamReader(context.getAssets().open("languages.txt")));
String line;
while ((line = r.readLine()) != null)
{
line = line.trim();
int spaceOffset = line.indexOf(' ');
if (spaceOffset < 0)
continue;
int languageId = Integer.parseInt(line.substring(0, spaceOffset), 10);
int spaceOffset2 = line.indexOf(' ', spaceOffset + 1);
if (spaceOffset2 < 0)
continue;
String languageTag = line.substring(spaceOffset + 1, spaceOffset2);
String languageMarker = line.substring(spaceOffset2 + 1);
// Log.d(TAG, String.format("Now loading [%d] [%s]...", languageId, languageTag));
ILanguagePack pack = null;
if (languageTag.equals("utf8") || languageTag.equals("utf16"))
pack = new LanguagePackUtf(context, languageId, languageTag, languageMarker);
else
pack = new LanguagePack(context, languageId, languageTag, languageMarker);
languagePacks.put(languageId, pack);
}
} catch (IOException e) {
// TODO: what do we do with this?
}
}
public String ssidToMessage(final String s)
{
if (!s.startsWith(AHOY_PREFIX_CHAR))
return null;
if (s.length() != 31)
return null;
BigInteger bigint = BigInteger.ZERO;
for (int i = s.length() - 1; i >= 1; i--)
{
// TODO: This is slow.
int n = SSID_ALPHABET.indexOf(s.charAt(i));
if (n == -1)
return null;
bigint = bigint.multiply(radix);
// TODO: This is slow.
bigint = bigint.add(new BigInteger(String.format("%d", n)));
}
// Log.d(TAG, String.format("BigInt is %s.", bigint.toString()));
byte[] bits = new byte[MAX_BITS];
for (int i = 0; i < MAX_BITS; i++)
bits[i] = 0;
int offset = 0;
while (!bigint.equals(BigInteger.ZERO))
{
if (bigint.and(BigInteger.ONE).equals(BigInteger.ONE))
bits[offset] = 1;
offset++;
if (offset >= MAX_BITS)
// TODO: Should we return null here? Probably yes.
break;
bigint = bigint.shiftRight(1);
}
// String bitstring = new String();
// for (int i = 0; i < bits.length; i++)
// bitstring += bits[i] == 0 ? "0" : "1";
// Log.d(TAG, String.format("Bit string is %s.", bitstring));
if (bits[0] == 1)
{
// this is language pack 1 to 127...
int languagePackId = 0;
for (int i = 0; i < 7; i++)
languagePackId |= (bits[i + 1] << (6 - i));
if (languagePacks.containsKey(languagePackId))
{
// Log.d(TAG, String.format("Language pack id is [%d].", languagePackId));
final String message = languagePacks.get(languagePackId).decodeMessage(bits, 8);
// Log.d(TAG, String.format("Message is [%s].", message));
return message;
}
}
return s;
}
public String messageToSsid(final String _message)
{
String s = compactMessage(_message);
int[] _result = this.encodeMessage(s);
int bitLength = _result[0];
int languageId = _result[1];
byte[] bits = new byte[MAX_BITS];
for (int i = 0; i < bits.length; i++)
bits[i] = 0;
languagePacks.get(languageId).encodeMessage(s, bits);
// String bitstring = new String();
// for (int i = 0; i < bits.length; i++)
// bitstring += bits[i] == 0 ? "0" : "1";
// Log.d(TAG, String.format("Bit string is %s.", bitstring));
BigInteger bigint = BigInteger.ZERO;
// most important stuff is at the beginning of bits,
// therefore: add it last, (put it in the LSB area)
for (int i = bits.length - 1; i >= 0; i--)
{
bigint = bigint.shiftLeft(1);
if (bits[i] == 1)
bigint = bigint.add(BigInteger.ONE);
}
// Log.d(TAG, String.format("BigInteger is %s.", bigint.toString()));
String ssid = AHOY_PREFIX_CHAR;
while (!bigint.equals(BigInteger.ZERO))
{
BigInteger[] result = bigint.divideAndRemainder(radix);
ssid += SSID_ALPHABET.charAt(result[1].intValue());
bigint = result[0];
}
while (ssid.length() < 31)
ssid += SSID_ALPHABET.charAt(0);
// Log.d(TAG, String.format("SSID is %s.", ssid));
return ssid;
}
public int[] encodeMessage(String _message)
{
String message = compactMessage(_message);
// Log.d(TAG, String.format("Encoding message: [%s]", message));
int minimumBitLength = -1;
int minimumBitLengthLang = -1;
for (int languageId : languagePacks.keySet())
{
ILanguagePack pack = languagePacks.get(languageId);
if (pack.canEncodeMessage(message))
{
short bitLength = pack.getEncodedMessageLength(message);
// Log.d(TAG, String.format("[%s]: %4d bits", pack.languageTag(), bitLength));
if (minimumBitLength == -1 || bitLength < minimumBitLength)
{
minimumBitLength = bitLength;
minimumBitLengthLang = languageId;
}
}
}
Log.d(TAG, String.format("Message is probably [%s], length is %3d bits: [%s]", languagePacks.get(minimumBitLengthLang).languageTag(), minimumBitLength, message));
int[] result = new int[2];
result[0] = minimumBitLength;
result[1] = minimumBitLengthLang;
return result;
}
private String compactMessage(final String message)
{
// remove leading and trailing spaces, replace spans of multiple spaces with a single space
return message.trim().replaceAll(" +", " ");
}
};
| UTF-8 | Java | 7,260 | java | 2_e2108c3bf6e4bf2c441de92331a83f07ac0dc698_ApMessageFilter_s.java | Java | []
| null | []
| package org.nhcham.ahoy;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import android.content.*;
import android.content.res.*;
import android.util.*;
public class ApMessageFilter
{
final static String SSID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final static String AHOY_PREFIX_CHAR = "a";
final static int MAX_BITS = 178;
final static String TAG = "ApMessageFilter";
public HashMap<Integer, ILanguagePack> languagePacks;
BigInteger radix = new BigInteger("62");
public ApMessageFilter(Context context)
{
languagePacks = new HashMap<Integer, ILanguagePack>();
try
{
BufferedReader r = new BufferedReader(new InputStreamReader(context.getAssets().open("languages.txt")));
String line;
while ((line = r.readLine()) != null)
{
line = line.trim();
int spaceOffset = line.indexOf(' ');
if (spaceOffset < 0)
continue;
int languageId = Integer.parseInt(line.substring(0, spaceOffset), 10);
int spaceOffset2 = line.indexOf(' ', spaceOffset + 1);
if (spaceOffset2 < 0)
continue;
String languageTag = line.substring(spaceOffset + 1, spaceOffset2);
String languageMarker = line.substring(spaceOffset2 + 1);
// Log.d(TAG, String.format("Now loading [%d] [%s]...", languageId, languageTag));
ILanguagePack pack = null;
if (languageTag.equals("utf8") || languageTag.equals("utf16"))
pack = new LanguagePackUtf(context, languageId, languageTag, languageMarker);
else
pack = new LanguagePack(context, languageId, languageTag, languageMarker);
languagePacks.put(languageId, pack);
}
} catch (IOException e) {
// TODO: what do we do with this?
}
}
public String ssidToMessage(final String s)
{
if (!s.startsWith(AHOY_PREFIX_CHAR))
return null;
if (s.length() != 31)
return null;
BigInteger bigint = BigInteger.ZERO;
for (int i = s.length() - 1; i >= 1; i--)
{
// TODO: This is slow.
int n = SSID_ALPHABET.indexOf(s.charAt(i));
if (n == -1)
return null;
bigint = bigint.multiply(radix);
// TODO: This is slow.
bigint = bigint.add(new BigInteger(String.format("%d", n)));
}
// Log.d(TAG, String.format("BigInt is %s.", bigint.toString()));
byte[] bits = new byte[MAX_BITS];
for (int i = 0; i < MAX_BITS; i++)
bits[i] = 0;
int offset = 0;
while (!bigint.equals(BigInteger.ZERO))
{
if (bigint.and(BigInteger.ONE).equals(BigInteger.ONE))
bits[offset] = 1;
offset++;
if (offset >= MAX_BITS)
// TODO: Should we return null here? Probably yes.
break;
bigint = bigint.shiftRight(1);
}
// String bitstring = new String();
// for (int i = 0; i < bits.length; i++)
// bitstring += bits[i] == 0 ? "0" : "1";
// Log.d(TAG, String.format("Bit string is %s.", bitstring));
if (bits[0] == 1)
{
// this is language pack 1 to 127...
int languagePackId = 0;
for (int i = 0; i < 7; i++)
languagePackId |= (bits[i + 1] << (6 - i));
if (languagePacks.containsKey(languagePackId))
{
// Log.d(TAG, String.format("Language pack id is [%d].", languagePackId));
final String message = languagePacks.get(languagePackId).decodeMessage(bits, 8);
// Log.d(TAG, String.format("Message is [%s].", message));
return message;
}
}
return s;
}
public String messageToSsid(final String _message)
{
String s = compactMessage(_message);
int[] _result = this.encodeMessage(s);
int bitLength = _result[0];
int languageId = _result[1];
byte[] bits = new byte[MAX_BITS];
for (int i = 0; i < bits.length; i++)
bits[i] = 0;
languagePacks.get(languageId).encodeMessage(s, bits);
// String bitstring = new String();
// for (int i = 0; i < bits.length; i++)
// bitstring += bits[i] == 0 ? "0" : "1";
// Log.d(TAG, String.format("Bit string is %s.", bitstring));
BigInteger bigint = BigInteger.ZERO;
// most important stuff is at the beginning of bits,
// therefore: add it last, (put it in the LSB area)
for (int i = bits.length - 1; i >= 0; i--)
{
bigint = bigint.shiftLeft(1);
if (bits[i] == 1)
bigint = bigint.add(BigInteger.ONE);
}
// Log.d(TAG, String.format("BigInteger is %s.", bigint.toString()));
String ssid = AHOY_PREFIX_CHAR;
while (!bigint.equals(BigInteger.ZERO))
{
BigInteger[] result = bigint.divideAndRemainder(radix);
ssid += SSID_ALPHABET.charAt(result[1].intValue());
bigint = result[0];
}
while (ssid.length() < 31)
ssid += SSID_ALPHABET.charAt(0);
// Log.d(TAG, String.format("SSID is %s.", ssid));
return ssid;
}
public int[] encodeMessage(String _message)
{
String message = compactMessage(_message);
// Log.d(TAG, String.format("Encoding message: [%s]", message));
int minimumBitLength = -1;
int minimumBitLengthLang = -1;
for (int languageId : languagePacks.keySet())
{
ILanguagePack pack = languagePacks.get(languageId);
if (pack.canEncodeMessage(message))
{
short bitLength = pack.getEncodedMessageLength(message);
// Log.d(TAG, String.format("[%s]: %4d bits", pack.languageTag(), bitLength));
if (minimumBitLength == -1 || bitLength < minimumBitLength)
{
minimumBitLength = bitLength;
minimumBitLengthLang = languageId;
}
}
}
Log.d(TAG, String.format("Message is probably [%s], length is %3d bits: [%s]", languagePacks.get(minimumBitLengthLang).languageTag(), minimumBitLength, message));
int[] result = new int[2];
result[0] = minimumBitLength;
result[1] = minimumBitLengthLang;
return result;
}
private String compactMessage(final String message)
{
// remove leading and trailing spaces, replace spans of multiple spaces with a single space
return message.trim().replaceAll(" +", " ");
}
};
| 7,260 | 0.515702 | 0.504545 | 185 | 38.237839 | 27.236654 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.848649 | false | false | 1 |
9510ee0bd11a11e51db928955a989b65919e954a | 11,742,440,609,121 | b3b1cf0246f91a84f96179dff340952c8b04d279 | /app/src/main/java/vam/whapp/LocalDB.java | ad8dbdc00dec725cd0cacfd5fa4611e216fc4f50 | []
| no_license | vamanocchio/WHapp | https://github.com/vamanocchio/WHapp | ea71526efa7e06fb2090f30f8377df459c1f7b2e | a5ebb59a5bb067d20ef1a5be6c3c53b49ac2bb51 | refs/heads/master | 2020-03-06T21:22:54.375000 | 2018-05-01T09:52:22 | 2018-05-01T09:52:22 | 127,076,142 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vam.whapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.*;
//import android.util.Pair;
import org.javatuples.*;
import org.javatuples.Pair;
//import org.javatuples.Sextet;
//import org.javatuples.Triplet;
import java.util.ArrayList;
import java.util.UUID;
/**
* Created by resnet on 3/28/18.
*/
public class LocalDB extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "localuser.db";
private static String TABLE_USER = "User";
private static String COLUMN_USER_ID = "user_id";
private static String COLUMN_USER_NAME = "user_name";
private static String COLUMN_PWORD = "password";
private static String COLUMN_EMAIL = "email";
private static String COLUMN_PHONE = "phone";
private static String TABLE_ITEM = "Item";
private static String COLUMN_ITEM_ID = "item_id"; //pk
private static String COLUMN_ITEM_NAME = "item_name";
private static String COLUMN_PRICE = "price";
private static String COLUMN_EXP = "exp_date";
private static String COLUMN_QTY = "quantity";
private static String COLUMN_LOC = "location";
private static String COLUMN_NOTES = "notes";
private static String TABLE_INV = "Inventory";
private static String COLUMN_INV_NUM = "inv_num"; //pk
private static String COLUMN_FK_WH_ID = "fk_wh_id"; //fk ref Warehouse(wh_id)
// private static String COLUMN_FK_TITLE = "fk_title"; //fk ref Warehouse(title)
private static String COLUMN_FK_ITEM_ID = "fk_item_id"; //fk ref Item(item_id)
private static String TABLE_WH = "Warehouse";
private static String COLUMN_WH_NUM = "warehouse_num"; //pk
private static String COLUMN_WH_ID = "wh_id"; //gen and verify is unique
private static String COLUMN_TITLE = "wh_title";
private static String COLUMN_FK_USER_ID = "fk_user_id";
SQLiteDatabase db;
private static final String CREATE_TABLE_USER = "create table User (user_id integer primary key autoincrement, user_name text not null, password text not null , email text not null, phone text)";
private static final String CREATE_TABLE_ITEM = "create table Item (item_id integer primary key autoincrement, item_name text not null, price real not null, exp_date integer, quantity integer, location text, notes text)";
private static final String CREATE_TABLE_WH = "create table Warehouse (warehouse_num integer primary key autoincrement, wh_id text unique not null, wh_title text not null, fk_user_id integer, foreign key (fk_user_id) references User(user_id))";
// private static final String CREATE_TABLE_INV = "create table Inventory (inv_num integer primary key autoincrement, fk_wh_id text not null, foreign key (fk_wh_id) references Warehouse(wh_id), fk_wh_title text not null, foreign key (fk_wh_title) references Warehouse(wh_title), fk_item_id integer not null, foreign key (fk_item_id) references Item(item_id))";
private static final String CREATE_TABLE_INV = "create table Inventory (inv_num integer primary key autoincrement, fk_wh_id text not null, fk_wh_title text not null, fk_item_id integer not null, foreign key (fk_item_id) references Item(item_id), foreign key (fk_wh_id) references Warehouse(wh_id), foreign key (fk_wh_title) references Warehouse(wh_title))";
// private static final String CREATE_TABLE_ITEM = "create table inventory (item text primary key not null, exp text not null, price text not null, location text not null, notes text)" ;
// private static final String CREATE_TABLE_LU = "create table lookup (item text primary key not null, exp text not null, price text not null, location text not null, notes text)";
// private static final String CREATE_TABLE_WH = "create table warehouses (id text primary key not null, owner text not null, members text)";
// private static final String CREATE_TABLE_USER = "create table user (email text primary key not null, password text not null, phone text not null)";
public LocalDB(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
long insertUser(Quartet<String, String, String, String> user){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getValue0());
values.put(COLUMN_PWORD, user.getValue1());
values.put(COLUMN_EMAIL, user.getValue2());
values.put(COLUMN_PHONE, user.getValue3());
long id = db.insert(TABLE_USER, null, values);
db.close();
return id;
}
long insertItem(Item i, String wh_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_ITEM_NAME, i.getName());
values.put(COLUMN_PRICE, i.getPrice());
values.put(COLUMN_EXP, i.getExp());
values.put(COLUMN_QTY, i.getQty());
values.put(COLUMN_LOC, i.getLoc());
values.put(COLUMN_NOTES, i.getNotes());
long id = db.insert(TABLE_ITEM, null, values);
insertInv(id, wh_id);
db.close();
return id;
}
String insertWH(String title, long user_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String id = genID();
values.put(COLUMN_WH_ID, id);
values.put(COLUMN_TITLE, title);
values.put(COLUMN_FK_USER_ID, user_id);
db.insert(TABLE_WH, null, values);
db.close();
return id;
}
long insertInv(long item_id, String wh_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FK_WH_ID, wh_id);
values.put(COLUMN_FK_ITEM_ID, item_id);
long id = db.insert(TABLE_INV, null, values);
db.close();
return id;
}
// long insertUser(User u){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
//// values.put(COLUMN_USER_ID, u.getID());
// values.put(COLUMN_USER_NAME, u.getName());
// values.put(COLUMN_EMAIL, u.getEmail());
// values.put(COLUMN_PHONE, u.getPhone());
// values.put(COLUMN_PWORD, u.getPword());
//
// long id = db.insert(TABLE_USER, null, values);
// db.close();
// return id;
// }
// long insertUser(User u){
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_EMAIL, u.getEmail());
// values.put(COLUMN_PWORD, u.getPword());
// values.put(COLUMN_PHONE, u.getPhone());
// values.put(COLUMN_ID, u.getId());
// long id = db.insert(TABLE_USER, null, values);
// db.close();
// return id;
// }
// void insertItem2(Item i){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_ITEM_ID, i.getID());
// values.put(COLUMN_ITEM_NAME, i.getName());
// values.put(COLUMN_PRICE, i.getPrice());
// values.put(COLUMN_EXP, i.getExp());
// values.put(COLUMN_QTY, i.getQty());
// values.put(COLUMN_LOC, i.getLoc());
// values.put(COLUMN_NOTES, i.getNotes());
//
// db.insert(TABLE_ITEM, null, values);
// db.close();
// }
// void insertItem(Item i){
//
// Log.d("InDB", "In DB, congrats");
// String output = (i.getName() + " " + i.getExp() + " " + i.getPrice() + " " + i.getLoc() + " " + i.getNotes());
// Log.d("DBTag", output);
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_ITEM, i.getName());
// values.put(COLUMN_EXP, i.getExp());
// values.put(COLUMN_PRICE, i.getPrice());
// values.put(COLUMN_LOC, i.getLoc());
// values.put(COLUMN_NOTES, i.getNotes());
//
// db.insert(TABLE_INV, null, values);
// db.close();
// }
// void insertInv(Inventory i){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_INV_ID, i.getID());
// values.put(COLUMN_TITLE, i.getTitle());
// //add items in Inventory class
//
// db.insert(TABLE_INV, null, values);
// }
//
//
// long insertWH(String title, long user_id){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// //values.put(COLUMN_WH_ID, i.getID());
// values.put(COLUMN_TITLE, title);
// //add
// }
Quintet<Long, String, String , String, String> getUser(long id){
Quintet<Long, String, String, String, String> user = new Quintet<>(null, null, null, null, null);
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_USER + " where user_id = " + id, null);
if(c!=null){
if(c.moveToFirst()){
do{
String name = c.getString(c.getColumnIndex("user_name"));
String pword = c.getString(c.getColumnIndex("pword"));
String email = c.getString(c.getColumnIndex("email"));
String phone = c.getString(c.getColumnIndex("phone"));
user = new Quintet<>(id, name, pword, email, phone);
}while(c.moveToNext());
}
}
db.close();
return user;
}
ArrayList<String> getInv(String wh_id){
ArrayList<String> list = new ArrayList<>();
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select Inventory.fk_item_id, Item.item_name from Inventory, Item where Inventory.fk_item_id = Item.item_id and Inventory.fk_wh_id = \"" + wh_id + "\"", null);
if(c!=null){
if(c.moveToFirst()){
do{
//long item_id = c.getLong(c.getColumnIndex("fk_item_id"));
String item_name = c.getString(c.getColumnIndex("item_name"));
list.add(item_name);
}while(c.moveToNext());
}
}
return list;
}
// SELECT
//WHERE inv.fk_item_id = item.item_id AND inv.fk_wh_id = "id"
Septet<Long, String, Float, Integer, Integer, String, String> getItem(long id){
Septet<Long, String, Float, Integer , Integer, String, String> item = new Septet<>(null, null, null, null, null, null, null);
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from Item where item_id = id", null);
if(c!=null){
if(c.moveToFirst()){
do{
String name = c.getString(c.getColumnIndex("item_name"));
Float price = c.getFloat(c.getColumnIndex("price"));
Integer exp = c.getInt(c.getColumnIndex("exp_date"));
Integer qty = c.getInt(c.getColumnIndex("quantity"));
String loc = c.getString(c.getColumnIndex("location"));
String notes = c.getString(c.getColumnIndex("notes"));
item = new Septet<>(id, name, price, exp, qty, loc, notes);
}while(c.moveToNext());
}
}
return item;
// select * from Item where item_id = id
}
String getWH_ID(String title, long curr_user){
String id = null;
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select wh_id from Warehouses where wh_title = title and fk_user_id = curr_user", null);
if(c!=null){
if(c.moveToFirst()){
do{
id = c.getString(c.getColumnIndex("wh_id"));
}while(c.moveToNext());
}
}
return id;
}
ArrayList<String> getWarehouses(){
ArrayList<String> list = new ArrayList<>();
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select wh_title from Warehouses", null);
if(c!=null){
if(c.moveToFirst()){
do{
String wh = c.getString(c.getColumnIndex("wh_title"));
list.add(wh);
}while(c.moveToNext());
}
}
db.close();
return list;
}
// ArrayList<String> getInv(){
// ArrayList<String> list = new ArrayList<String>();
//
// db = this.getWritableDatabase();
// Cursor c = db.rawQuery("select item from " + TABLE_INV, null);
//
// if(c!=null){
// if(c.moveToFirst()){
// do{
// String item = c.getString(c.getColumnIndex("item"));
// list.add(item);
//
// }while(c.moveToNext());
// }
// }
// db.close();
// return list;
// }
boolean isUser(String email, String pword){
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select email, password from " + TABLE_USER, null);
if(c!=null){
if(c.moveToFirst()){
do{
if(c.getString(0).equals(email)){
if(c.getString(1).equals(pword)) {
return true;
}else{ return false; }
}
}while(c.moveToNext());
}
}
return false;
}
String genID(){
return UUID.randomUUID().toString().replace("-", "");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_ITEM);
db.execSQL(CREATE_TABLE_WH);
db.execSQL(CREATE_TABLE_INV);
this.db = db;
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = "DROP TABLE IF EXISTS " + TABLE_INV + ", " + TABLE_ITEM + ", " + TABLE_WH + ", " + TABLE_USER;
db.execSQL(query);
this.onCreate(db);
}
}
| UTF-8 | Java | 14,170 | java | LocalDB.java | Java | [
{
"context": "rayList;\nimport java.util.UUID;\n\n/**\n * Created by resnet on 3/28/18.\n */\n\npublic class LocalDB extends SQL",
"end": 466,
"score": 0.9996846914291382,
"start": 460,
"tag": "USERNAME",
"value": "resnet"
},
{
"context": "d\";\n private static String COLUMN_USER_NAME = \"user_name\";\n private static String COLUMN_PWORD = \"passw",
"end": 804,
"score": 0.7005192637443542,
"start": 795,
"tag": "USERNAME",
"value": "user_name"
},
{
"context": "_name\";\n private static String COLUMN_PWORD = \"password\";\n private static String COLUMN_EMAIL = \"email",
"end": 857,
"score": 0.9990314245223999,
"start": 849,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package vam.whapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.*;
//import android.util.Pair;
import org.javatuples.*;
import org.javatuples.Pair;
//import org.javatuples.Sextet;
//import org.javatuples.Triplet;
import java.util.ArrayList;
import java.util.UUID;
/**
* Created by resnet on 3/28/18.
*/
public class LocalDB extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "localuser.db";
private static String TABLE_USER = "User";
private static String COLUMN_USER_ID = "user_id";
private static String COLUMN_USER_NAME = "user_name";
private static String COLUMN_PWORD = "<PASSWORD>";
private static String COLUMN_EMAIL = "email";
private static String COLUMN_PHONE = "phone";
private static String TABLE_ITEM = "Item";
private static String COLUMN_ITEM_ID = "item_id"; //pk
private static String COLUMN_ITEM_NAME = "item_name";
private static String COLUMN_PRICE = "price";
private static String COLUMN_EXP = "exp_date";
private static String COLUMN_QTY = "quantity";
private static String COLUMN_LOC = "location";
private static String COLUMN_NOTES = "notes";
private static String TABLE_INV = "Inventory";
private static String COLUMN_INV_NUM = "inv_num"; //pk
private static String COLUMN_FK_WH_ID = "fk_wh_id"; //fk ref Warehouse(wh_id)
// private static String COLUMN_FK_TITLE = "fk_title"; //fk ref Warehouse(title)
private static String COLUMN_FK_ITEM_ID = "fk_item_id"; //fk ref Item(item_id)
private static String TABLE_WH = "Warehouse";
private static String COLUMN_WH_NUM = "warehouse_num"; //pk
private static String COLUMN_WH_ID = "wh_id"; //gen and verify is unique
private static String COLUMN_TITLE = "wh_title";
private static String COLUMN_FK_USER_ID = "fk_user_id";
SQLiteDatabase db;
private static final String CREATE_TABLE_USER = "create table User (user_id integer primary key autoincrement, user_name text not null, password text not null , email text not null, phone text)";
private static final String CREATE_TABLE_ITEM = "create table Item (item_id integer primary key autoincrement, item_name text not null, price real not null, exp_date integer, quantity integer, location text, notes text)";
private static final String CREATE_TABLE_WH = "create table Warehouse (warehouse_num integer primary key autoincrement, wh_id text unique not null, wh_title text not null, fk_user_id integer, foreign key (fk_user_id) references User(user_id))";
// private static final String CREATE_TABLE_INV = "create table Inventory (inv_num integer primary key autoincrement, fk_wh_id text not null, foreign key (fk_wh_id) references Warehouse(wh_id), fk_wh_title text not null, foreign key (fk_wh_title) references Warehouse(wh_title), fk_item_id integer not null, foreign key (fk_item_id) references Item(item_id))";
private static final String CREATE_TABLE_INV = "create table Inventory (inv_num integer primary key autoincrement, fk_wh_id text not null, fk_wh_title text not null, fk_item_id integer not null, foreign key (fk_item_id) references Item(item_id), foreign key (fk_wh_id) references Warehouse(wh_id), foreign key (fk_wh_title) references Warehouse(wh_title))";
// private static final String CREATE_TABLE_ITEM = "create table inventory (item text primary key not null, exp text not null, price text not null, location text not null, notes text)" ;
// private static final String CREATE_TABLE_LU = "create table lookup (item text primary key not null, exp text not null, price text not null, location text not null, notes text)";
// private static final String CREATE_TABLE_WH = "create table warehouses (id text primary key not null, owner text not null, members text)";
// private static final String CREATE_TABLE_USER = "create table user (email text primary key not null, password text not null, phone text not null)";
public LocalDB(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
long insertUser(Quartet<String, String, String, String> user){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getValue0());
values.put(COLUMN_PWORD, user.getValue1());
values.put(COLUMN_EMAIL, user.getValue2());
values.put(COLUMN_PHONE, user.getValue3());
long id = db.insert(TABLE_USER, null, values);
db.close();
return id;
}
long insertItem(Item i, String wh_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_ITEM_NAME, i.getName());
values.put(COLUMN_PRICE, i.getPrice());
values.put(COLUMN_EXP, i.getExp());
values.put(COLUMN_QTY, i.getQty());
values.put(COLUMN_LOC, i.getLoc());
values.put(COLUMN_NOTES, i.getNotes());
long id = db.insert(TABLE_ITEM, null, values);
insertInv(id, wh_id);
db.close();
return id;
}
String insertWH(String title, long user_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String id = genID();
values.put(COLUMN_WH_ID, id);
values.put(COLUMN_TITLE, title);
values.put(COLUMN_FK_USER_ID, user_id);
db.insert(TABLE_WH, null, values);
db.close();
return id;
}
long insertInv(long item_id, String wh_id){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FK_WH_ID, wh_id);
values.put(COLUMN_FK_ITEM_ID, item_id);
long id = db.insert(TABLE_INV, null, values);
db.close();
return id;
}
// long insertUser(User u){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
//// values.put(COLUMN_USER_ID, u.getID());
// values.put(COLUMN_USER_NAME, u.getName());
// values.put(COLUMN_EMAIL, u.getEmail());
// values.put(COLUMN_PHONE, u.getPhone());
// values.put(COLUMN_PWORD, u.getPword());
//
// long id = db.insert(TABLE_USER, null, values);
// db.close();
// return id;
// }
// long insertUser(User u){
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_EMAIL, u.getEmail());
// values.put(COLUMN_PWORD, u.getPword());
// values.put(COLUMN_PHONE, u.getPhone());
// values.put(COLUMN_ID, u.getId());
// long id = db.insert(TABLE_USER, null, values);
// db.close();
// return id;
// }
// void insertItem2(Item i){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_ITEM_ID, i.getID());
// values.put(COLUMN_ITEM_NAME, i.getName());
// values.put(COLUMN_PRICE, i.getPrice());
// values.put(COLUMN_EXP, i.getExp());
// values.put(COLUMN_QTY, i.getQty());
// values.put(COLUMN_LOC, i.getLoc());
// values.put(COLUMN_NOTES, i.getNotes());
//
// db.insert(TABLE_ITEM, null, values);
// db.close();
// }
// void insertItem(Item i){
//
// Log.d("InDB", "In DB, congrats");
// String output = (i.getName() + " " + i.getExp() + " " + i.getPrice() + " " + i.getLoc() + " " + i.getNotes());
// Log.d("DBTag", output);
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_ITEM, i.getName());
// values.put(COLUMN_EXP, i.getExp());
// values.put(COLUMN_PRICE, i.getPrice());
// values.put(COLUMN_LOC, i.getLoc());
// values.put(COLUMN_NOTES, i.getNotes());
//
// db.insert(TABLE_INV, null, values);
// db.close();
// }
// void insertInv(Inventory i){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put(COLUMN_INV_ID, i.getID());
// values.put(COLUMN_TITLE, i.getTitle());
// //add items in Inventory class
//
// db.insert(TABLE_INV, null, values);
// }
//
//
// long insertWH(String title, long user_id){
//
// db = this.getWritableDatabase();
// ContentValues values = new ContentValues();
// //values.put(COLUMN_WH_ID, i.getID());
// values.put(COLUMN_TITLE, title);
// //add
// }
Quintet<Long, String, String , String, String> getUser(long id){
Quintet<Long, String, String, String, String> user = new Quintet<>(null, null, null, null, null);
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_USER + " where user_id = " + id, null);
if(c!=null){
if(c.moveToFirst()){
do{
String name = c.getString(c.getColumnIndex("user_name"));
String pword = c.getString(c.getColumnIndex("pword"));
String email = c.getString(c.getColumnIndex("email"));
String phone = c.getString(c.getColumnIndex("phone"));
user = new Quintet<>(id, name, pword, email, phone);
}while(c.moveToNext());
}
}
db.close();
return user;
}
ArrayList<String> getInv(String wh_id){
ArrayList<String> list = new ArrayList<>();
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select Inventory.fk_item_id, Item.item_name from Inventory, Item where Inventory.fk_item_id = Item.item_id and Inventory.fk_wh_id = \"" + wh_id + "\"", null);
if(c!=null){
if(c.moveToFirst()){
do{
//long item_id = c.getLong(c.getColumnIndex("fk_item_id"));
String item_name = c.getString(c.getColumnIndex("item_name"));
list.add(item_name);
}while(c.moveToNext());
}
}
return list;
}
// SELECT
//WHERE inv.fk_item_id = item.item_id AND inv.fk_wh_id = "id"
Septet<Long, String, Float, Integer, Integer, String, String> getItem(long id){
Septet<Long, String, Float, Integer , Integer, String, String> item = new Septet<>(null, null, null, null, null, null, null);
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from Item where item_id = id", null);
if(c!=null){
if(c.moveToFirst()){
do{
String name = c.getString(c.getColumnIndex("item_name"));
Float price = c.getFloat(c.getColumnIndex("price"));
Integer exp = c.getInt(c.getColumnIndex("exp_date"));
Integer qty = c.getInt(c.getColumnIndex("quantity"));
String loc = c.getString(c.getColumnIndex("location"));
String notes = c.getString(c.getColumnIndex("notes"));
item = new Septet<>(id, name, price, exp, qty, loc, notes);
}while(c.moveToNext());
}
}
return item;
// select * from Item where item_id = id
}
String getWH_ID(String title, long curr_user){
String id = null;
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select wh_id from Warehouses where wh_title = title and fk_user_id = curr_user", null);
if(c!=null){
if(c.moveToFirst()){
do{
id = c.getString(c.getColumnIndex("wh_id"));
}while(c.moveToNext());
}
}
return id;
}
ArrayList<String> getWarehouses(){
ArrayList<String> list = new ArrayList<>();
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select wh_title from Warehouses", null);
if(c!=null){
if(c.moveToFirst()){
do{
String wh = c.getString(c.getColumnIndex("wh_title"));
list.add(wh);
}while(c.moveToNext());
}
}
db.close();
return list;
}
// ArrayList<String> getInv(){
// ArrayList<String> list = new ArrayList<String>();
//
// db = this.getWritableDatabase();
// Cursor c = db.rawQuery("select item from " + TABLE_INV, null);
//
// if(c!=null){
// if(c.moveToFirst()){
// do{
// String item = c.getString(c.getColumnIndex("item"));
// list.add(item);
//
// }while(c.moveToNext());
// }
// }
// db.close();
// return list;
// }
boolean isUser(String email, String pword){
db = this.getWritableDatabase();
Cursor c = db.rawQuery("select email, password from " + TABLE_USER, null);
if(c!=null){
if(c.moveToFirst()){
do{
if(c.getString(0).equals(email)){
if(c.getString(1).equals(pword)) {
return true;
}else{ return false; }
}
}while(c.moveToNext());
}
}
return false;
}
String genID(){
return UUID.randomUUID().toString().replace("-", "");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_ITEM);
db.execSQL(CREATE_TABLE_WH);
db.execSQL(CREATE_TABLE_INV);
this.db = db;
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = "DROP TABLE IF EXISTS " + TABLE_INV + ", " + TABLE_ITEM + ", " + TABLE_WH + ", " + TABLE_USER;
db.execSQL(query);
this.onCreate(db);
}
}
| 14,172 | 0.588567 | 0.587579 | 404 | 34.074257 | 41.576298 | 363 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928218 | false | false | 1 |
d768c6c8230573f2be45880d9addf97348fc1dc8 | 32,727,650,803,437 | e71032ab2236ad1b4d17f1cea4f1cce362a24830 | /src/knowledgefruitflyfuzzy/FuzzyFJSP.java | 41fc206418d5ab1e6818c93cfafd668e8b35da29 | []
| no_license | PancrasD/RCPSPfriutflyfuzzy | https://github.com/PancrasD/RCPSPfriutflyfuzzy | aa6748b28c7db39e64f5a9b182b325468966aa74 | 4d9a2e57c5352788bdf52e8cd9aa74ae76f9c6fa | refs/heads/master | 2021-04-15T04:44:19.542000 | 2018-03-26T12:06:28 | 2018-03-26T12:06:28 | 126,793,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package knowledgefruitflyfuzzy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class FuzzyFJSP {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
if (args.length==1){
File ff = new File("case_def");
String[] fl = ff.list();
if (fl==null){
System.out.print("没有在case_def目录下找到算例文件");
return;
}
if (args[0].trim().toLowerCase().equals("f")){
PrintStream out = System.out;
for(int i = 0; i<fl.length; i++){
String _fn = "case_def/" + fl[i];
String _fo = "datalei/fuzzyFJSP_"+fl[i]+".txt";
NSFFA_algorithm(_fn,_fo);
}
System.setOut(out);
System.out.println(fl.length +"个案例算法计算完成");
return;
}
}else{
System.out.print("请输入参数:'f'、自学习算法");
return;
}
}
public static void NSFFA_algorithm(String casefile,String datafile) throws IOException{
//记录开始计算的时间,用于统计本算法的总时间
long startTime = System.currentTimeMillis();
// 创建案例类对象
Case project = new Case(casefile);
// 初始化种群
Population P = new Population(NSFFA.NS,project,true);
int generationCount = 0;
//循环迭代 算法指定的次数
while (generationCount < NSFFA.maxGenerations ) {
P = P.getOffSpring_NSFFA();
generationCount++;
}
//从最后得到种群中获取最优解集
Population solutions = Tools.getbestsolution(P, project);
File f = new File(datafile);
PrintStream ps = null;
try {
if (f.exists()) f.delete();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
ps = new PrintStream(fos);
System.setOut(ps);
//输出最优解集
Tools.printsolutions(solutions,startTime);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ps != null) ps.close();
}
}
}
| UTF-8 | Java | 2,247 | java | FuzzyFJSP.java | Java | []
| null | []
| package knowledgefruitflyfuzzy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class FuzzyFJSP {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
if (args.length==1){
File ff = new File("case_def");
String[] fl = ff.list();
if (fl==null){
System.out.print("没有在case_def目录下找到算例文件");
return;
}
if (args[0].trim().toLowerCase().equals("f")){
PrintStream out = System.out;
for(int i = 0; i<fl.length; i++){
String _fn = "case_def/" + fl[i];
String _fo = "datalei/fuzzyFJSP_"+fl[i]+".txt";
NSFFA_algorithm(_fn,_fo);
}
System.setOut(out);
System.out.println(fl.length +"个案例算法计算完成");
return;
}
}else{
System.out.print("请输入参数:'f'、自学习算法");
return;
}
}
public static void NSFFA_algorithm(String casefile,String datafile) throws IOException{
//记录开始计算的时间,用于统计本算法的总时间
long startTime = System.currentTimeMillis();
// 创建案例类对象
Case project = new Case(casefile);
// 初始化种群
Population P = new Population(NSFFA.NS,project,true);
int generationCount = 0;
//循环迭代 算法指定的次数
while (generationCount < NSFFA.maxGenerations ) {
P = P.getOffSpring_NSFFA();
generationCount++;
}
//从最后得到种群中获取最优解集
Population solutions = Tools.getbestsolution(P, project);
File f = new File(datafile);
PrintStream ps = null;
try {
if (f.exists()) f.delete();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
ps = new PrintStream(fos);
System.setOut(ps);
//输出最优解集
Tools.printsolutions(solutions,startTime);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ps != null) ps.close();
}
}
}
| 2,247 | 0.558695 | 0.556746 | 76 | 26.013159 | 19.631134 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.144737 | false | false | 1 |
73776cb6354fc594f692674a6c84e934836dca69 | 7,842,610,313,346 | d1faebeb59d51276c5c4f49ebbf5c22fa0bb2fab | /lion-client/src/main/java/com/dianping/lion/pigeon/ServiceChange.java | 0fe5298a8fd918ba037b30bcf8f43f6211ad8ed1 | []
| no_license | fv3386/lion | https://github.com/fv3386/lion | 91ced0c1aa2a750221bc9012f8e769635ab41abc | c83a38ee50e90c4225affd3f14c66a30dff731fd | refs/heads/master | 2020-12-25T11:06:23.997000 | 2013-05-29T09:55:43 | 2013-05-29T09:55:43 | 7,847,318 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dianping.lion.pigeon;
import java.util.List;
/**
* Comment of ServiceChange
* @author yong.you
*
*/
public interface ServiceChange {
//当服务器权重变化
public void onHostWeightChange(String host,int weight);
//当服务新增机器、修改机器。 String[]默认1维数组,ip+port
public void onServiceHostChange(String serviceName, List<String[]> hostList);
}
| UTF-8 | Java | 408 | java | ServiceChange.java | Java | [
{
"context": "ist;\r\n/**\r\n * Comment of ServiceChange\r\n * @author yong.you\r\n *\r\n */\r\npublic interface ServiceChange {\r\n\t//当服",
"end": 114,
"score": 0.9777281284332275,
"start": 106,
"tag": "USERNAME",
"value": "yong.you"
}
]
| null | []
| package com.dianping.lion.pigeon;
import java.util.List;
/**
* Comment of ServiceChange
* @author yong.you
*
*/
public interface ServiceChange {
//当服务器权重变化
public void onHostWeightChange(String host,int weight);
//当服务新增机器、修改机器。 String[]默认1维数组,ip+port
public void onServiceHostChange(String serviceName, List<String[]> hostList);
}
| 408 | 0.725989 | 0.723164 | 14 | 23.285715 | 22.330084 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 1 |
7ff45678923a23c61f25330533335c0269de3ec3 | 20,048,907,345,912 | 1207d02f5d77b02c6d3ad9faa327b431fc9fc703 | /app/src/main/java/com/example/movifirst/R_Hijo.java | e830975d78e35e6f0029cbaabbad20976fd7cc55 | []
| no_license | GuidoPinares/TecMoviles | https://github.com/GuidoPinares/TecMoviles | 1aa3fc5a3d6d14b7fc888a53857ee1710655353d | 2af125ae071f940d86658cc831bd32ae581a9a87 | refs/heads/master | 2020-06-13T08:22:03.424000 | 2019-07-01T04:18:36 | 2019-07-01T04:18:36 | 194,599,077 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.movifirst;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class R_Hijo extends AppCompatActivity {
private String idcliente;
private int idhijo;
private TextView tv_nombre, tv_apellidos, tv_dni, tv_edad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r__hijo);
idhijo = LastUserId();
idcliente = getIntent().getStringExtra("idcliente");
tv_nombre = (TextView)findViewById(R.id.txt_NombreHijo);
tv_apellidos = (TextView)findViewById(R.id.txt_ApellidosHijo);
tv_dni = (TextView)findViewById(R.id.txt_DNICliente);
tv_edad = (TextView)findViewById(R.id.txt_edad);
}
public void Agregar (View view) {
AddHijo();
Limpiar(view);
}
public void Limpiar (View view) {
final TextView label = (TextView)findViewById(R.id.txt_NombreHijo);
final TextView label1 = (TextView)findViewById(R.id.txt_ApellidosHijo);
final TextView label2 = (TextView)findViewById(R.id.txt_DNICliente);
final TextView label3 = (TextView)findViewById(R.id.txt_edad);
label.setText("");
label1.setText("");
label2.setText("");
label3.setText("");
}
public void AddHijo ()
{
AdminSQLite admin = new AdminSQLite(this,"dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
// Traer el ultimo idhijo
int hijo = LastUserId();
if(hijo != 0)
hijo++;
else
hijo = 1;
String nombre = tv_nombre.getText().toString();
String apellidos = tv_apellidos.getText().toString();
String dni = tv_dni.getText().toString();
String edad =tv_edad.getText().toString();
if(!nombre.isEmpty() && !apellidos.isEmpty() && !dni.isEmpty() && !edad.isEmpty()){
ContentValues registro = new ContentValues();
registro.put("idhijo", hijo);
registro.put("nombre", nombre);
registro.put("apellidos", apellidos);
registro.put("dni", dni);
registro.put("edad", edad);
registro.put("idcliente", idcliente);
BaseDeDatos.insert("hijo",null,registro);
BaseDeDatos.close();
tv_nombre.setText("");
tv_apellidos.setText("");
tv_dni.setText("");
tv_edad.setText("");
Toast.makeText(this,"Registro exitoso",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Debes llenar todos los campos", Toast.LENGTH_SHORT).show();
}
showLastHijo();
}
public int LastUserId ()
{
AdminSQLite admin = new AdminSQLite(this, "dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
Cursor fila = BaseDeDatos.rawQuery("SELECT MAX(idhijo) FROM hijo",null);
if(fila.moveToFirst()){
return fila.getInt(0);
} else {
return 0;
}
}
public void showLastHijo(){
AdminSQLite admin = new AdminSQLite(this, "dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
Cursor fila = BaseDeDatos.rawQuery("SELECT MAX(idhijo), idcliente FROM hijo",null);
if(fila.moveToFirst()){
Toast.makeText(this, "Reg:"+fila.getString(0)+", P:"+fila.getString(1), Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(this, "No hay movilidades", Toast.LENGTH_SHORT).show();
}
}
}
| UTF-8 | Java | 3,899 | java | R_Hijo.java | Java | []
| null | []
| package com.example.movifirst;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class R_Hijo extends AppCompatActivity {
private String idcliente;
private int idhijo;
private TextView tv_nombre, tv_apellidos, tv_dni, tv_edad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r__hijo);
idhijo = LastUserId();
idcliente = getIntent().getStringExtra("idcliente");
tv_nombre = (TextView)findViewById(R.id.txt_NombreHijo);
tv_apellidos = (TextView)findViewById(R.id.txt_ApellidosHijo);
tv_dni = (TextView)findViewById(R.id.txt_DNICliente);
tv_edad = (TextView)findViewById(R.id.txt_edad);
}
public void Agregar (View view) {
AddHijo();
Limpiar(view);
}
public void Limpiar (View view) {
final TextView label = (TextView)findViewById(R.id.txt_NombreHijo);
final TextView label1 = (TextView)findViewById(R.id.txt_ApellidosHijo);
final TextView label2 = (TextView)findViewById(R.id.txt_DNICliente);
final TextView label3 = (TextView)findViewById(R.id.txt_edad);
label.setText("");
label1.setText("");
label2.setText("");
label3.setText("");
}
public void AddHijo ()
{
AdminSQLite admin = new AdminSQLite(this,"dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
// Traer el ultimo idhijo
int hijo = LastUserId();
if(hijo != 0)
hijo++;
else
hijo = 1;
String nombre = tv_nombre.getText().toString();
String apellidos = tv_apellidos.getText().toString();
String dni = tv_dni.getText().toString();
String edad =tv_edad.getText().toString();
if(!nombre.isEmpty() && !apellidos.isEmpty() && !dni.isEmpty() && !edad.isEmpty()){
ContentValues registro = new ContentValues();
registro.put("idhijo", hijo);
registro.put("nombre", nombre);
registro.put("apellidos", apellidos);
registro.put("dni", dni);
registro.put("edad", edad);
registro.put("idcliente", idcliente);
BaseDeDatos.insert("hijo",null,registro);
BaseDeDatos.close();
tv_nombre.setText("");
tv_apellidos.setText("");
tv_dni.setText("");
tv_edad.setText("");
Toast.makeText(this,"Registro exitoso",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Debes llenar todos los campos", Toast.LENGTH_SHORT).show();
}
showLastHijo();
}
public int LastUserId ()
{
AdminSQLite admin = new AdminSQLite(this, "dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
Cursor fila = BaseDeDatos.rawQuery("SELECT MAX(idhijo) FROM hijo",null);
if(fila.moveToFirst()){
return fila.getInt(0);
} else {
return 0;
}
}
public void showLastHijo(){
AdminSQLite admin = new AdminSQLite(this, "dbmovilidad",null,1);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
Cursor fila = BaseDeDatos.rawQuery("SELECT MAX(idhijo), idcliente FROM hijo",null);
if(fila.moveToFirst()){
Toast.makeText(this, "Reg:"+fila.getString(0)+", P:"+fila.getString(1), Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(this, "No hay movilidades", Toast.LENGTH_SHORT).show();
}
}
}
| 3,899 | 0.616825 | 0.612465 | 120 | 31.491667 | 26.905699 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.816667 | false | false | 1 |
2e94ea4c8e65b1c26f74808869ae5fa8382266f4 | 19,284,403,168,033 | 1fea2d0a526115a6d6f880a1e7033940a898051b | /src/main/java/com/github/yungyu16/spring/http/interceptor/BaseMethodAnnotationInterceptor.java | 6400228e085436f0220a5ce0fab533717fa7a49c | [
"Apache-2.0"
]
| permissive | yungyu16/spring-boot-starter-retrofit2 | https://github.com/yungyu16/spring-boot-starter-retrofit2 | c826c8b2eaed4910d76da7fe73f34a6ee01dc389 | 685eebb37f9e0eb3ba9b5fdf32eff8b942af0bf3 | refs/heads/master | 2023-01-16T05:31:44.036000 | 2020-11-26T08:53:51 | 2020-11-26T08:53:51 | 301,428,279 | 10 | 1 | null | false | 2020-11-26T08:53:52 | 2020-10-05T14:03:30 | 2020-11-26T08:51:15 | 2020-11-26T08:53:51 | 117 | 8 | 0 | 0 | Java | false | false | package com.github.yungyu16.spring.http.interceptor;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import retrofit2.Invocation;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public abstract class BaseMethodAnnotationInterceptor<T extends Annotation> implements Interceptor {
private final Class<T> annotationClass;
public BaseMethodAnnotationInterceptor(Class<T> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException("annotationClass");
}
this.annotationClass = annotationClass;
}
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Invocation tag = request.tag(Invocation.class);
if (tag == null) {
return chain.proceed(request);
}
Method method = tag.method();
T annotation = method.getAnnotation(annotationClass);
if (annotation == null) {
return chain.proceed(request);
}
return doIntercept(method, annotation, chain, request);
}
protected abstract Response doIntercept(@NotNull Method method, @NotNull T annotation, @NotNull Chain chain, @NotNull Request request) throws IOException;
}
| UTF-8 | Java | 1,360 | java | BaseMethodAnnotationInterceptor.java | Java | [
{
"context": "package com.github.yungyu16.spring.http.interceptor;\n\nimport okhttp3.Intercep",
"end": 27,
"score": 0.9984939694404602,
"start": 19,
"tag": "USERNAME",
"value": "yungyu16"
}
]
| null | []
| package com.github.yungyu16.spring.http.interceptor;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import retrofit2.Invocation;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public abstract class BaseMethodAnnotationInterceptor<T extends Annotation> implements Interceptor {
private final Class<T> annotationClass;
public BaseMethodAnnotationInterceptor(Class<T> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException("annotationClass");
}
this.annotationClass = annotationClass;
}
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Invocation tag = request.tag(Invocation.class);
if (tag == null) {
return chain.proceed(request);
}
Method method = tag.method();
T annotation = method.getAnnotation(annotationClass);
if (annotation == null) {
return chain.proceed(request);
}
return doIntercept(method, annotation, chain, request);
}
protected abstract Response doIntercept(@NotNull Method method, @NotNull T annotation, @NotNull Chain chain, @NotNull Request request) throws IOException;
}
| 1,360 | 0.711765 | 0.707353 | 38 | 34.789474 | 31.670307 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 1 |
d1b248092135d86afcc50f7e22b5c0070905c35e | 8,778,913,177,408 | 12a67eb67785846d259d9ea2390efb2699192253 | /app/src/main/java/com/sa/arvi/scanner/MainActivity.java | 29776e6b9e3cc2ee7d2b67d0d4b9483690655be2 | []
| no_license | sankar810/Android_Scanner | https://github.com/sankar810/Android_Scanner | ae48225b9865502f31834bdd3912bc56cfe5d56d | e43d2b250342b152d73bc8717471e48e6b89b53f | refs/heads/master | 2020-04-21T11:06:47.190000 | 2019-02-07T02:59:46 | 2019-02-07T02:59:46 | 169,510,719 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sa.arvi.scanner;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
import com.google.firebase.ml.vision.text.RecognizedLanguage;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final int TEXT_RECO_REQ_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void textReco(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TEXT_RECO_REQ_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_RECO_REQ_CODE) {
Bitmap photo = (Bitmap)data.getExtras().get("data");
textRecognisation(photo);
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Operation Cancelled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Failed to Capture Image", Toast.LENGTH_SHORT).show();
}
}
private void textRecognisation(Bitmap photo) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionTextRecognizer textRecognizer = FirebaseVision.getInstance()
.getOnDeviceTextRecognizer();
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText result) {
// Task completed successfully
String resultText = result.getText();
for (FirebaseVisionText.TextBlock block: result.getTextBlocks()) {
String blockText = block.getText();
List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages();
Point[] blockCornerPoints = block.getCornerPoints();
Rect blockFrame = block.getBoundingBox();
Toast.makeText(MainActivity.this, "Recognized Text is:"+blockText, Toast.LENGTH_SHORT).show();
for (FirebaseVisionText.Line line: block.getLines()) {
String lineText = line.getText();
Float lineConfidence = line.getConfidence();
List<RecognizedLanguage> lineLanguages = line.getRecognizedLanguages();
Point[] lineCornerPoints = line.getCornerPoints();
Rect lineFrame = line.getBoundingBox();
for (FirebaseVisionText.Element element: line.getElements()) {
String elementText = element.getText();
Float elementConfidence = element.getConfidence();
List<RecognizedLanguage> elementLanguages = element.getRecognizedLanguages();
Point[] elementCornerPoints = element.getCornerPoints();
Rect elementFrame = element.getBoundingBox();
}
}
}
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
Toast.makeText(MainActivity.this, "Failed to Recognize", Toast.LENGTH_SHORT).show();
}
});
}
}
| UTF-8 | Java | 4,675 | java | MainActivity.java | Java | []
| null | []
| package com.sa.arvi.scanner;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
import com.google.firebase.ml.vision.text.RecognizedLanguage;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final int TEXT_RECO_REQ_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void textReco(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TEXT_RECO_REQ_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_RECO_REQ_CODE) {
Bitmap photo = (Bitmap)data.getExtras().get("data");
textRecognisation(photo);
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Operation Cancelled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Failed to Capture Image", Toast.LENGTH_SHORT).show();
}
}
private void textRecognisation(Bitmap photo) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionTextRecognizer textRecognizer = FirebaseVision.getInstance()
.getOnDeviceTextRecognizer();
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText result) {
// Task completed successfully
String resultText = result.getText();
for (FirebaseVisionText.TextBlock block: result.getTextBlocks()) {
String blockText = block.getText();
List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages();
Point[] blockCornerPoints = block.getCornerPoints();
Rect blockFrame = block.getBoundingBox();
Toast.makeText(MainActivity.this, "Recognized Text is:"+blockText, Toast.LENGTH_SHORT).show();
for (FirebaseVisionText.Line line: block.getLines()) {
String lineText = line.getText();
Float lineConfidence = line.getConfidence();
List<RecognizedLanguage> lineLanguages = line.getRecognizedLanguages();
Point[] lineCornerPoints = line.getCornerPoints();
Rect lineFrame = line.getBoundingBox();
for (FirebaseVisionText.Element element: line.getElements()) {
String elementText = element.getText();
Float elementConfidence = element.getConfidence();
List<RecognizedLanguage> elementLanguages = element.getRecognizedLanguages();
Point[] elementCornerPoints = element.getCornerPoints();
Rect elementFrame = element.getBoundingBox();
}
}
}
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
Toast.makeText(MainActivity.this, "Failed to Recognize", Toast.LENGTH_SHORT).show();
}
});
}
}
| 4,675 | 0.580107 | 0.579251 | 98 | 45.704082 | 31.671209 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632653 | false | false | 1 |
8fdbaac88c272970bc8ffa18c8f87f665caa918b | 1,692,217,131,547 | 076c9b66d0c9803eb425f0eb4daf6731a8d6fae2 | /spring-examples/01_preferred_beans/src/main/java/org/zezutom/springseries0114/part01/qualifier/Lemon.java | 6bf8498a76f93e228712b6e3dcea1a3626f50a42 | []
| no_license | santos-samuel/AllGit | https://github.com/santos-samuel/AllGit | ac75b072ec052ffa2addfb1e14b19f648cfd41ca | 69d79f534091aa42eab2928041538cef22f15448 | refs/heads/master | 2022-08-16T15:09:15.746000 | 2017-06-23T06:37:56 | 2017-06-23T06:37:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.zezutom.springseries0114.part01.qualifier;
@Service("lemon")
@Lazy
public class Lemon implements IFruit {
@Override
public String whoAmI() {
return "lemon";
}
}
| UTF-8 | Java | 195 | java | Lemon.java | Java | []
| null | []
| package org.zezutom.springseries0114.part01.qualifier;
@Service("lemon")
@Lazy
public class Lemon implements IFruit {
@Override
public String whoAmI() {
return "lemon";
}
}
| 195 | 0.682051 | 0.651282 | 11 | 16.727272 | 16.798759 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 1 |
c08871b2863367a5356e5b51b48f1c88a9c188e3 | 8,555,574,870,699 | 573ce86da1e76115af646c699fa81fd4e232bf81 | /src/main/java/pl/poznan/put/cs/school/gui/StudentsPresenceTableModel.java | 40eb8db8039386ce33df59e1b59b8a06354d881e | []
| no_license | nschlaffke/school-register | https://github.com/nschlaffke/school-register | ee7077320e9e0ba1ff61d31a351feaaeb5b0439a | 6419f5941614a92302fee0a5843ec124a70fc003 | refs/heads/master | 2021-05-14T02:37:37.677000 | 2018-04-06T16:37:14 | 2018-04-06T16:37:14 | 116,599,916 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.poznan.put.cs.school.gui;
import javax.swing.table.AbstractTableModel;
/**
* Created by ns on 30.01.18.
*/
public class StudentsPresenceTableModel extends AbstractTableModel
{
private Object data[][];
private int columnCount;
public StudentsPresenceTableModel(int columnCount, Object data[][])
{
super();
this.data = data;
this.columnCount = columnCount;
}
@Override
public String getColumnName(int column)
{
if (column == 0)
{
return "Przedmiot";
}
else
{
Integer c = column;
return c.toString();
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnCount;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if (data[rowIndex][columnIndex] == null)
{
return "";
}
return data[rowIndex][columnIndex];
}
}
| UTF-8 | Java | 1,058 | java | StudentsPresenceTableModel.java | Java | [
{
"context": "swing.table.AbstractTableModel;\n\n/**\n * Created by ns on 30.01.18.\n */\npublic class StudentsPresenceTab",
"end": 104,
"score": 0.9983678460121155,
"start": 102,
"tag": "USERNAME",
"value": "ns"
}
]
| null | []
| package pl.poznan.put.cs.school.gui;
import javax.swing.table.AbstractTableModel;
/**
* Created by ns on 30.01.18.
*/
public class StudentsPresenceTableModel extends AbstractTableModel
{
private Object data[][];
private int columnCount;
public StudentsPresenceTableModel(int columnCount, Object data[][])
{
super();
this.data = data;
this.columnCount = columnCount;
}
@Override
public String getColumnName(int column)
{
if (column == 0)
{
return "Przedmiot";
}
else
{
Integer c = column;
return c.toString();
}
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnCount;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if (data[rowIndex][columnIndex] == null)
{
return "";
}
return data[rowIndex][columnIndex];
}
}
| 1,058 | 0.563327 | 0.556711 | 54 | 18.592592 | 17.764423 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.296296 | false | false | 1 |
180381a61ec208fe2a0c9d6c32bbfc4f12140d7d | 32,452,772,894,802 | 3ab2a3294b954d3dbabf8007cb9416bbe193229b | /src/main/java/com/iotek/hrmgr/aspect/RPAspect.java | d1471b778c9234d9ceb18cd5d94842feff90b239 | []
| no_license | myTwilightSparkle/repo1 | https://github.com/myTwilightSparkle/repo1 | dcde0b48a6268351fbb7073e3aff651e1d034027 | 1b6cbb65f9cfff523062a6cc809aad73d87e2ec3 | refs/heads/master | 2020-03-23T19:52:42.619000 | 2018-07-31T03:40:57 | 2018-07-31T03:40:57 | 141,688,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iotek.hrmgr.aspect;
import com.iotek.hrmgr.entity.RwdPnt;
import com.iotek.hrmgr.entity.Visitor;
import com.iotek.hrmgr.service.AttendenceService;
import com.iotek.hrmgr.service.EmpService;
import com.iotek.hrmgr.service.RpService;
import com.iotek.hrmgr.service.VisitorService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
/**
* 生成待处理的奖惩记录
* 这个切面负责起诉
* (handled=0)
* 管理员通过RpController来判
* (handled=1)
* 工资结算流程只看已经判的记录
* (handled==1)
*/
@Aspect
@Component
public class RPAspect {
@Autowired
private RpService rpService;
@Autowired
private VisitorService visitorService;
@Autowired
private EmpService empService;
@Autowired
private AttendenceService attendenceService;
/*
迟到惩罚
*/
@Async
@Around("execution(* com.iotek.hrmgr.controller.AttendenceController.late())")
public void latePnt(ProceedingJoinPoint point) throws Throwable {
System.out.println("@Around:执行目标方法之前...");
//访问目标方法的参数:
Object[] args = point.getArgs();
//用改变后的参数执行目标方法
Object returnValue = point.proceed(args);
System.out.println("@Around:执行目标方法之后...");
//生成记录
//拿用户
String username = (String)SecurityUtils.getSubject().getPrincipal();
Visitor visitor = new Visitor();
visitor.setName(username);
visitor=visitorService.getVisitor(visitor);
RwdPnt rp = new RwdPnt();
rp.setVisitor(visitor);
rp.setDate(new Date());
rp.setCause("迟到");
//调用RpService的方法
rpService.addRP(rp);
}
/*
早退惩罚
*/
@Async
@Around("execution(* com.iotek.hrmgr.controller.AttendenceController.early())")
public void earlyPnt(ProceedingJoinPoint point) throws Throwable {
System.out.println("@Around:执行目标方法之前...");
//访问目标方法的参数:
Object[] args = point.getArgs();
//用改变后的参数执行目标方法
Object returnValue = point.proceed(args);
System.out.println("@Around:执行目标方法之后...");
//生成记录
//拿用户
String username = (String)SecurityUtils.getSubject().getPrincipal();
Visitor visitor = new Visitor();
visitor.setName(username);
visitor=visitorService.getVisitor(visitor);
RwdPnt rp = new RwdPnt();
rp.setVisitor(visitor);
rp.setDate(new Date());
rp.setCause("早退");
//调用RpService的方法
rpService.addRP(rp);
}
/*
找缺席
这不是个切面上的方法
*/
@Scheduled(cron="0,0,17,*")
public void absence(){
List<Visitor> rs = empService.getAllEmployeesAsVisitors();
for (Visitor v:rs){
if (attendenceService.hasClockin(v.getName())){
RwdPnt rp = new RwdPnt();
rp.setVisitor(v);
rp.setDate(new Date());
rp.setCause("缺勤");
rpService.addRP(rp);
}
}
}
}
| UTF-8 | Java | 3,677 | java | RPAspect.java | Java | [
{
"context": "itor = new Visitor();\n visitor.setName(username);\n visitor=visitorService.getVisitor(v",
"end": 1749,
"score": 0.9952689409255981,
"start": 1741,
"tag": "USERNAME",
"value": "username"
},
{
"context": " visitor = new Visitor();\n visitor.setName(username);\n visitor=visitorService.getVisitor(visit",
"end": 2618,
"score": 0.9694353938102722,
"start": 2610,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.iotek.hrmgr.aspect;
import com.iotek.hrmgr.entity.RwdPnt;
import com.iotek.hrmgr.entity.Visitor;
import com.iotek.hrmgr.service.AttendenceService;
import com.iotek.hrmgr.service.EmpService;
import com.iotek.hrmgr.service.RpService;
import com.iotek.hrmgr.service.VisitorService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
/**
* 生成待处理的奖惩记录
* 这个切面负责起诉
* (handled=0)
* 管理员通过RpController来判
* (handled=1)
* 工资结算流程只看已经判的记录
* (handled==1)
*/
@Aspect
@Component
public class RPAspect {
@Autowired
private RpService rpService;
@Autowired
private VisitorService visitorService;
@Autowired
private EmpService empService;
@Autowired
private AttendenceService attendenceService;
/*
迟到惩罚
*/
@Async
@Around("execution(* com.iotek.hrmgr.controller.AttendenceController.late())")
public void latePnt(ProceedingJoinPoint point) throws Throwable {
System.out.println("@Around:执行目标方法之前...");
//访问目标方法的参数:
Object[] args = point.getArgs();
//用改变后的参数执行目标方法
Object returnValue = point.proceed(args);
System.out.println("@Around:执行目标方法之后...");
//生成记录
//拿用户
String username = (String)SecurityUtils.getSubject().getPrincipal();
Visitor visitor = new Visitor();
visitor.setName(username);
visitor=visitorService.getVisitor(visitor);
RwdPnt rp = new RwdPnt();
rp.setVisitor(visitor);
rp.setDate(new Date());
rp.setCause("迟到");
//调用RpService的方法
rpService.addRP(rp);
}
/*
早退惩罚
*/
@Async
@Around("execution(* com.iotek.hrmgr.controller.AttendenceController.early())")
public void earlyPnt(ProceedingJoinPoint point) throws Throwable {
System.out.println("@Around:执行目标方法之前...");
//访问目标方法的参数:
Object[] args = point.getArgs();
//用改变后的参数执行目标方法
Object returnValue = point.proceed(args);
System.out.println("@Around:执行目标方法之后...");
//生成记录
//拿用户
String username = (String)SecurityUtils.getSubject().getPrincipal();
Visitor visitor = new Visitor();
visitor.setName(username);
visitor=visitorService.getVisitor(visitor);
RwdPnt rp = new RwdPnt();
rp.setVisitor(visitor);
rp.setDate(new Date());
rp.setCause("早退");
//调用RpService的方法
rpService.addRP(rp);
}
/*
找缺席
这不是个切面上的方法
*/
@Scheduled(cron="0,0,17,*")
public void absence(){
List<Visitor> rs = empService.getAllEmployeesAsVisitors();
for (Visitor v:rs){
if (attendenceService.hasClockin(v.getName())){
RwdPnt rp = new RwdPnt();
rp.setVisitor(v);
rp.setDate(new Date());
rp.setCause("缺勤");
rpService.addRP(rp);
}
}
}
}
| 3,677 | 0.637564 | 0.635464 | 119 | 27.008404 | 20.907356 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 1 |
39d716ff1db8b823b747574232966e82cbf0cba7 | 18,030,272,747,071 | 7ca728a275c2bdc378a9b93ef8a8415005c95453 | /common/java/com/cboe/instrumentationService/calculator/HeapInstrumentorCalculatedImpl.java | ec4593c68edf670c65081294662374389fb779a1 | []
| no_license | bellmit/MSFM | https://github.com/bellmit/MSFM | 8915538c18a0258dfba33224b07f0fd917d2a542 | 6b26c4768140990e64fa574aeb8350d0cb5fb024 | refs/heads/master | 2021-05-28T13:40:29.453000 | 2014-12-24T20:49:05 | 2014-12-24T20:49:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cboe.instrumentationService.calculator;
import com.cboe.instrumentationService.instrumentors.HeapInstrumentor;
import com.cboe.instrumentationService.instrumentors.CalculatedHeapInstrumentor;
import com.cboe.instrumentationService.factories.InstrumentorFactory;
/**
* HeapInstrumentorCalculatedImpl.java
*
*
* Created: Thu Sep 18 11:16:33 2003
*
* @author <a href="mailto:yaussy@devinfra2">Kevin Yaussy</a>
* @version 1.0
*/
class HeapInstrumentorCalculatedImpl implements HeapInstrumentor, CalculatedHeapInstrumentor {
private HeapInstrumentor raw;
private Object lock;
private long numSamples = 0;
// These are set at the beginning of a stats interval.
private long curIntervalMaxMemory = 0;
private long curIntervalTotalMemory = 0;
private long curIntervalFreeMemory = 0;
// Calculated values.
private long intervalMaxMemory = 0;
private long intervalTotalMemory = 0;
private long intervalFreeMemory = 0;
private InstrumentorFactory factory = null;
public HeapInstrumentorCalculatedImpl( HeapInstrumentor rawInst ) {
raw = rawInst;
lock = this;
} // HeapInstrumentorCalculatedImpl constructor
public void setLockObject( Object newLockObject ) {
lock = newLockObject;
raw.setLockObject( lock );
}
public void setFactory( InstrumentorFactory factory ) {
this.factory = factory;
}
public InstrumentorFactory getFactory() {
return factory;
}
public void sumIntervalTime( long timestamp ) {
// Not used here.
}
public void calculate( short calcToSampleFactor ) {
synchronized( lock ) {
intervalMaxMemory = raw.getMaxMemory() - curIntervalMaxMemory;
if ( intervalMaxMemory < 0 ) {
intervalMaxMemory = 0;
}
intervalTotalMemory = raw.getTotalMemory() - curIntervalTotalMemory;
if ( intervalTotalMemory < 0 ) {
intervalTotalMemory = 0;
}
intervalFreeMemory = raw.getFreeMemory() - curIntervalFreeMemory;
if ( intervalFreeMemory < 0 ) {
intervalFreeMemory = 0;
}
curIntervalMaxMemory = 0;
curIntervalTotalMemory = 0;
curIntervalFreeMemory = 0;
}
}
public long incSamples() {
numSamples++;
return numSamples;
}
public long getIntervalMaxMemory() {
synchronized( lock ) {
return intervalMaxMemory;
}
}
public long getIntervalTotalMemory() {
synchronized( lock ) {
return intervalTotalMemory;
}
}
public long getIntervalFreeMemory() {
synchronized( lock ) {
return intervalFreeMemory;
}
}
// Provide impls for interface, delegate everything to raw.
/**
* Sets new value to privateMode. This flag can control whether this
* instrumentor is exposed to the outside via any output
* mechanism.
*
* @param newValue a <code>boolean</code> value
*/
public void setPrivate( boolean newValue ) {
raw.setPrivate( newValue );
}
/**
* Returns value of privateMode. This flag can control whether this
* instrumentor is exposed to the outside via any output
* mechanism.
*
* @return a <code>boolean</code> value
*/
public boolean isPrivate() {
return raw.isPrivate();
}
/**
* Gets the value of key
*
* @return the value of key
*/
public byte[] getKey() {
return raw.getKey();
}
/**
* Sets the value of key
*
* @param argKey Value to assign to this.key
*/
public void setKey(byte[] argKey) {
raw.setKey( argKey );
}
/**
* Gets the value of name
*
* @return the value of name
*/
public String getName() {
return raw.getName();
}
/**
* Renames the instrumentor. Do not call this method
* if the instrumentor is currently registered with
* its factory. A rename without first unregistering
* the instrumentor will make a subsequent unregister
* call fail (it won't find the instrumentor, so the
* instrumentor won't be unregistered).
*
* So, before calling this method, unregister this
* instrumentor. After the rename, the instrumentor
* can be reregistered with the factory under the new
* name.
*
* @param newName a <code>String</code> value
*/
public void rename( String newName ) {
raw.rename( newName );
}
/**
* Gets the value of userData
*
* @return the value of userData
*/
public Object getUserData() {
return raw.getUserData();
}
/**
* Sets the value of userData
*
* @param argUserObject Value to assign to this.userData
*/
public void setUserData(Object argUserData) {
raw.setUserData( argUserData );
}
/**
* Gets the value of maxMemory
*
* @return the value of maxMemory
*/
public long getMaxMemory() {
return raw.getMaxMemory();
}
/**
* Sets the value of maxMemory
*
* @param argMaxMemory Value to assign to this.maxMemory
*/
public void setMaxMemory(long argMaxMemory) {
synchronized( lock ) {
if ( curIntervalMaxMemory == 0 ) {
curIntervalMaxMemory = raw.getMaxMemory();
}
}
raw.setMaxMemory( argMaxMemory );
}
/**
* Gets the value of totalMemory
*
* @return the value of totalMemory
*/
public long getTotalMemory() {
return raw.getTotalMemory();
}
/**
* Sets the value of totalMemory
*
* @param argTotalMemory Value to assign to this.totalMemory
*/
public void setTotalMemory(long argTotalMemory) {
synchronized( lock ) {
if ( curIntervalTotalMemory == 0 ) {
curIntervalTotalMemory = raw.getTotalMemory();
}
}
raw.setTotalMemory( argTotalMemory );
}
/**
* Gets the value of freeMemory
*
* @return the value of freeMemory
*/
public long getFreeMemory() {
return raw.getFreeMemory();
}
/**
* Sets the value of freeMemory
*
* @param argFreeMemory Value to assign to this.freeMemory
*/
public void setFreeMemory(long argFreeMemory) {
synchronized( lock ) {
if ( curIntervalFreeMemory == 0 ) {
curIntervalFreeMemory = raw.getFreeMemory();
}
}
raw.setFreeMemory( argFreeMemory );
}
/**
* Copies this HI to the given HI.
*
* @param hi a <code>HeapInstrumentor</code> value
*/
public void get( HeapInstrumentor hi ) {
raw.get( hi );
}
public String getToStringHeader( boolean showUserData, boolean showPrivate ) {
return "THIS getToStringHeader NOT IMPLEMENTED";
}
public String getToStringHeader() {
return "Name,IntMaxMemory,IntTotalMemory,IntFreeMemory";
}
public String toString( boolean showUserData, boolean showPrivate, String instNameToUse ) {
return raw.toString( showUserData, showPrivate, instNameToUse );
}
public String toString( String instNameToUse ) {
return instNameToUse + "," +
getIntervalMaxMemory() + "," +
getIntervalTotalMemory() + "," +
getIntervalFreeMemory();
}
public String toString() {
return toString( getName() );
}
} // HeapInstrumentorCalculatedImpl
| UTF-8 | Java | 6,652 | java | HeapInstrumentorCalculatedImpl.java | Java | [
{
"context": "ep 18 11:16:33 2003\n *\n * @author <a href=\"mailto:yaussy@devinfra2\">Kevin Yaussy</a>\n * @version 1.0\n */\nclass HeapI",
"end": 408,
"score": 0.996967613697052,
"start": 392,
"tag": "EMAIL",
"value": "yaussy@devinfra2"
},
{
"context": "3\n *\n * @author <a href=\"mailto:yaussy@devinfra2\">Kevin Yaussy</a>\n * @version 1.0\n */\nclass HeapInstrumentorCal",
"end": 422,
"score": 0.9998698234558105,
"start": 410,
"tag": "NAME",
"value": "Kevin Yaussy"
}
]
| null | []
| package com.cboe.instrumentationService.calculator;
import com.cboe.instrumentationService.instrumentors.HeapInstrumentor;
import com.cboe.instrumentationService.instrumentors.CalculatedHeapInstrumentor;
import com.cboe.instrumentationService.factories.InstrumentorFactory;
/**
* HeapInstrumentorCalculatedImpl.java
*
*
* Created: Thu Sep 18 11:16:33 2003
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.0
*/
class HeapInstrumentorCalculatedImpl implements HeapInstrumentor, CalculatedHeapInstrumentor {
private HeapInstrumentor raw;
private Object lock;
private long numSamples = 0;
// These are set at the beginning of a stats interval.
private long curIntervalMaxMemory = 0;
private long curIntervalTotalMemory = 0;
private long curIntervalFreeMemory = 0;
// Calculated values.
private long intervalMaxMemory = 0;
private long intervalTotalMemory = 0;
private long intervalFreeMemory = 0;
private InstrumentorFactory factory = null;
public HeapInstrumentorCalculatedImpl( HeapInstrumentor rawInst ) {
raw = rawInst;
lock = this;
} // HeapInstrumentorCalculatedImpl constructor
public void setLockObject( Object newLockObject ) {
lock = newLockObject;
raw.setLockObject( lock );
}
public void setFactory( InstrumentorFactory factory ) {
this.factory = factory;
}
public InstrumentorFactory getFactory() {
return factory;
}
public void sumIntervalTime( long timestamp ) {
// Not used here.
}
public void calculate( short calcToSampleFactor ) {
synchronized( lock ) {
intervalMaxMemory = raw.getMaxMemory() - curIntervalMaxMemory;
if ( intervalMaxMemory < 0 ) {
intervalMaxMemory = 0;
}
intervalTotalMemory = raw.getTotalMemory() - curIntervalTotalMemory;
if ( intervalTotalMemory < 0 ) {
intervalTotalMemory = 0;
}
intervalFreeMemory = raw.getFreeMemory() - curIntervalFreeMemory;
if ( intervalFreeMemory < 0 ) {
intervalFreeMemory = 0;
}
curIntervalMaxMemory = 0;
curIntervalTotalMemory = 0;
curIntervalFreeMemory = 0;
}
}
public long incSamples() {
numSamples++;
return numSamples;
}
public long getIntervalMaxMemory() {
synchronized( lock ) {
return intervalMaxMemory;
}
}
public long getIntervalTotalMemory() {
synchronized( lock ) {
return intervalTotalMemory;
}
}
public long getIntervalFreeMemory() {
synchronized( lock ) {
return intervalFreeMemory;
}
}
// Provide impls for interface, delegate everything to raw.
/**
* Sets new value to privateMode. This flag can control whether this
* instrumentor is exposed to the outside via any output
* mechanism.
*
* @param newValue a <code>boolean</code> value
*/
public void setPrivate( boolean newValue ) {
raw.setPrivate( newValue );
}
/**
* Returns value of privateMode. This flag can control whether this
* instrumentor is exposed to the outside via any output
* mechanism.
*
* @return a <code>boolean</code> value
*/
public boolean isPrivate() {
return raw.isPrivate();
}
/**
* Gets the value of key
*
* @return the value of key
*/
public byte[] getKey() {
return raw.getKey();
}
/**
* Sets the value of key
*
* @param argKey Value to assign to this.key
*/
public void setKey(byte[] argKey) {
raw.setKey( argKey );
}
/**
* Gets the value of name
*
* @return the value of name
*/
public String getName() {
return raw.getName();
}
/**
* Renames the instrumentor. Do not call this method
* if the instrumentor is currently registered with
* its factory. A rename without first unregistering
* the instrumentor will make a subsequent unregister
* call fail (it won't find the instrumentor, so the
* instrumentor won't be unregistered).
*
* So, before calling this method, unregister this
* instrumentor. After the rename, the instrumentor
* can be reregistered with the factory under the new
* name.
*
* @param newName a <code>String</code> value
*/
public void rename( String newName ) {
raw.rename( newName );
}
/**
* Gets the value of userData
*
* @return the value of userData
*/
public Object getUserData() {
return raw.getUserData();
}
/**
* Sets the value of userData
*
* @param argUserObject Value to assign to this.userData
*/
public void setUserData(Object argUserData) {
raw.setUserData( argUserData );
}
/**
* Gets the value of maxMemory
*
* @return the value of maxMemory
*/
public long getMaxMemory() {
return raw.getMaxMemory();
}
/**
* Sets the value of maxMemory
*
* @param argMaxMemory Value to assign to this.maxMemory
*/
public void setMaxMemory(long argMaxMemory) {
synchronized( lock ) {
if ( curIntervalMaxMemory == 0 ) {
curIntervalMaxMemory = raw.getMaxMemory();
}
}
raw.setMaxMemory( argMaxMemory );
}
/**
* Gets the value of totalMemory
*
* @return the value of totalMemory
*/
public long getTotalMemory() {
return raw.getTotalMemory();
}
/**
* Sets the value of totalMemory
*
* @param argTotalMemory Value to assign to this.totalMemory
*/
public void setTotalMemory(long argTotalMemory) {
synchronized( lock ) {
if ( curIntervalTotalMemory == 0 ) {
curIntervalTotalMemory = raw.getTotalMemory();
}
}
raw.setTotalMemory( argTotalMemory );
}
/**
* Gets the value of freeMemory
*
* @return the value of freeMemory
*/
public long getFreeMemory() {
return raw.getFreeMemory();
}
/**
* Sets the value of freeMemory
*
* @param argFreeMemory Value to assign to this.freeMemory
*/
public void setFreeMemory(long argFreeMemory) {
synchronized( lock ) {
if ( curIntervalFreeMemory == 0 ) {
curIntervalFreeMemory = raw.getFreeMemory();
}
}
raw.setFreeMemory( argFreeMemory );
}
/**
* Copies this HI to the given HI.
*
* @param hi a <code>HeapInstrumentor</code> value
*/
public void get( HeapInstrumentor hi ) {
raw.get( hi );
}
public String getToStringHeader( boolean showUserData, boolean showPrivate ) {
return "THIS getToStringHeader NOT IMPLEMENTED";
}
public String getToStringHeader() {
return "Name,IntMaxMemory,IntTotalMemory,IntFreeMemory";
}
public String toString( boolean showUserData, boolean showPrivate, String instNameToUse ) {
return raw.toString( showUserData, showPrivate, instNameToUse );
}
public String toString( String instNameToUse ) {
return instNameToUse + "," +
getIntervalMaxMemory() + "," +
getIntervalTotalMemory() + "," +
getIntervalFreeMemory();
}
public String toString() {
return toString( getName() );
}
} // HeapInstrumentorCalculatedImpl
| 6,637 | 0.702345 | 0.697234 | 290 | 21.937931 | 21.649153 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.441379 | false | false | 1 |
d5bf4799e94ba589a9f8bcab544a577c85db3778 | 26,010,321,964,406 | 54bd2ef2481bf3502cb554158c1d5874aab8491c | /src/main/java/com/gochinatv/cdn/api/geo/GetLocation.java | 4752f9d0ffe6218e9222ab239fbbd1097b936509 | [
"Apache-2.0"
]
| permissive | jacktomcat/aggregation | https://github.com/jacktomcat/aggregation | d9d352aac93d72422148974f4b0834922aad92d8 | 2138d68e9accb8e624d9f071fae867c18af45b8b | refs/heads/master | 2022-12-25T09:09:38.327000 | 2019-06-14T03:42:11 | 2019-06-14T03:42:11 | 72,733,338 | 0 | 1 | Apache-2.0 | false | 2022-12-16T06:16:00 | 2016-11-03T10:15:44 | 2019-06-14T03:45:20 | 2022-12-16T06:15:57 | 551 | 0 | 1 | 16 | Java | false | false | package com.gochinatv.cdn.api.geo;
import java.net.URL;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class GetLocation {
public static void main(String[] args) {
String add = getAdd("111.985261","32.102603");
JSONObject jsonObject = JSONObject.parseObject(add);
JSONArray jsonArray = jsonObject.getJSONArray("addrList");
JSONObject object = (JSONObject)jsonArray.get(0);
System.out.println(object.toJSONString());
//String allAdd = j_2.getString("admName");
//String arr[] = allAdd.split(",");
//System.out.println("省:" + arr[0] + "\n市:" + arr[1] + "\n区:" + arr[2]);
}
public static String getAdd(String log, String lat) {
// lat 小 log 大
// 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
String res = "";
try {
URL url = new URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
} catch (Exception e) {
System.out.println("error in wapaction,and e is " + e.getMessage());
}
System.out.println(res);
return res;
}
}
| UTF-8 | Java | 1,577 | java | GetLocation.java | Java | []
| null | []
| package com.gochinatv.cdn.api.geo;
import java.net.URL;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class GetLocation {
public static void main(String[] args) {
String add = getAdd("111.985261","32.102603");
JSONObject jsonObject = JSONObject.parseObject(add);
JSONArray jsonArray = jsonObject.getJSONArray("addrList");
JSONObject object = (JSONObject)jsonArray.get(0);
System.out.println(object.toJSONString());
//String allAdd = j_2.getString("admName");
//String arr[] = allAdd.split(",");
//System.out.println("省:" + arr[0] + "\n市:" + arr[1] + "\n区:" + arr[2]);
}
public static String getAdd(String log, String lat) {
// lat 小 log 大
// 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
String res = "";
try {
URL url = new URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
} catch (Exception e) {
System.out.println("error in wapaction,and e is " + e.getMessage());
}
System.out.println(res);
return res;
}
}
| 1,577 | 0.652232 | 0.624917 | 44 | 32.113636 | 25.40778 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.477273 | false | false | 1 |
08fea9024e3617205d4717e509518901b3e9b7a3 | 17,274,358,468,522 | db34f500cb6bb5da81ca38db3e2312066d998338 | /Library/src/main/java/com/inke/library/core/display/BitmapDisplayer.java | 23c6cc6175a087150240f53285ea1bef44c7ee6d | []
| no_license | guanzhen-yun/myimageloadscheme | https://github.com/guanzhen-yun/myimageloadscheme | 6a5978c978b2768da63ab4bd65bc4f278f007ffa | c877dca57bf116477120bb47d218c07ff37c0cd6 | refs/heads/master | 2023-08-30T00:54:05.189000 | 2021-11-02T06:11:53 | 2021-11-02T06:11:53 | 423,726,758 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inke.library.core.display;
import android.graphics.Bitmap;
import com.inke.library.core.LoadedFrom;
import com.inke.library.core.view.ImageAware;
/**
* Bitmap显示接口
*/
public interface BitmapDisplayer {
void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom);
}
| UTF-8 | Java | 308 | java | BitmapDisplayer.java | Java | []
| null | []
| package com.inke.library.core.display;
import android.graphics.Bitmap;
import com.inke.library.core.LoadedFrom;
import com.inke.library.core.view.ImageAware;
/**
* Bitmap显示接口
*/
public interface BitmapDisplayer {
void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom);
}
| 308 | 0.78 | 0.78 | 15 | 19 | 22.931784 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 1 |
1d6ac820fa0a62352fafe64f62c2576b566ad623 | 23,673,859,748,029 | bc8125826fff2b73909b41f194f48708708822a9 | /src/VC/server/dao/StuDAO.java | c3406f1f6614eed32db5ff8e331d5da28f12bf79 | []
| no_license | scenerysong/javaServer | https://github.com/scenerysong/javaServer | 6fbed5c2c9ffc9fc4fb84713639ae28808bf30db | 7abacf54e0148ca05ab9b2af42762c92bd3c32cf | refs/heads/master | 2020-03-27T04:44:02.339000 | 2018-09-14T06:38:16 | 2018-09-14T06:38:16 | 145,964,249 | 0 | 1 | null | false | 2018-09-05T07:51:50 | 2018-08-24T08:25:11 | 2018-09-05T07:16:42 | 2018-09-05T07:16:40 | 2,967 | 0 | 1 | 2 | Java | false | null | package VC.server.dao;
/**
* class {@code StuDAO} is the subclass of class {@link VC.server.db.DBstart} for database.
* <p>it is used to get the information from database according to the requirements and do some simple data processing if needed.
* including methods for maintaining the personal information of students.
*
* @author Guangwei Xiong
* @author Linsong Wang
*
* @version 1.0
*/
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import VC.common.Course;
import VC.common.User;
import VC.server.db.DBstart;
public class StuDAO extends DBstart{
public StuDAO() throws ClassNotFoundException, SQLException {
super();
}
// TODO Auto-generated constructor stub
/**
*
* get the personal information of a user in database.
*
* <p>the name of user is needed.
*
* <p><pre>{@code
* show how to use this method
*
* String user = "wls";
* StuDAO studao = new StuDAO();
* User infofwls = studao.getUserInf(user);
*
* }</pre>
*
* @param Users
* @return the information of Users
* @throws SQLException
*/
public User getUserInf(String Users) throws SQLException{
sql = "select * from login where usrname = ?";
ps = ct.prepareStatement(sql);
ps.setString(1, Users);
rs = ps.executeQuery();
User inf = new User();
while(rs.next()) {
inf.setBirthday(rs.getString("birthday"));
System.out.println(rs.getString("personname"));
inf.setPersonname(rs.getString("personname"));
inf.setRace(rs.getString("race"));
inf.setSex(rs.getString("sex"));
inf.setUsername("Users");
}
return inf;
}
/**
* update the personal information of a user in database
*
* <p><pre>{@code
* show how to use this method
*
* String user = "wls";
* User inf = new User();
* inf.setBirthday("1998/1/1");
*
* StuDAO studao = new StuDAO();
* studao.modifyInf(user, inf);
*
* }</pre>
*
* @param Users
* @param inf
* @return the result of the operation
* @throws SQLException
*/
public boolean modifyinf(String Users, User inf) throws SQLException {
sql = "update login set personname = ?, sex = ?, race = ?, birthday = ?"
+ "where usrname = ?";
ps = ct.prepareStatement(sql);
ps.setString(1, inf.getPersonname());
ps.setString(2, inf.getSex());
ps.setString(3, inf.getRace());
ps.setString(4, inf.getBirthday());
ps.setString(5, Users);
if(ps.executeUpdate() > 0) return true;
return false;
}
}
| UTF-8 | Java | 2,589 | java | StuDAO.java | Java | [
{
"context": "personal information of students.\r\n * \r\n * @author Guangwei Xiong\r\n * @author Linsong Wang \r\n *\r\n * @version 1.0\r\n*",
"end": 361,
"score": 0.9998166561126709,
"start": 347,
"tag": "NAME",
"value": "Guangwei Xiong"
},
{
"context": "dents.\r\n * \r\n * @author Guangwei Xiong\r\n * @author Linsong Wang \r\n *\r\n * @version 1.0\r\n*/\r\n\r\nimport java.sql.SQLE",
"end": 386,
"score": 0.9998443126678467,
"start": 374,
"tag": "NAME",
"value": "Linsong Wang"
},
{
"context": "how to use this method\r\n\t * \r\n\t * String user = \"wls\";\r\n\t * StuDAO studao = new StuDAO();\r\n\t * User in",
"end": 950,
"score": 0.7042931914329529,
"start": 948,
"tag": "USERNAME",
"value": "ls"
},
{
"context": " how to use this method\r\n\t * \r\n\t * String user = \"wls\";\r\n\t * User inf = new User();\r\n\t * inf.setBirthda",
"end": 1850,
"score": 0.9995975494384766,
"start": 1847,
"tag": "USERNAME",
"value": "wls"
}
]
| null | []
| package VC.server.dao;
/**
* class {@code StuDAO} is the subclass of class {@link VC.server.db.DBstart} for database.
* <p>it is used to get the information from database according to the requirements and do some simple data processing if needed.
* including methods for maintaining the personal information of students.
*
* @author <NAME>
* @author <NAME>
*
* @version 1.0
*/
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import VC.common.Course;
import VC.common.User;
import VC.server.db.DBstart;
public class StuDAO extends DBstart{
public StuDAO() throws ClassNotFoundException, SQLException {
super();
}
// TODO Auto-generated constructor stub
/**
*
* get the personal information of a user in database.
*
* <p>the name of user is needed.
*
* <p><pre>{@code
* show how to use this method
*
* String user = "wls";
* StuDAO studao = new StuDAO();
* User infofwls = studao.getUserInf(user);
*
* }</pre>
*
* @param Users
* @return the information of Users
* @throws SQLException
*/
public User getUserInf(String Users) throws SQLException{
sql = "select * from login where usrname = ?";
ps = ct.prepareStatement(sql);
ps.setString(1, Users);
rs = ps.executeQuery();
User inf = new User();
while(rs.next()) {
inf.setBirthday(rs.getString("birthday"));
System.out.println(rs.getString("personname"));
inf.setPersonname(rs.getString("personname"));
inf.setRace(rs.getString("race"));
inf.setSex(rs.getString("sex"));
inf.setUsername("Users");
}
return inf;
}
/**
* update the personal information of a user in database
*
* <p><pre>{@code
* show how to use this method
*
* String user = "wls";
* User inf = new User();
* inf.setBirthday("1998/1/1");
*
* StuDAO studao = new StuDAO();
* studao.modifyInf(user, inf);
*
* }</pre>
*
* @param Users
* @param inf
* @return the result of the operation
* @throws SQLException
*/
public boolean modifyinf(String Users, User inf) throws SQLException {
sql = "update login set personname = ?, sex = ?, race = ?, birthday = ?"
+ "where usrname = ?";
ps = ct.prepareStatement(sql);
ps.setString(1, inf.getPersonname());
ps.setString(2, inf.getSex());
ps.setString(3, inf.getRace());
ps.setString(4, inf.getBirthday());
ps.setString(5, Users);
if(ps.executeUpdate() > 0) return true;
return false;
}
}
| 2,575 | 0.627269 | 0.621475 | 103 | 23.058252 | 22.203308 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.650485 | false | false | 1 |
0ffd27505af3c8ec8302a2139b37a9883117c8fb | 18,245,021,104,693 | 86078ed15a652f40fd7cf37e0e733ef6405a9009 | /src/stackOverflow/studentWithMaxAverageGrade/Student.java | 8a3269d0cf8bcd6bbfee466ef14328e3979eb785 | []
| no_license | o-morenets/My | https://github.com/o-morenets/My | 2a5fde9707b14f9a0f7f450481de76757b0e9a8c | 36c244770c7913cd4033cdeba639ba3c88060ef5 | refs/heads/master | 2023-04-25T10:11:08.076000 | 2021-05-11T13:55:37 | 2021-05-11T13:55:37 | 220,635,458 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stackOverflow.studentWithMaxAverageGrade;
public class Student {
private double averageGrade;
public Student(double averageGrade) {
this.averageGrade = averageGrade;
}
public double getAverageGrade() {
return averageGrade;
}
@Override
public String toString() {
return "Student{" +
"averageGrade=" + averageGrade +
'}';
}
}
| UTF-8 | Java | 424 | java | Student.java | Java | []
| null | []
| package stackOverflow.studentWithMaxAverageGrade;
public class Student {
private double averageGrade;
public Student(double averageGrade) {
this.averageGrade = averageGrade;
}
public double getAverageGrade() {
return averageGrade;
}
@Override
public String toString() {
return "Student{" +
"averageGrade=" + averageGrade +
'}';
}
}
| 424 | 0.608491 | 0.608491 | 20 | 20.200001 | 17.089764 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
ea1e5b4f7e543db2e72312e5647a71a8cf5bc917 | 3,728,031,630,818 | 42ba1cb6e787a6c017a88145df6c04d81e464b18 | /oyx-backend/oyx-authority/oyx-authority-biz/src/main/java/com/github/oyx/authority/service/defaults/impl/GlobalUserServiceImpl.java | 43269d00e649fc636db994fe1429f6ca053ba999 | []
| no_license | oyx888/oyx-admin-cloud | https://github.com/oyx888/oyx-admin-cloud | 303f7521df7dd34bb04c43ca84612520c1741c91 | 0805f58c4cd86594cf1de930a298dbbb4a086a96 | refs/heads/master | 2020-09-26T12:10:47.877000 | 2019-12-25T09:20:43 | 2019-12-25T09:20:43 | 226,251,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.oyx.authority.service.defaults.impl;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.oyx.authority.dao.defaults.GlobalUserMapper;
import com.github.oyx.authority.dto.defaults.GlobalUserSaveDTO;
import com.github.oyx.authority.dto.defaults.GlobalUserUpdateDTO;
import com.github.oyx.authority.entity.auth.User;
import com.github.oyx.authority.entity.defaults.GlobalUser;
import com.github.oyx.authority.service.auth.UserService;
import com.github.oyx.authority.service.defaults.GlobalUserService;
import com.github.oyx.context.BaseContextHandler;
import com.github.oyx.database.mybatis.conditions.Wraps;
import com.github.oyx.dozer.DozerUtils;
import com.github.oyx.utils.BizAssert;
import com.github.oyx.utils.StrHelper;
import cn.hutool.core.util.StrUtil;
/**
* @author OYX
* @date 2019-12-16 14:10
*/
@Service
public class GlobalUserServiceImpl extends ServiceImpl<GlobalUserMapper, GlobalUser> implements GlobalUserService {
@Autowired
private UserService userService;
@Autowired
private DozerUtils dozer;
@Override
public Boolean check(String tenantCode, String account) {
int globalUserCount = super.count(Wraps.<GlobalUser>lbQ()
.eq(GlobalUser::getTenantCode, tenantCode)
.eq(GlobalUser::getAccount, account));
if (globalUserCount > 0) {
return false;
}
BaseContextHandler.setTenant(tenantCode);
int userCount = userService.count(Wraps.<User>lbQ()
.eq(User::getAccount, account));
if (userCount > 0) {
return false;
}
return true;
}
@Override
public GlobalUser save(GlobalUserSaveDTO globalUserSaveDTO) {
BizAssert.equals(globalUserSaveDTO.getPassword(), globalUserSaveDTO.getConfirmPassword(), "2次输入的密码不一致");
String md5Password = DigestUtils.md5Hex(globalUserSaveDTO.getPassword());
GlobalUser globalAccount = dozer.map(globalUserSaveDTO, GlobalUser.class);
// defaults 库
globalAccount.setPassword(md5Password);
save(globalAccount);
// 保存到租户库
BaseContextHandler.setTenant(globalUserSaveDTO.getTenantCode());
// 1,保存租户用户 // 租户库
User user = dozer.map(globalUserSaveDTO, User.class);
user.setId(globalAccount.getId());
user.setPassword(md5Password)
.setName(StrHelper.getOrDef(globalUserSaveDTO.getName(), globalUserSaveDTO.getAccount()))
.setStatus(true);
userService.save(user);
return globalAccount;
}
@Override
public GlobalUser update(GlobalUserUpdateDTO data) {
if (StrUtil.isNotBlank(data.getPassword()) || StrUtil.isNotBlank(data.getPassword())) {
BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
}
GlobalUser globalUser = dozer.map(data, GlobalUser.class);
User user = dozer.map(data, User.class);
if (StrUtil.isNotBlank(data.getPassword())) {
String md5Password = DigestUtils.md5Hex(data.getPassword());
globalUser.setPassword(md5Password);
user.setPassword(md5Password);
}
updateById(globalUser);
BaseContextHandler.setTenant(data.getTenantCode());
userService.updateById(user);
return globalUser;
}
@Override
public void removeByIds(String tenantCode, Long[] ids) {
List<Long> idList = Arrays.asList(ids);
super.removeByIds(idList);
BaseContextHandler.setTenant(tenantCode);
userService.removeByIds(idList);
//TODO 缓存 & T人下线
}
}
| UTF-8 | Java | 3,951 | java | GlobalUserServiceImpl.java | Java | [
{
"context": "mport cn.hutool.core.util.StrUtil;\n\n/**\n * @author OYX\n * @date 2019-12-16 14:10\n */\n@Service\npublic cla",
"end": 1047,
"score": 0.9993990063667297,
"start": 1044,
"tag": "USERNAME",
"value": "OYX"
},
{
"context": "ord(), \"2次输入的密码不一致\");\n String md5Password = DigestUtils.md5Hex(globalUserSaveDTO.getPassword());\n ",
"end": 2110,
"score": 0.8807922601699829,
"start": 2104,
"tag": "PASSWORD",
"value": "Digest"
},
{
"context": " // defaults 库\n globalAccount.setPassword(md5Password);\n save(globalAccount);\n // 保存到租户库\n",
"end": 2307,
"score": 0.9972882270812988,
"start": 2296,
"tag": "PASSWORD",
"value": "md5Password"
},
{
"context": "(globalAccount.getId());\n user.setPassword(md5Password)\n .setName(StrHelper.getOrDef(glob",
"end": 2598,
"score": 0.9993187785148621,
"start": 2587,
"tag": "PASSWORD",
"value": "md5Password"
},
{
"context": "Blank(data.getPassword())) {\n String md5Password = DigestUtils.md5Hex(data.getPassword());",
"end": 3270,
"score": 0.5300074219703674,
"start": 3269,
"tag": "PASSWORD",
"value": "5"
},
{
"context": "getPassword())) {\n String md5Password = DigestUtils.md5Hex(data.getPassword());\n globalUse",
"end": 3292,
"score": 0.8347969055175781,
"start": 3281,
"tag": "PASSWORD",
"value": "DigestUtils"
},
{
"context": " {\n String md5Password = DigestUtils.md5Hex(data.getPassword());\n globalUser.setPa",
"end": 3299,
"score": 0.715727686882019,
"start": 3295,
"tag": "PASSWORD",
"value": "5Hex"
},
{
"context": "etPassword());\n globalUser.setPassword(md5Password);\n\n user.setPassword(md5Password);\n ",
"end": 3367,
"score": 0.9919061064720154,
"start": 3356,
"tag": "PASSWORD",
"value": "md5Password"
},
{
"context": "sword(md5Password);\n\n user.setPassword(md5Password);\n }\n updateById(globalUser);\n ",
"end": 3411,
"score": 0.9980683922767639,
"start": 3400,
"tag": "PASSWORD",
"value": "md5Password"
}
]
| null | []
| package com.github.oyx.authority.service.defaults.impl;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.oyx.authority.dao.defaults.GlobalUserMapper;
import com.github.oyx.authority.dto.defaults.GlobalUserSaveDTO;
import com.github.oyx.authority.dto.defaults.GlobalUserUpdateDTO;
import com.github.oyx.authority.entity.auth.User;
import com.github.oyx.authority.entity.defaults.GlobalUser;
import com.github.oyx.authority.service.auth.UserService;
import com.github.oyx.authority.service.defaults.GlobalUserService;
import com.github.oyx.context.BaseContextHandler;
import com.github.oyx.database.mybatis.conditions.Wraps;
import com.github.oyx.dozer.DozerUtils;
import com.github.oyx.utils.BizAssert;
import com.github.oyx.utils.StrHelper;
import cn.hutool.core.util.StrUtil;
/**
* @author OYX
* @date 2019-12-16 14:10
*/
@Service
public class GlobalUserServiceImpl extends ServiceImpl<GlobalUserMapper, GlobalUser> implements GlobalUserService {
@Autowired
private UserService userService;
@Autowired
private DozerUtils dozer;
@Override
public Boolean check(String tenantCode, String account) {
int globalUserCount = super.count(Wraps.<GlobalUser>lbQ()
.eq(GlobalUser::getTenantCode, tenantCode)
.eq(GlobalUser::getAccount, account));
if (globalUserCount > 0) {
return false;
}
BaseContextHandler.setTenant(tenantCode);
int userCount = userService.count(Wraps.<User>lbQ()
.eq(User::getAccount, account));
if (userCount > 0) {
return false;
}
return true;
}
@Override
public GlobalUser save(GlobalUserSaveDTO globalUserSaveDTO) {
BizAssert.equals(globalUserSaveDTO.getPassword(), globalUserSaveDTO.getConfirmPassword(), "2次输入的密码不一致");
String md5Password = <PASSWORD>Utils.md5Hex(globalUserSaveDTO.getPassword());
GlobalUser globalAccount = dozer.map(globalUserSaveDTO, GlobalUser.class);
// defaults 库
globalAccount.setPassword(<PASSWORD>);
save(globalAccount);
// 保存到租户库
BaseContextHandler.setTenant(globalUserSaveDTO.getTenantCode());
// 1,保存租户用户 // 租户库
User user = dozer.map(globalUserSaveDTO, User.class);
user.setId(globalAccount.getId());
user.setPassword(<PASSWORD>)
.setName(StrHelper.getOrDef(globalUserSaveDTO.getName(), globalUserSaveDTO.getAccount()))
.setStatus(true);
userService.save(user);
return globalAccount;
}
@Override
public GlobalUser update(GlobalUserUpdateDTO data) {
if (StrUtil.isNotBlank(data.getPassword()) || StrUtil.isNotBlank(data.getPassword())) {
BizAssert.equals(data.getPassword(), data.getConfirmPassword(), "2次输入的密码不一致");
}
GlobalUser globalUser = dozer.map(data, GlobalUser.class);
User user = dozer.map(data, User.class);
if (StrUtil.isNotBlank(data.getPassword())) {
String md5Password = <PASSWORD>.md<PASSWORD>(data.getPassword());
globalUser.setPassword(<PASSWORD>);
user.setPassword(<PASSWORD>);
}
updateById(globalUser);
BaseContextHandler.setTenant(data.getTenantCode());
userService.updateById(user);
return globalUser;
}
@Override
public void removeByIds(String tenantCode, Long[] ids) {
List<Long> idList = Arrays.asList(ids);
super.removeByIds(idList);
BaseContextHandler.setTenant(tenantCode);
userService.removeByIds(idList);
//TODO 缓存 & T人下线
}
}
| 3,956 | 0.699819 | 0.693361 | 105 | 35.866665 | 27.614374 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 1 |
489954441ca8c8b3468eaeb992a5d4b2f20f8361 | 30,897,994,789,843 | 0db4abf77aefedfb5509a73df5c77e7393290ca0 | /src/main/java/by/tc/film_rating/util/PaginatorUtil.java | 36a17914766d3b0c3728750f66d13e7dec314c6d | []
| no_license | TopJavaDev/final | https://github.com/TopJavaDev/final | 332ef72f5d4189b13a1e028a822a008a6282a8bc | 317cbb1009a8a45cfe14a5abad06f79c9a368f5e | refs/heads/master | 2020-03-06T22:38:25.932000 | 2018-06-06T21:07:29 | 2018-06-06T21:07:29 | 127,108,631 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.tc.film_rating.util;
import javax.servlet.http.HttpServletRequest;
import static by.tc.film_rating.util.StringUtils.isNull;
public class PaginatorUtil {
private static final Integer DEFAULT_PAGE_SIZE = 5;
private static final Integer DEFAULT_PAGE_NUMBER = 1;
public static Integer[] getPagesProperties(HttpServletRequest req) {
String numberOfPage = req.getParameter("pageNumber");
String sizeOfPage = req.getParameter("pageSize");
Integer pageNumber = isNull(numberOfPage) ? DEFAULT_PAGE_NUMBER : Integer.parseInt(numberOfPage);
Integer pageSize = isNull(sizeOfPage) ? DEFAULT_PAGE_SIZE : Integer.parseInt(sizeOfPage);
return new Integer[] {pageNumber, pageSize};
}
}
| UTF-8 | Java | 741 | java | PaginatorUtil.java | Java | []
| null | []
| package by.tc.film_rating.util;
import javax.servlet.http.HttpServletRequest;
import static by.tc.film_rating.util.StringUtils.isNull;
public class PaginatorUtil {
private static final Integer DEFAULT_PAGE_SIZE = 5;
private static final Integer DEFAULT_PAGE_NUMBER = 1;
public static Integer[] getPagesProperties(HttpServletRequest req) {
String numberOfPage = req.getParameter("pageNumber");
String sizeOfPage = req.getParameter("pageSize");
Integer pageNumber = isNull(numberOfPage) ? DEFAULT_PAGE_NUMBER : Integer.parseInt(numberOfPage);
Integer pageSize = isNull(sizeOfPage) ? DEFAULT_PAGE_SIZE : Integer.parseInt(sizeOfPage);
return new Integer[] {pageNumber, pageSize};
}
}
| 741 | 0.734143 | 0.731444 | 19 | 38 | 33.29454 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 8 |
97764f89851b02646268b9e40b28ef0ac2099a48 | 3,582,002,793,520 | f9837ead637251a76a38def466882048851e874e | /src/test/java/pl/adma/guru/springframework/sfgdi/sfgdi/controllers/ConstructorInjectedControllerTest.java | 101464a9fdfe0fec4b7c143c7994f5aebc603b06 | []
| no_license | slewdziu99/sfg-di | https://github.com/slewdziu99/sfg-di | 7885b545b02517d9101b36b06b47e7beee6b2188 | 670b1089446e4b1edfaea63a28cd60c1e5fbfcd9 | refs/heads/master | 2021-04-13T13:45:37.963000 | 2020-03-29T16:51:59 | 2020-03-29T16:51:59 | 249,166,659 | 0 | 0 | null | false | 2020-10-13T20:39:23 | 2020-03-22T11:12:54 | 2020-03-29T16:52:14 | 2020-10-13T20:39:22 | 60 | 0 | 0 | 1 | Java | false | false | package pl.adma.guru.springframework.sfgdi.sfgdi.controllers;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pl.adma.guru.springframework.sfgdi.sfgdi.services.ContructorGreetingService;
class ConstructorInjectedControllerTest {
ConstructorInjectedController controller;
@BeforeEach
void setUp() {
controller = new ConstructorInjectedController(new ContructorGreetingService());
}
@Test
void test() {
System.out.println(controller.getGreeting());
}
}
| UTF-8 | Java | 557 | java | ConstructorInjectedControllerTest.java | Java | []
| null | []
| package pl.adma.guru.springframework.sfgdi.sfgdi.controllers;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pl.adma.guru.springframework.sfgdi.sfgdi.services.ContructorGreetingService;
class ConstructorInjectedControllerTest {
ConstructorInjectedController controller;
@BeforeEach
void setUp() {
controller = new ConstructorInjectedController(new ContructorGreetingService());
}
@Test
void test() {
System.out.println(controller.getGreeting());
}
}
| 557 | 0.797127 | 0.797127 | 24 | 22.208334 | 26.551804 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 8 |
8fdb46ee204fdfe3f121d3fcc569bed48d97f293 | 3,582,002,793,385 | dfa944adbc7dfa23bcba502db2d0b67b4d519dca | /src/main/java/com/pearson/Interface/Windows/CreateNewRuleWindow.java | 4161eb972d7d350d0922bd9f367a9ea49b0d54ef | []
| no_license | jds86930/DataScrubber | https://github.com/jds86930/DataScrubber | f3ce2bb93d29288a05a751c8e4b9f8f49393c9f4 | 4fbb5b230077a2568d739cb0cc3808c70edc5189 | refs/heads/master | 2021-01-15T15:58:15.639000 | 2013-08-07T16:44:55 | 2013-08-07T16:44:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.pearson.Interface.Windows;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.sql.SQLException;
/**
*
* @author Ruslan Kiselev
*/
public class CreateNewRuleWindow extends JDialog {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(CreateNewRuleWindow.class.getName());
private javax.swing.JButton cancelButton = new JButton();
private javax.swing.JLabel chooseTypeLabel = new JLabel();
private javax.swing.JLabel createLable = new JLabel();
private javax.swing.JPanel jPanel1 = new JPanel();
private javax.swing.JButton newShuffleRuleButton = new JButton();
private javax.swing.JButton newSubstitutionRuleButton = new JButton();
/**
* Creates new form CreateNewRuleWindow
*/
public CreateNewRuleWindow() {
initComponents();
setModalityType(ModalityType.APPLICATION_MODAL);
}
private void initComponents() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createLable.setText("Create a New Masking Rule");
chooseTypeLabel.setText("Choose the Masking Rule Type");
newSubstitutionRuleButton.setText("New Substitution Rule...");
newSubstitutionRuleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newSubstitutionRuleButtonActionPerformed(evt);
}
});
newSubstitutionRuleButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
newSubstitutionRuleButtonKeyPressed(evt);
}
});
newShuffleRuleButton.setText("New Shuffle Rule...");
newShuffleRuleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newShuffleRuleButtonActionPerformed(evt);
}
});
newShuffleRuleButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
newShuffleRuleButtonKeyPressed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
cancelButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
cancelButtonKeyPressed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(132, 132, 132)
.addComponent(createLable))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(124, 124, 124)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(newSubstitutionRuleButton)
.addComponent(chooseTypeLabel)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(newShuffleRuleButton))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(cancelButton)))
.addContainerGap(127, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(createLable)
.addGap(18, 18, 18)
.addComponent(chooseTypeLabel)
.addGap(18, 18, 18)
.addComponent(newSubstitutionRuleButton)
.addGap(18, 18, 18)
.addComponent(newShuffleRuleButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
.addComponent(cancelButton)
.addGap(60, 60, 60))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void newSubstitutionRuleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSubstitutionRuleButtonActionPerformed
// open the new substitution rule window
NewSubstitutionRuleWindow rw = null;
try {
rw = new NewSubstitutionRuleWindow();
} catch (SQLException ex) {
}
dispose();
rw.setVisible(true);
rw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}//GEN-LAST:event_newSubstitutionRuleButtonActionPerformed
private void newShuffleRuleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newShuffleRuleButtonActionPerformed
// open the new shuffle rule window
NewShuffleRuleWindow srw = null;
try {
srw = new NewShuffleRuleWindow();
} catch (SQLException ex) {
}
dispose();
srw.setVisible(true);
srw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}//GEN-LAST:event_newShuffleRuleButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
// action event for cancle button
dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void newSubstitutionRuleButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_newSubstitutionRuleButtonKeyPressed
// if enter key is pressed by user on new shuffle rule button, open the new substitution rule window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
NewSubstitutionRuleWindow rw = null;
try {
rw = new NewSubstitutionRuleWindow();
} catch (SQLException ex) {
}
dispose();
rw.setVisible(true);
rw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}
}//GEN-LAST:event_newSubstitutionRuleButtonKeyPressed
private void newShuffleRuleButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_newShuffleRuleButtonKeyPressed
// if enter key is pressed by user on new shuffle rule button, open the new shuffle rule window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
NewShuffleRuleWindow srw = null;
try {
srw = new NewShuffleRuleWindow();
} catch (SQLException ex) {
}
dispose();
srw.setVisible(true);
srw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}
}//GEN-LAST:event_newShuffleRuleButtonKeyPressed
private void cancelButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cancelButtonKeyPressed
// if enter key is pressed on cancel button, close the window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
dispose();
}
}//GEN-LAST:event_cancelButtonKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CreateNewRuleWindow().setVisible(true);
}
});
}
}
| UTF-8 | Java | 10,298 | java | CreateNewRuleWindow.java | Java | [
{
"context": "\nimport java.sql.SQLException;\n\n\n/**\n *\n * @author Ruslan Kiselev\n */\npublic class CreateNewRuleWindow extends JDia",
"end": 259,
"score": 0.9998598694801331,
"start": 245,
"tag": "NAME",
"value": "Ruslan Kiselev"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.pearson.Interface.Windows;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.sql.SQLException;
/**
*
* @author <NAME>
*/
public class CreateNewRuleWindow extends JDialog {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(CreateNewRuleWindow.class.getName());
private javax.swing.JButton cancelButton = new JButton();
private javax.swing.JLabel chooseTypeLabel = new JLabel();
private javax.swing.JLabel createLable = new JLabel();
private javax.swing.JPanel jPanel1 = new JPanel();
private javax.swing.JButton newShuffleRuleButton = new JButton();
private javax.swing.JButton newSubstitutionRuleButton = new JButton();
/**
* Creates new form CreateNewRuleWindow
*/
public CreateNewRuleWindow() {
initComponents();
setModalityType(ModalityType.APPLICATION_MODAL);
}
private void initComponents() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createLable.setText("Create a New Masking Rule");
chooseTypeLabel.setText("Choose the Masking Rule Type");
newSubstitutionRuleButton.setText("New Substitution Rule...");
newSubstitutionRuleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newSubstitutionRuleButtonActionPerformed(evt);
}
});
newSubstitutionRuleButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
newSubstitutionRuleButtonKeyPressed(evt);
}
});
newShuffleRuleButton.setText("New Shuffle Rule...");
newShuffleRuleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newShuffleRuleButtonActionPerformed(evt);
}
});
newShuffleRuleButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
newShuffleRuleButtonKeyPressed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
cancelButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
cancelButtonKeyPressed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(132, 132, 132)
.addComponent(createLable))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(124, 124, 124)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(newSubstitutionRuleButton)
.addComponent(chooseTypeLabel)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(newShuffleRuleButton))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(cancelButton)))
.addContainerGap(127, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(createLable)
.addGap(18, 18, 18)
.addComponent(chooseTypeLabel)
.addGap(18, 18, 18)
.addComponent(newSubstitutionRuleButton)
.addGap(18, 18, 18)
.addComponent(newShuffleRuleButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
.addComponent(cancelButton)
.addGap(60, 60, 60))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void newSubstitutionRuleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSubstitutionRuleButtonActionPerformed
// open the new substitution rule window
NewSubstitutionRuleWindow rw = null;
try {
rw = new NewSubstitutionRuleWindow();
} catch (SQLException ex) {
}
dispose();
rw.setVisible(true);
rw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}//GEN-LAST:event_newSubstitutionRuleButtonActionPerformed
private void newShuffleRuleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newShuffleRuleButtonActionPerformed
// open the new shuffle rule window
NewShuffleRuleWindow srw = null;
try {
srw = new NewShuffleRuleWindow();
} catch (SQLException ex) {
}
dispose();
srw.setVisible(true);
srw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}//GEN-LAST:event_newShuffleRuleButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
// action event for cancle button
dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void newSubstitutionRuleButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_newSubstitutionRuleButtonKeyPressed
// if enter key is pressed by user on new shuffle rule button, open the new substitution rule window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
NewSubstitutionRuleWindow rw = null;
try {
rw = new NewSubstitutionRuleWindow();
} catch (SQLException ex) {
}
dispose();
rw.setVisible(true);
rw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}
}//GEN-LAST:event_newSubstitutionRuleButtonKeyPressed
private void newShuffleRuleButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_newShuffleRuleButtonKeyPressed
// if enter key is pressed by user on new shuffle rule button, open the new shuffle rule window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
NewShuffleRuleWindow srw = null;
try {
srw = new NewShuffleRuleWindow();
} catch (SQLException ex) {
}
dispose();
srw.setVisible(true);
srw.setDefaultCloseOperation(MainWindow.HIDE_ON_CLOSE);
}
}//GEN-LAST:event_newShuffleRuleButtonKeyPressed
private void cancelButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cancelButtonKeyPressed
// if enter key is pressed on cancel button, close the window
int kc = evt.getKeyCode();
if (kc == evt.VK_ENTER){
dispose();
}
}//GEN-LAST:event_cancelButtonKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateNewRuleWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CreateNewRuleWindow().setVisible(true);
}
});
}
}
| 10,290 | 0.644494 | 0.636046 | 237 | 42.451477 | 34.928299 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481013 | false | false | 8 |
98e448ab19c1243f2339ad46c48b9e62c77135fd | 38,800,734,605,503 | d96f36987296d1288a189d71e804d25785e91115 | /examples/MonkeyTrap/src/trap/ErrorState.java | fe042803a5e68bb0df2aa056a43978781516b5a2 | [
"BSD-3-Clause"
]
| permissive | jMonkeyEngine-Contributions/zay-es | https://github.com/jMonkeyEngine-Contributions/zay-es | 08d283df9a9affae79b178d75d4b85f059756858 | b024f67a7120a43f5bddb61ba16875077dc5b183 | refs/heads/master | 2023-07-11T07:32:42.326000 | 2023-01-27T01:17:16 | 2023-01-27T01:17:16 | 41,591,265 | 58 | 39 | BSD-3-Clause | false | 2023-06-23T20:33:39 | 2015-08-29T11:28:54 | 2023-04-04T09:21:09 | 2023-06-23T20:33:38 | 79,485 | 48 | 17 | 6 | Java | false | false | /*
* $Id$
*
* Copyright (c) 2013 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package trap;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Command;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.component.BorderLayout;
import com.simsilica.lemur.component.QuadBackgroundComponent;
import com.simsilica.lemur.event.BaseAppState;
import com.simsilica.lemur.event.ConsumingMouseListener;
import com.simsilica.lemur.style.ElementId;
/**
* State that takes over the screen and pops up an
* error dialog.
*
* @author Paul Speed
*/
public class ErrorState extends BaseAppState {
public static final ElementId POPUP_ID = new ElementId("error.popup");
public static final ElementId TITLE_ID = new ElementId("error.title");
public static final ElementId MESSAGE_ID = new ElementId("error.message");
public static final ElementId CLOSE_ID = new ElementId("error.close.button");
private Container blocker;
private Container popup;
private String title;
private String message;
private String style;
public ErrorState( String title, String message, String style ) {
this.title = title;
this.message = message;
this.style = style;
}
@Override
protected void initialize(Application app) {
blocker = new Container();
blocker.setBackground(new QuadBackgroundComponent(new ColorRGBA(0, 0, 0, 0.5f)));
blocker.addMouseListener(ConsumingMouseListener.INSTANCE);
popup = new Container(new BorderLayout(), POPUP_ID, style);
popup.addChild(new Label(title, TITLE_ID, style), BorderLayout.Position.North);
popup.addChild(new Label(message, MESSAGE_ID, style), BorderLayout.Position.Center);
Button ok = popup.addChild(new Button("Ok", CLOSE_ID, style), BorderLayout.Position.South);
ok.addClickCommands(new Close());
Camera cam = app.getCamera();
blocker.setPreferredSize(new Vector3f(cam.getWidth(), cam.getHeight(), 0));
blocker.setLocalTranslation(0, cam.getHeight(), 99);
float menuScale = cam.getHeight()/720f;
popup.setLocalScale(menuScale);
Vector3f pref = popup.getPreferredSize();
pref.x = Math.max(pref.x, 600);
pref.y = Math.max(pref.y, 400);
popup.setPreferredSize(pref);
popup.setLocalTranslation(cam.getWidth() * 0.5f - menuScale * pref.x * 0.5f,
cam.getHeight() * 0.5f + menuScale * pref.y * 0.5f, 100);
}
@Override
protected void cleanup(Application app) {
}
@Override
protected void enable() {
((SimpleApplication)getApplication()).getGuiNode().attachChild(blocker);
((SimpleApplication)getApplication()).getGuiNode().attachChild(popup);
}
@Override
protected void disable() {
blocker.removeFromParent();
popup.removeFromParent();
}
private class Close implements Command<Button> {
public void execute( Button source ) {
getStateManager().detach(ErrorState.this);
}
}
}
| UTF-8 | Java | 4,934 | java | ErrorState.java | Java | [
{
"context": "/*\n * $Id$\n *\n * Copyright (c) 2013 jMonkeyEngine\n * All rights reserved.\n *\n * Redistribution and ",
"end": 49,
"score": 0.9833663702011108,
"start": 36,
"tag": "USERNAME",
"value": "jMonkeyEngine"
},
{
"context": "and pops up an\n * error dialog.\n *\n * @author Paul Speed\n */\npublic class ErrorState extends BaseAppState ",
"end": 2276,
"score": 0.9998136758804321,
"start": 2266,
"tag": "NAME",
"value": "Paul Speed"
}
]
| null | []
| /*
* $Id$
*
* Copyright (c) 2013 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package trap;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Command;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.component.BorderLayout;
import com.simsilica.lemur.component.QuadBackgroundComponent;
import com.simsilica.lemur.event.BaseAppState;
import com.simsilica.lemur.event.ConsumingMouseListener;
import com.simsilica.lemur.style.ElementId;
/**
* State that takes over the screen and pops up an
* error dialog.
*
* @author <NAME>
*/
public class ErrorState extends BaseAppState {
public static final ElementId POPUP_ID = new ElementId("error.popup");
public static final ElementId TITLE_ID = new ElementId("error.title");
public static final ElementId MESSAGE_ID = new ElementId("error.message");
public static final ElementId CLOSE_ID = new ElementId("error.close.button");
private Container blocker;
private Container popup;
private String title;
private String message;
private String style;
public ErrorState( String title, String message, String style ) {
this.title = title;
this.message = message;
this.style = style;
}
@Override
protected void initialize(Application app) {
blocker = new Container();
blocker.setBackground(new QuadBackgroundComponent(new ColorRGBA(0, 0, 0, 0.5f)));
blocker.addMouseListener(ConsumingMouseListener.INSTANCE);
popup = new Container(new BorderLayout(), POPUP_ID, style);
popup.addChild(new Label(title, TITLE_ID, style), BorderLayout.Position.North);
popup.addChild(new Label(message, MESSAGE_ID, style), BorderLayout.Position.Center);
Button ok = popup.addChild(new Button("Ok", CLOSE_ID, style), BorderLayout.Position.South);
ok.addClickCommands(new Close());
Camera cam = app.getCamera();
blocker.setPreferredSize(new Vector3f(cam.getWidth(), cam.getHeight(), 0));
blocker.setLocalTranslation(0, cam.getHeight(), 99);
float menuScale = cam.getHeight()/720f;
popup.setLocalScale(menuScale);
Vector3f pref = popup.getPreferredSize();
pref.x = Math.max(pref.x, 600);
pref.y = Math.max(pref.y, 400);
popup.setPreferredSize(pref);
popup.setLocalTranslation(cam.getWidth() * 0.5f - menuScale * pref.x * 0.5f,
cam.getHeight() * 0.5f + menuScale * pref.y * 0.5f, 100);
}
@Override
protected void cleanup(Application app) {
}
@Override
protected void enable() {
((SimpleApplication)getApplication()).getGuiNode().attachChild(blocker);
((SimpleApplication)getApplication()).getGuiNode().attachChild(popup);
}
@Override
protected void disable() {
blocker.removeFromParent();
popup.removeFromParent();
}
private class Close implements Command<Button> {
public void execute( Button source ) {
getStateManager().detach(ErrorState.this);
}
}
}
| 4,930 | 0.69092 | 0.68261 | 128 | 37.546875 | 30.418657 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 8 |
62703612dd993f2e12a006c076ffa9932e464cdd | 11,364,483,524,451 | 6e8a3b32a2c4f1db92b5a434c8f932ca71e4dbce | /src/main/com/ultrapower/workflow/engine/def/model/ActorDescriptor.java | e288994cdd457a2992dcfa3e690473716da59e97 | []
| no_license | liveqmock/emos4 | https://github.com/liveqmock/emos4 | 0fc046f2537cbdc8833e10a44410f03fefaa583c | 2a3206a67f82ee8cff03195dcfb53b065f880bd3 | refs/heads/master | 2021-01-18T00:34:19.211000 | 2015-04-12T11:28:00 | 2015-04-12T11:28:00 | 34,325,603 | 1 | 2 | null | true | 2015-04-21T12:29:34 | 2015-04-21T12:29:34 | 2015-04-12T11:30:21 | 2015-04-12T11:30:09 | 115,512 | 0 | 0 | 0 | null | null | null | /* */ package com.ultrapower.workflow.engine.def.model;
/* */
/* */ public class ActorDescriptor extends AbstractDescriptor
/* */ {
/* */ private String roleId;
/* */ private String roleName;
/* */ private String actorType;
/* */ private String rule;
/* */
/* */ public ActorDescriptor(AbstractDescriptor parent)
/* */ {
/* 10 */ setParent(parent);
/* */ }
/* */
/* */ public String getRoleId() {
/* 14 */ return this.roleId;
/* */ }
/* */ public void setRoleId(String roleId) {
/* 17 */ this.roleId = roleId;
/* */ }
/* */ public String getRoleName() {
/* 20 */ return this.roleName;
/* */ }
/* */ public void setRoleName(String roleName) {
/* 23 */ this.roleName = roleName;
/* */ }
/* */ public String getActorType() {
/* 26 */ return this.actorType;
/* */ }
/* */ public void setActorType(String actorType) {
/* 29 */ this.actorType = actorType;
/* */ }
/* */ public String getRule() {
/* 32 */ return this.rule;
/* */ }
/* */ public void setRule(String rule) {
/* 35 */ this.rule = rule;
/* */ }
/* */ }
/* Location: F:\Ultrapower\WebProject\BPP\eoms4\WebRoot\WEB-INF\lib\WFServer.jar
* Qualified Name: com.ultrapower.workflow.engine.def.model.ActorDescriptor
* JD-Core Version: 0.6.0
*/ | UTF-8 | Java | 1,431 | java | ActorDescriptor.java | Java | []
| null | []
| /* */ package com.ultrapower.workflow.engine.def.model;
/* */
/* */ public class ActorDescriptor extends AbstractDescriptor
/* */ {
/* */ private String roleId;
/* */ private String roleName;
/* */ private String actorType;
/* */ private String rule;
/* */
/* */ public ActorDescriptor(AbstractDescriptor parent)
/* */ {
/* 10 */ setParent(parent);
/* */ }
/* */
/* */ public String getRoleId() {
/* 14 */ return this.roleId;
/* */ }
/* */ public void setRoleId(String roleId) {
/* 17 */ this.roleId = roleId;
/* */ }
/* */ public String getRoleName() {
/* 20 */ return this.roleName;
/* */ }
/* */ public void setRoleName(String roleName) {
/* 23 */ this.roleName = roleName;
/* */ }
/* */ public String getActorType() {
/* 26 */ return this.actorType;
/* */ }
/* */ public void setActorType(String actorType) {
/* 29 */ this.actorType = actorType;
/* */ }
/* */ public String getRule() {
/* 32 */ return this.rule;
/* */ }
/* */ public void setRule(String rule) {
/* 35 */ this.rule = rule;
/* */ }
/* */ }
/* Location: F:\Ultrapower\WebProject\BPP\eoms4\WebRoot\WEB-INF\lib\WFServer.jar
* Qualified Name: com.ultrapower.workflow.engine.def.model.ActorDescriptor
* JD-Core Version: 0.6.0
*/ | 1,431 | 0.522013 | 0.506639 | 44 | 30.568182 | 20.327318 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 8 |
b62fe22b5879159d943a50d698cf63ea4b6df4bc | 8,787,503,092,260 | e4d7c2ff9b7bd40a9aca68574861e5f4d98b717a | /JavaSource/gov/noaa/pmel/tmap/las/test/LASResponseTester.java | 2ce694cb4b275be0c22e18191bc730c45302b108 | [
"Unlicense"
]
| permissive | karlmattsmith/SocatLAS | https://github.com/karlmattsmith/SocatLAS | c392f63838f2a409546b326e4c832efa5ae6e789 | b61bb999fa836edcdb6c43598f0ad5d4d2e77bd3 | refs/heads/master | 2022-11-06T22:14:34.127000 | 2020-06-25T22:58:17 | 2020-06-25T22:58:17 | 274,228,227 | 0 | 0 | Unlicense | true | 2020-06-22T19:48:34 | 2020-06-22T19:48:33 | 2020-06-22T18:43:08 | 2020-06-22T18:43:05 | 538,695 | 0 | 0 | 0 | null | false | false | package gov.noaa.pmel.tmap.las.test;
import gov.noaa.pmel.tmap.addxml.JDOMUtils;
import gov.noaa.pmel.tmap.las.client.lastest.TestConstants;
import gov.noaa.pmel.tmap.las.jdom.LASConfig;
import gov.noaa.pmel.tmap.las.jdom.LASTestResults;
import gov.noaa.pmel.tmap.las.jdom.LASUIRequest;
import gov.noaa.pmel.tmap.las.ui.state.OptionBean;
import gov.noaa.pmel.tmap.las.util.Dataset;
import gov.noaa.pmel.tmap.las.util.Grid;
import gov.noaa.pmel.tmap.las.util.Variable;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.jdom.Element;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import dods.dap.DConnect;
import dods.dap.DDS;
import dods.dap.DDSException;
import dods.dap.DODSException;
import dods.dap.parser.ParseException;
/**
* This class tests the responses form a LAS product server
* @author Jing Yang Li
*
*/
public class LASResponseTester{
private LASConfig lasConfig;
private LASTestOptions lto;
//public LASResponseTester(LASConfig config, LASDocument operations, LASDocument options, LASTestOptions l){
/**
* Constructor
*/
public LASResponseTester(LASConfig config, LASTestOptions l){
lasConfig = config;
lto = l;
}
/**
* Test whether responses from product server are correct
*
*/
public void testResponse(boolean web_output, ArrayList<Dataset> datasets) {
String dsID;
String varID;
String varpath;
ArrayList<Variable> variables = new ArrayList<Variable>();
String productServerURL;
String test_output_file = null;
LASTestResults testResults = new LASTestResults();
try{
if ( web_output ) {
test_output_file = lasConfig.getOutputDir()+File.separator+TestConstants.TEST_RESULTS_FILE;
File c = new File(test_output_file);
if ( c.exists() ) {
JDOMUtils.XML2JDOM(new File(test_output_file), testResults);
}
Date date = new Date();
testResults.putTest(TestConstants.TEST_PRODUCT_RESPONSE, date.getTime());
}
productServerURL = lto.getLAS()+"ProductServer.do";
String dregex = lto.getDregex();
String vregex = lto.getVregex();
//loop over each dataset
for(Iterator dsIt = datasets.iterator(); dsIt.hasNext();){
Dataset ds = (Dataset)dsIt.next();
boolean dmatch = true;
if ( dregex != null ) {
dmatch = Pattern.matches(dregex, ds.getID());
}
if ( dmatch ) {
if ( web_output ) {
testResults.putDataset(TestConstants.TEST_PRODUCT_RESPONSE, ds.getName(), ds.getID());
}
//get first variable of this dataset
variables = ds.getVariables();
boolean allVar = lto.allVariable() || vregex != null;
if(!allVar){
if ( variables != null && variables.size() > 0 ) {
Variable firstVar = null;
// We cannot test subset variables for DSG data.
for ( int i = 0; i < variables.size(); i++ ) {
Variable candidate = variables.get(i);
// find the first non-subset variable, and not time, lat or lon since these require
// special treatment to extract from the server properly
if ( candidate.getAttributesAsMap().get("subset_variable") == null &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("time") &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("lat") &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("lon") ) {
firstVar = candidate;
break;
}
}
if ( firstVar != null ) {
varLASRequest(ds, firstVar, web_output, testResults);
}
}
}else{
for(Iterator varIt = variables.iterator(); varIt.hasNext();){
boolean vmatch = true;
Variable theVar = (Variable)varIt.next();
if ( vregex != null ) {
vmatch = Pattern.matches(vregex, theVar.getID());
}
if ( vmatch ) {
varLASRequest(ds, theVar, web_output, testResults);
}
}
}
}
}
if ( web_output ) {
testResults.write(test_output_file);
}
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Test the LAS response for a variable
* @param dsE the dataset element
* @param theVar the variable to test
*/
public void varLASRequest(Dataset dataset, Variable theVar, boolean web_output, LASTestResults testResults) {
String dsoURL = dataset.getAttributeValue("url");
String varURL = theVar.getAttributeValue("url");
try{
//get the data URL
String dsURL = LASConfig.combinedURL(dsoURL, varURL);
String userds = lto.getDataset();
//if url is in format of ....xyz.nc#var
if(dsURL.contains("#")){
String[] tmp = dsURL.split("#");
dsURL = tmp[0];
}
boolean isAvailable = false;
//check if a remote dataset is available
if(dsURL == null && dsURL == ""){
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, dataset.getID(), dsURL, "n/a", "n/a", "n/a", "failed - dataset invalid");
} else {
System.out.println("The dataset URL is not valid.");
}
}
//check if a dataset is available
/*
if( userds == null || userds==""){
if(dsURL.contains("http")){
isAvailable = isAvailable(dsURL); //remote dataset
}else{
isAvailable = true; //local dataset
}
}else{
if(dsURL.contains(userds)){
isAvailable = isAvailable(dsURL);
}
}
*/
//if(isAvailable){
if( userds == null || userds=="" || dsURL.contains(userds) ){
if ( !web_output ) {
System.out.println("---- Dataset Name: "+ dataset.getName() + " with ID="+dataset.getID());
System.out.println(" -- Dataset URL: "+ dsURL);
}
if(dsURL.contains("http") && !dsURL.contains("tabledap") ){
isAvailable = isAvailable(dsURL); //remote dataset
}else{
isAvailable = true; //local dataset
}
if(isAvailable){
if ( !web_output ) {
System.out.println(" Variable: "+ theVar.getName());
}
boolean hasZ = theVar.getGrid().hasZ();
boolean hasT = theVar.getGrid().hasT();
String v = lto.getView();
//by default, test each view
if(v == null || v.equals("")){
//1D plots
if ( !web_output ) {
System.out.print(" -- test x line plot: ");
}
makeLASRequest("x", theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test y line plot: ");
}
makeLASRequest("y", theVar, web_output, testResults);
if(hasZ){
if ( !web_output ) {
System.out.print(" -- test z line plot: ");
}
makeLASRequest("z", theVar, web_output, testResults);
}
if(hasT){
if ( !web_output ) {
System.out.print(" -- test time series: ");
}
makeLASRequest("t", theVar, web_output, testResults);
}
//2D plots
if ( !web_output ) {
System.out.print(" -- test XY 2D plot: ");
}
makeLASRequest("xy", theVar, web_output, testResults);
if(hasZ){
if ( !web_output ) {
System.out.print(" -- test XZ 2D plot: ");
}
makeLASRequest("xz", theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test YZ 2D plot: ");
}
makeLASRequest("yz", theVar, web_output, testResults);
if(hasT){
if ( !web_output ) {
System.out.print(" -- test ZT 2D plot: ");
}
makeLASRequest("zt", theVar, web_output, testResults);
}
}
if(hasT){
if ( !web_output ) {
System.out.print(" -- test XT 2D plot: ");
}
makeLASRequest("xt",theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test YT 2D plot: ");
}
makeLASRequest("yt", theVar, web_output, testResults);
}
}else{
//only make request for the plot defined by command-line parameter
if( v.contains("z") && (!hasZ) ){
if ( !web_output) System.out.println(" -- No Z axis!");
}else if( v.contains("t") && (!hasT) ){
if ( !web_output) System.out.println(" -- No T axis!");
}else{
if ( !web_output ) System.out.print(" -- test "+v+" plot: ");
makeLASRequest(v, theVar, web_output, testResults);
}
}
}else{
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, dataset.getID(), dsURL, "n/a", "n/a", "n/a", "failed - dataset unavailable");
} else {
System.out.println(" ******** WARNING ******** The dataset is not available");
}
}
if ( !web_output ) {
System.out.println("");
}
}
/*
}else{
if( userds == null || userds==""){
System.out.println("---- Dataset Name: "+ dsName);
System.out.println(" -- Dataset URL: "+ dsURL);
System.out.println(" ******** WARNING ******** The dataset is not available");
}else{
if(dsURL.contains(userds)){
System.out.println("---- Dataset Name: "+ dsName);
System.out.println(" -- Dataset URL: "+ dsURL);
System.out.println(" ******** WARNING ******** The dataset is not available");
}
}
}
*/
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Check if a dataset with the given URL is available
* @param url the URL of the dataset
* @return isAvailable
*/
public boolean isAvailable(String url) throws Exception{
boolean isAvailable = false;
try{
DConnect dc = new DConnect(url);
DDS mydds = dc.getDDS();
if(mydds != null){
isAvailable = true;
}else{
isAvailable = false;
}
}catch (MalformedURLException e){
//java.net.MalformedURLException - if the URL given to the constructor has an error
isAvailable = false;
}catch (IOException e){
//java.io.IOException - if an error connecting to the remote server
isAvailable = false;
}catch (ParseException e){
//dods.dap.parser.ParseException - if the DDS parser returned an error
isAvailable = false;
}catch (DDSException e){
//dods.dap.DDSException - on an error constructing the DDS
isAvailable = false;
}catch (DODSException e){
//dods.dap.DODSException - if an error returned by the remote server
isAvailable = false;
}catch (Exception e){
//e.printStackTrace();
isAvailable = false;
}
return isAvailable;
}
/**
* Test LAS request for 1D and 2D plots
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public void makeLASRequest(String viewtype, Variable variable, boolean web_output, LASTestResults testResults) {
String requestURL ="";
String serverURL;
LASUIRequest lr = new LASUIRequest();
lr = buildLASUIRequest(viewtype,variable);
try{
serverURL = lto.getLAS()+"ProductServer.do";
requestURL = serverURL+"?xml=" + lr.toEncodedURLString()+"&debug=true";
} catch (Exception e){
e.printStackTrace();
}
boolean inProgress = true;
int noProgress = 0;
InputStream instream = null;
while(inProgress && (noProgress < 2)){
try{
//send request to ProductServer
URL url = new URL(requestURL);
URLConnection conn = url.openConnection();
conn.connect();
instream = conn.getInputStream();
String contentType = conn.getContentType();
char[] buf = new char[4096];
BufferedReader is = new BufferedReader(new InputStreamReader(instream));
StringBuffer sbuf = new StringBuffer();
int length = is.read(buf, 0, 4096);
while (length >=0 ){
sbuf.append(buf, 0, length);
length = is.read(buf, 0, 4096);
}
int size = sbuf.length();
if(sbuf.toString().contains("error")){
String debugFile = extractDebugFile(sbuf.toString());
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "failed");
} else {
System.out.println(" ---------- ERROR !!!");
}
if(debugFile !=null && debugFile !=""){
if ( !web_output ) System.out.println(" The debug file is "+ debugFile);
}
//print the whole error message
if(lto.isVerbose() || debugFile == null || debugFile == ""){
if (!web_output) System.out.println(sbuf.toString());
}
inProgress = false;
if(lto.exitFirst()){System.exit(-1);}
}else if(sbuf.toString().contains("Progress") || sbuf.toString().contains("progress")){
inProgress = true;
noProgress++;
if ( !web_output) {
System.out.println("The response is:");
System.out.println(sbuf.toString());
}
}else{//correct response (hope so!)
inProgress = false;
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "passed");
} else {
System.out.println(" ---------- PASS!");
}
}
}catch (Exception e){
if ( !web_output ) System.out.println("error in making request to product server");
e.printStackTrace();
break;
} finally {
if ( instream != null ) {
try {
instream.close();
} catch (IOException e) {
System.err.println("Error closing stream. "+e.getMessage());
}
}
}
}
//if the request was sent more than 3 times; kill it
//it may be taking too long or there are errors (e.g. Ferret script hangs)
if(inProgress && (noProgress == 2)){
if ( !web_output) System.out.println("----------------------------cancel request");
//send cancel request to ProductServer
try{
URL url = new URL(requestURL+"&cancel=Cancel");
URLConnection conn = url.openConnection();
conn.connect();
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "canceled");
} else {
System.out.println("The request either takes too long or may have error --- cancel it!");
}
}catch (IOException e){
System.out.println("error in canceling request");
}
}
}
/**
* Extract the debug file from the error message
* @param errMsg the error message returned from LAS
*/
private String extractDebugFile(String errMsg){
//System.out.println(errMsg);
String debugFile="";
int i1 = errMsg.indexOf("debug.txt");
if(i1 > 0){
String s1 = errMsg.substring(0,i1+9);
int i2 = s1.lastIndexOf("http");
if(i2>0){debugFile = s1.substring(i2);}
}
return debugFile;
}
/**
* Build a LASUIRequest for 1D and 2D plots
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public LASUIRequest buildLASUIRequest(String viewtype, Variable variable){
ArrayList<OptionBean> options = null;
LASUIRequest lr = new LASUIRequest();
lr.addVariable(variable.getDSID(),variable.getID());
if(viewtype.length() == 1){
lr.setOperation("Plot_1D");
//options = extractOptions("Options_1D");
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
lr.setProperty("ferret","line_or_sym","default");
lr.setProperty("ferret","line_color","default");
lr.setProperty("ferret","line_thickness","default");
}else if(viewtype.length() == 2){
if(viewtype.equals("xy")){
lr.setOperation("Plot_2D_XY");
}else{
lr.setOperation("Plot_2D");
}
//options = extractOptions("Options_2D");
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
lr.setProperty("ferret","palette","default");
} else if ( viewtype.length() == 3 && variable.isDiscrete() ) {
String gt = variable.getGridType();
// TODO other discrete types.
if ( gt != null ) {
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
if ( gt.equals("timeseries") ) {
lr.setOperation("Timeseries_interactive_plot");
} else if (gt.equals("profile") ) {
lr.setOperation("Profile_interactive_plot");
} else if ( gt.equals("trajectory") ) {
lr.setOperation("Trajectory_interactive_plot");
}
}
}
Date now = new Date();
String timestamp = String.valueOf(now.getTime());
lr.setProperty("ferret", "annotations", "file");
lr.setProperty("result","annotations_ID", "annotations");
lr.setProperty("result","annotations_filename", timestamp+"_annotations.xml");
lr.setProperty("result","annotations_type","annotations");
lr.setProperty("data_0", "dataset_name", "Test data set");
HashMap<String, HashMap<String,String[]>> region = new HashMap<String, HashMap<String,String[]>>();
region = makeRegion(viewtype, variable);
if(region != null){lr.setRegion(region);}
return lr;
}
/**
* Make a region for a plot
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public ArrayList<OptionBean> makeOptions(String viewtype){
ArrayList<OptionBean> options = new ArrayList<OptionBean>();
OptionBean opb1 = new OptionBean();
opb1.setWidget_name("interpolate_data");
opb1.setValue("false");
options.add(opb1);
OptionBean opb2 = new OptionBean();
opb2.setWidget_name("image_format");
opb2.setValue("default");
options.add(opb2);
OptionBean opb3 = new OptionBean();
opb3.setWidget_name("size");
opb3.setValue(".5");
options.add(opb3);
OptionBean opb4 = new OptionBean();
opb4.setWidget_name("use_ref_map");
opb4.setValue("default");
options.add(opb4);
OptionBean opb5 = new OptionBean();
opb5.setWidget_name("use_graticules");
opb5.setValue("default");
options.add(opb5);
OptionBean opb6 = new OptionBean();
opb6.setWidget_name("no_margins");
opb6.setValue("default");
options.add(opb6);
OptionBean opb7 = new OptionBean();
opb7.setWidget_name("deg_min_sec");
opb7.setValue("default");
options.add(opb7);
OptionBean opb8 = new OptionBean();
opb8.setWidget_name("view");
opb8.setValue(viewtype);
options.add(opb8);
return options;
}
/**
* Make a region for a plot
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public HashMap<String, HashMap<String,String[]>> makeRegion(String viewtype, Variable variable){
Grid grid = variable.getGrid();
String xLo = "";
String xHi = "";
String yLo = "";
String yHi = "";
String zLo = "";
String zHi = "";
String tLo = "";
String tHi = "";
boolean hasZ = false;
boolean hasT = false;
DateTime lodt=null;
DateTime hidt=null;
HashMap<String, HashMap<String,String[]>> region = new HashMap<String, HashMap<String,String[]>>();
HashMap<String,String[]> points = new HashMap<String,String[]>();
HashMap<String,String[]> intervals = new HashMap<String,String[]>();
try{
//get the end points of each axis
xLo = grid.getAxis("x").getLo();
xHi = grid.getAxis("x").getHi();
yLo = grid.getAxis("y") .getLo();
yHi = grid.getAxis("y").getHi();
if(grid.hasZ()){
hasZ = true;
zLo = grid.getAxis("z").getLo();
zHi = grid.getAxis("z").getHi();
}
//time axis
if(grid.hasT()){
hasT = true;
//get time format for this variable defined in dataset configuration file
tLo = grid.getTime().getLo();
LASDateFormat ldf = new LASDateFormat(tLo);
String tFormat = ldf.getDateFormat();
DateTimeFormatter fmt = DateTimeFormat.forPattern(tFormat).withZone(DateTimeZone.UTC);
DateTimeFormatter ferretfmt = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.UTC);
lodt = fmt.parseDateTime(tLo);
tLo = lodt.toString(ferretfmt);
tHi = grid.getTime().getHi();
hidt= fmt.parseDateTime(tHi);
tHi = hidt.toString(ferretfmt);
}
}catch (Exception e){
e.printStackTrace();
}
//make a x interval or point
if(viewtype.contains("x")){
//make a small x interval in case it's a large dataset
String[] x = new String[2];
double lox = Double.valueOf(xLo).doubleValue();
double hix = Double.valueOf(xHi).doubleValue();
double dx = hix - lox;
x[0] = xLo;
x[1] = Double.toString(lox+(dx/4));
intervals.put("x",x);
}else{
//make a x point
String[] x = new String[1];
x[0] = xLo;
points.put("x",x);
}
//make a y interval or point
if(viewtype.contains("y")){
//make a small y interval in case it's a large dataset
String[] y = new String[2];
double loy = Double.valueOf(yLo).doubleValue();
double hiy = Double.valueOf(yHi).doubleValue();
double dy = hiy - loy;
y[0] = yLo;
y[1] = Double.toString(loy+(dy/4));
intervals.put("y",y);
}else{
//make a y point
String[] y = new String[1];
y[0] = yLo;
points.put("y",y);
}
//make a z interval or point
if(hasZ){
if(viewtype.contains("z") || variable.isDiscrete() ){
//make a z interval
String[] z = new String[2];
z[0] = zLo;
z[1] = zHi;
intervals.put("z",z);
}else{
//make a z point
String[] z = new String[1];
z[0] = zLo;
points.put("z",z);
}
}
//make a t interval or point
if(hasT){
if(viewtype.contains("t")){
//make a t interval
String[] t = new String[2];
t[0] = tLo;
t[1] = tHi;
intervals.put("t",t);
}else{
//make a t point
String[] t = new String[1];
t[0] = tLo;
points.put("t",t);
}
}
region.put("intervals", intervals);
region.put("points", points);
return region;
}
public LASTimeAxis getLASTimeAxis(String varpath){
LASTimeAxis lta = new LASTimeAxis();
String timeStyle = null;
try{
if (!varpath.contains("@ID")) {
String[] parts = varpath.split("/");
// Throw away index 0 since the string has a leading "/".
varpath = "/"+parts[1]+"/"+parts[2]+"/dataset[@ID='"+parts[3]+"']/"+parts[4]+"/variable[@ID='"+parts[5]+"']";
}
Element variable = lasConfig.getElementByXPath(varpath);
if (variable == null) {
return null;
}
String gridID = variable.getChild("grid").getAttributeValue("IDREF");
Element grid = lasConfig.getElementByXPath("/lasdata/grids/grid[@ID='"+gridID+"']");
if (grid == null) {
//System.out.println("grid");
return null;
}
List axes = grid.getChildren("axis");
for (Iterator axIt = axes.iterator(); axIt.hasNext();) {
Element axis = (Element) axIt.next();
String axisID = axis.getAttributeValue("IDREF");
axis = lasConfig.getElementByXPath("/lasdata/axes/axis[@ID='"+axisID+"']");
String t = axis.getAttributeValue("type");
if ( t.equals("t") ) {
lta.setUnit(axis.getAttributeValue("units"));
Element arange = axis.getChild("arange");
if (arange == null) {
List v = axis.getChildren("v");
if(v != null){
timeStyle = "v";
lta.setStyle("v");
}
} else {
timeStyle = "arange";
lta.setStyle("arange");
double size = Double.valueOf(arange.getAttributeValue("size")).doubleValue();
double step = Double.valueOf(arange.getAttributeValue("step")).doubleValue();
lta.setSize(size);
lta.setStep(step);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return lta;
}
}
| UTF-8 | Java | 24,453 | java | LASResponseTester.java | Java | [
{
"context": "the responses form a LAS product server\n * @author Jing Yang Li\n *\n */\npublic class LASResponseTester{\n\n\tprivate ",
"end": 1307,
"score": 0.9983007907867432,
"start": 1295,
"tag": "NAME",
"value": "Jing Yang Li"
}
]
| null | []
| package gov.noaa.pmel.tmap.las.test;
import gov.noaa.pmel.tmap.addxml.JDOMUtils;
import gov.noaa.pmel.tmap.las.client.lastest.TestConstants;
import gov.noaa.pmel.tmap.las.jdom.LASConfig;
import gov.noaa.pmel.tmap.las.jdom.LASTestResults;
import gov.noaa.pmel.tmap.las.jdom.LASUIRequest;
import gov.noaa.pmel.tmap.las.ui.state.OptionBean;
import gov.noaa.pmel.tmap.las.util.Dataset;
import gov.noaa.pmel.tmap.las.util.Grid;
import gov.noaa.pmel.tmap.las.util.Variable;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.jdom.Element;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import dods.dap.DConnect;
import dods.dap.DDS;
import dods.dap.DDSException;
import dods.dap.DODSException;
import dods.dap.parser.ParseException;
/**
* This class tests the responses form a LAS product server
* @author <NAME>
*
*/
public class LASResponseTester{
private LASConfig lasConfig;
private LASTestOptions lto;
//public LASResponseTester(LASConfig config, LASDocument operations, LASDocument options, LASTestOptions l){
/**
* Constructor
*/
public LASResponseTester(LASConfig config, LASTestOptions l){
lasConfig = config;
lto = l;
}
/**
* Test whether responses from product server are correct
*
*/
public void testResponse(boolean web_output, ArrayList<Dataset> datasets) {
String dsID;
String varID;
String varpath;
ArrayList<Variable> variables = new ArrayList<Variable>();
String productServerURL;
String test_output_file = null;
LASTestResults testResults = new LASTestResults();
try{
if ( web_output ) {
test_output_file = lasConfig.getOutputDir()+File.separator+TestConstants.TEST_RESULTS_FILE;
File c = new File(test_output_file);
if ( c.exists() ) {
JDOMUtils.XML2JDOM(new File(test_output_file), testResults);
}
Date date = new Date();
testResults.putTest(TestConstants.TEST_PRODUCT_RESPONSE, date.getTime());
}
productServerURL = lto.getLAS()+"ProductServer.do";
String dregex = lto.getDregex();
String vregex = lto.getVregex();
//loop over each dataset
for(Iterator dsIt = datasets.iterator(); dsIt.hasNext();){
Dataset ds = (Dataset)dsIt.next();
boolean dmatch = true;
if ( dregex != null ) {
dmatch = Pattern.matches(dregex, ds.getID());
}
if ( dmatch ) {
if ( web_output ) {
testResults.putDataset(TestConstants.TEST_PRODUCT_RESPONSE, ds.getName(), ds.getID());
}
//get first variable of this dataset
variables = ds.getVariables();
boolean allVar = lto.allVariable() || vregex != null;
if(!allVar){
if ( variables != null && variables.size() > 0 ) {
Variable firstVar = null;
// We cannot test subset variables for DSG data.
for ( int i = 0; i < variables.size(); i++ ) {
Variable candidate = variables.get(i);
// find the first non-subset variable, and not time, lat or lon since these require
// special treatment to extract from the server properly
if ( candidate.getAttributesAsMap().get("subset_variable") == null &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("time") &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("lat") &&
!candidate.getName().toLowerCase(Locale.ENGLISH).contains("lon") ) {
firstVar = candidate;
break;
}
}
if ( firstVar != null ) {
varLASRequest(ds, firstVar, web_output, testResults);
}
}
}else{
for(Iterator varIt = variables.iterator(); varIt.hasNext();){
boolean vmatch = true;
Variable theVar = (Variable)varIt.next();
if ( vregex != null ) {
vmatch = Pattern.matches(vregex, theVar.getID());
}
if ( vmatch ) {
varLASRequest(ds, theVar, web_output, testResults);
}
}
}
}
}
if ( web_output ) {
testResults.write(test_output_file);
}
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Test the LAS response for a variable
* @param dsE the dataset element
* @param theVar the variable to test
*/
public void varLASRequest(Dataset dataset, Variable theVar, boolean web_output, LASTestResults testResults) {
String dsoURL = dataset.getAttributeValue("url");
String varURL = theVar.getAttributeValue("url");
try{
//get the data URL
String dsURL = LASConfig.combinedURL(dsoURL, varURL);
String userds = lto.getDataset();
//if url is in format of ....xyz.nc#var
if(dsURL.contains("#")){
String[] tmp = dsURL.split("#");
dsURL = tmp[0];
}
boolean isAvailable = false;
//check if a remote dataset is available
if(dsURL == null && dsURL == ""){
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, dataset.getID(), dsURL, "n/a", "n/a", "n/a", "failed - dataset invalid");
} else {
System.out.println("The dataset URL is not valid.");
}
}
//check if a dataset is available
/*
if( userds == null || userds==""){
if(dsURL.contains("http")){
isAvailable = isAvailable(dsURL); //remote dataset
}else{
isAvailable = true; //local dataset
}
}else{
if(dsURL.contains(userds)){
isAvailable = isAvailable(dsURL);
}
}
*/
//if(isAvailable){
if( userds == null || userds=="" || dsURL.contains(userds) ){
if ( !web_output ) {
System.out.println("---- Dataset Name: "+ dataset.getName() + " with ID="+dataset.getID());
System.out.println(" -- Dataset URL: "+ dsURL);
}
if(dsURL.contains("http") && !dsURL.contains("tabledap") ){
isAvailable = isAvailable(dsURL); //remote dataset
}else{
isAvailable = true; //local dataset
}
if(isAvailable){
if ( !web_output ) {
System.out.println(" Variable: "+ theVar.getName());
}
boolean hasZ = theVar.getGrid().hasZ();
boolean hasT = theVar.getGrid().hasT();
String v = lto.getView();
//by default, test each view
if(v == null || v.equals("")){
//1D plots
if ( !web_output ) {
System.out.print(" -- test x line plot: ");
}
makeLASRequest("x", theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test y line plot: ");
}
makeLASRequest("y", theVar, web_output, testResults);
if(hasZ){
if ( !web_output ) {
System.out.print(" -- test z line plot: ");
}
makeLASRequest("z", theVar, web_output, testResults);
}
if(hasT){
if ( !web_output ) {
System.out.print(" -- test time series: ");
}
makeLASRequest("t", theVar, web_output, testResults);
}
//2D plots
if ( !web_output ) {
System.out.print(" -- test XY 2D plot: ");
}
makeLASRequest("xy", theVar, web_output, testResults);
if(hasZ){
if ( !web_output ) {
System.out.print(" -- test XZ 2D plot: ");
}
makeLASRequest("xz", theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test YZ 2D plot: ");
}
makeLASRequest("yz", theVar, web_output, testResults);
if(hasT){
if ( !web_output ) {
System.out.print(" -- test ZT 2D plot: ");
}
makeLASRequest("zt", theVar, web_output, testResults);
}
}
if(hasT){
if ( !web_output ) {
System.out.print(" -- test XT 2D plot: ");
}
makeLASRequest("xt",theVar, web_output, testResults);
if ( !web_output ) {
System.out.print(" -- test YT 2D plot: ");
}
makeLASRequest("yt", theVar, web_output, testResults);
}
}else{
//only make request for the plot defined by command-line parameter
if( v.contains("z") && (!hasZ) ){
if ( !web_output) System.out.println(" -- No Z axis!");
}else if( v.contains("t") && (!hasT) ){
if ( !web_output) System.out.println(" -- No T axis!");
}else{
if ( !web_output ) System.out.print(" -- test "+v+" plot: ");
makeLASRequest(v, theVar, web_output, testResults);
}
}
}else{
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, dataset.getID(), dsURL, "n/a", "n/a", "n/a", "failed - dataset unavailable");
} else {
System.out.println(" ******** WARNING ******** The dataset is not available");
}
}
if ( !web_output ) {
System.out.println("");
}
}
/*
}else{
if( userds == null || userds==""){
System.out.println("---- Dataset Name: "+ dsName);
System.out.println(" -- Dataset URL: "+ dsURL);
System.out.println(" ******** WARNING ******** The dataset is not available");
}else{
if(dsURL.contains(userds)){
System.out.println("---- Dataset Name: "+ dsName);
System.out.println(" -- Dataset URL: "+ dsURL);
System.out.println(" ******** WARNING ******** The dataset is not available");
}
}
}
*/
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Check if a dataset with the given URL is available
* @param url the URL of the dataset
* @return isAvailable
*/
public boolean isAvailable(String url) throws Exception{
boolean isAvailable = false;
try{
DConnect dc = new DConnect(url);
DDS mydds = dc.getDDS();
if(mydds != null){
isAvailable = true;
}else{
isAvailable = false;
}
}catch (MalformedURLException e){
//java.net.MalformedURLException - if the URL given to the constructor has an error
isAvailable = false;
}catch (IOException e){
//java.io.IOException - if an error connecting to the remote server
isAvailable = false;
}catch (ParseException e){
//dods.dap.parser.ParseException - if the DDS parser returned an error
isAvailable = false;
}catch (DDSException e){
//dods.dap.DDSException - on an error constructing the DDS
isAvailable = false;
}catch (DODSException e){
//dods.dap.DODSException - if an error returned by the remote server
isAvailable = false;
}catch (Exception e){
//e.printStackTrace();
isAvailable = false;
}
return isAvailable;
}
/**
* Test LAS request for 1D and 2D plots
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public void makeLASRequest(String viewtype, Variable variable, boolean web_output, LASTestResults testResults) {
String requestURL ="";
String serverURL;
LASUIRequest lr = new LASUIRequest();
lr = buildLASUIRequest(viewtype,variable);
try{
serverURL = lto.getLAS()+"ProductServer.do";
requestURL = serverURL+"?xml=" + lr.toEncodedURLString()+"&debug=true";
} catch (Exception e){
e.printStackTrace();
}
boolean inProgress = true;
int noProgress = 0;
InputStream instream = null;
while(inProgress && (noProgress < 2)){
try{
//send request to ProductServer
URL url = new URL(requestURL);
URLConnection conn = url.openConnection();
conn.connect();
instream = conn.getInputStream();
String contentType = conn.getContentType();
char[] buf = new char[4096];
BufferedReader is = new BufferedReader(new InputStreamReader(instream));
StringBuffer sbuf = new StringBuffer();
int length = is.read(buf, 0, 4096);
while (length >=0 ){
sbuf.append(buf, 0, length);
length = is.read(buf, 0, 4096);
}
int size = sbuf.length();
if(sbuf.toString().contains("error")){
String debugFile = extractDebugFile(sbuf.toString());
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "failed");
} else {
System.out.println(" ---------- ERROR !!!");
}
if(debugFile !=null && debugFile !=""){
if ( !web_output ) System.out.println(" The debug file is "+ debugFile);
}
//print the whole error message
if(lto.isVerbose() || debugFile == null || debugFile == ""){
if (!web_output) System.out.println(sbuf.toString());
}
inProgress = false;
if(lto.exitFirst()){System.exit(-1);}
}else if(sbuf.toString().contains("Progress") || sbuf.toString().contains("progress")){
inProgress = true;
noProgress++;
if ( !web_output) {
System.out.println("The response is:");
System.out.println(sbuf.toString());
}
}else{//correct response (hope so!)
inProgress = false;
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "passed");
} else {
System.out.println(" ---------- PASS!");
}
}
}catch (Exception e){
if ( !web_output ) System.out.println("error in making request to product server");
e.printStackTrace();
break;
} finally {
if ( instream != null ) {
try {
instream.close();
} catch (IOException e) {
System.err.println("Error closing stream. "+e.getMessage());
}
}
}
}
//if the request was sent more than 3 times; kill it
//it may be taking too long or there are errors (e.g. Ferret script hangs)
if(inProgress && (noProgress == 2)){
if ( !web_output) System.out.println("----------------------------cancel request");
//send cancel request to ProductServer
try{
URL url = new URL(requestURL+"&cancel=Cancel");
URLConnection conn = url.openConnection();
conn.connect();
if ( web_output ) {
testResults.addProductResult(TestConstants.TEST_PRODUCT_RESPONSE, variable.getDSID(), requestURL, viewtype, lr.getOperation(), lr.getThi(), "canceled");
} else {
System.out.println("The request either takes too long or may have error --- cancel it!");
}
}catch (IOException e){
System.out.println("error in canceling request");
}
}
}
/**
* Extract the debug file from the error message
* @param errMsg the error message returned from LAS
*/
private String extractDebugFile(String errMsg){
//System.out.println(errMsg);
String debugFile="";
int i1 = errMsg.indexOf("debug.txt");
if(i1 > 0){
String s1 = errMsg.substring(0,i1+9);
int i2 = s1.lastIndexOf("http");
if(i2>0){debugFile = s1.substring(i2);}
}
return debugFile;
}
/**
* Build a LASUIRequest for 1D and 2D plots
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public LASUIRequest buildLASUIRequest(String viewtype, Variable variable){
ArrayList<OptionBean> options = null;
LASUIRequest lr = new LASUIRequest();
lr.addVariable(variable.getDSID(),variable.getID());
if(viewtype.length() == 1){
lr.setOperation("Plot_1D");
//options = extractOptions("Options_1D");
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
lr.setProperty("ferret","line_or_sym","default");
lr.setProperty("ferret","line_color","default");
lr.setProperty("ferret","line_thickness","default");
}else if(viewtype.length() == 2){
if(viewtype.equals("xy")){
lr.setOperation("Plot_2D_XY");
}else{
lr.setOperation("Plot_2D");
}
//options = extractOptions("Options_2D");
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
lr.setProperty("ferret","palette","default");
} else if ( viewtype.length() == 3 && variable.isDiscrete() ) {
String gt = variable.getGridType();
// TODO other discrete types.
if ( gt != null ) {
options = makeOptions(viewtype);
lr.setOptions("ferret", options);
if ( gt.equals("timeseries") ) {
lr.setOperation("Timeseries_interactive_plot");
} else if (gt.equals("profile") ) {
lr.setOperation("Profile_interactive_plot");
} else if ( gt.equals("trajectory") ) {
lr.setOperation("Trajectory_interactive_plot");
}
}
}
Date now = new Date();
String timestamp = String.valueOf(now.getTime());
lr.setProperty("ferret", "annotations", "file");
lr.setProperty("result","annotations_ID", "annotations");
lr.setProperty("result","annotations_filename", timestamp+"_annotations.xml");
lr.setProperty("result","annotations_type","annotations");
lr.setProperty("data_0", "dataset_name", "Test data set");
HashMap<String, HashMap<String,String[]>> region = new HashMap<String, HashMap<String,String[]>>();
region = makeRegion(viewtype, variable);
if(region != null){lr.setRegion(region);}
return lr;
}
/**
* Make a region for a plot
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public ArrayList<OptionBean> makeOptions(String viewtype){
ArrayList<OptionBean> options = new ArrayList<OptionBean>();
OptionBean opb1 = new OptionBean();
opb1.setWidget_name("interpolate_data");
opb1.setValue("false");
options.add(opb1);
OptionBean opb2 = new OptionBean();
opb2.setWidget_name("image_format");
opb2.setValue("default");
options.add(opb2);
OptionBean opb3 = new OptionBean();
opb3.setWidget_name("size");
opb3.setValue(".5");
options.add(opb3);
OptionBean opb4 = new OptionBean();
opb4.setWidget_name("use_ref_map");
opb4.setValue("default");
options.add(opb4);
OptionBean opb5 = new OptionBean();
opb5.setWidget_name("use_graticules");
opb5.setValue("default");
options.add(opb5);
OptionBean opb6 = new OptionBean();
opb6.setWidget_name("no_margins");
opb6.setValue("default");
options.add(opb6);
OptionBean opb7 = new OptionBean();
opb7.setWidget_name("deg_min_sec");
opb7.setValue("default");
options.add(opb7);
OptionBean opb8 = new OptionBean();
opb8.setWidget_name("view");
opb8.setValue(viewtype);
options.add(opb8);
return options;
}
/**
* Make a region for a plot
* @param viewtype view type of the plot
* @param dsID dataset ID
* @param varID variable ID
*/
public HashMap<String, HashMap<String,String[]>> makeRegion(String viewtype, Variable variable){
Grid grid = variable.getGrid();
String xLo = "";
String xHi = "";
String yLo = "";
String yHi = "";
String zLo = "";
String zHi = "";
String tLo = "";
String tHi = "";
boolean hasZ = false;
boolean hasT = false;
DateTime lodt=null;
DateTime hidt=null;
HashMap<String, HashMap<String,String[]>> region = new HashMap<String, HashMap<String,String[]>>();
HashMap<String,String[]> points = new HashMap<String,String[]>();
HashMap<String,String[]> intervals = new HashMap<String,String[]>();
try{
//get the end points of each axis
xLo = grid.getAxis("x").getLo();
xHi = grid.getAxis("x").getHi();
yLo = grid.getAxis("y") .getLo();
yHi = grid.getAxis("y").getHi();
if(grid.hasZ()){
hasZ = true;
zLo = grid.getAxis("z").getLo();
zHi = grid.getAxis("z").getHi();
}
//time axis
if(grid.hasT()){
hasT = true;
//get time format for this variable defined in dataset configuration file
tLo = grid.getTime().getLo();
LASDateFormat ldf = new LASDateFormat(tLo);
String tFormat = ldf.getDateFormat();
DateTimeFormatter fmt = DateTimeFormat.forPattern(tFormat).withZone(DateTimeZone.UTC);
DateTimeFormatter ferretfmt = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.UTC);
lodt = fmt.parseDateTime(tLo);
tLo = lodt.toString(ferretfmt);
tHi = grid.getTime().getHi();
hidt= fmt.parseDateTime(tHi);
tHi = hidt.toString(ferretfmt);
}
}catch (Exception e){
e.printStackTrace();
}
//make a x interval or point
if(viewtype.contains("x")){
//make a small x interval in case it's a large dataset
String[] x = new String[2];
double lox = Double.valueOf(xLo).doubleValue();
double hix = Double.valueOf(xHi).doubleValue();
double dx = hix - lox;
x[0] = xLo;
x[1] = Double.toString(lox+(dx/4));
intervals.put("x",x);
}else{
//make a x point
String[] x = new String[1];
x[0] = xLo;
points.put("x",x);
}
//make a y interval or point
if(viewtype.contains("y")){
//make a small y interval in case it's a large dataset
String[] y = new String[2];
double loy = Double.valueOf(yLo).doubleValue();
double hiy = Double.valueOf(yHi).doubleValue();
double dy = hiy - loy;
y[0] = yLo;
y[1] = Double.toString(loy+(dy/4));
intervals.put("y",y);
}else{
//make a y point
String[] y = new String[1];
y[0] = yLo;
points.put("y",y);
}
//make a z interval or point
if(hasZ){
if(viewtype.contains("z") || variable.isDiscrete() ){
//make a z interval
String[] z = new String[2];
z[0] = zLo;
z[1] = zHi;
intervals.put("z",z);
}else{
//make a z point
String[] z = new String[1];
z[0] = zLo;
points.put("z",z);
}
}
//make a t interval or point
if(hasT){
if(viewtype.contains("t")){
//make a t interval
String[] t = new String[2];
t[0] = tLo;
t[1] = tHi;
intervals.put("t",t);
}else{
//make a t point
String[] t = new String[1];
t[0] = tLo;
points.put("t",t);
}
}
region.put("intervals", intervals);
region.put("points", points);
return region;
}
public LASTimeAxis getLASTimeAxis(String varpath){
LASTimeAxis lta = new LASTimeAxis();
String timeStyle = null;
try{
if (!varpath.contains("@ID")) {
String[] parts = varpath.split("/");
// Throw away index 0 since the string has a leading "/".
varpath = "/"+parts[1]+"/"+parts[2]+"/dataset[@ID='"+parts[3]+"']/"+parts[4]+"/variable[@ID='"+parts[5]+"']";
}
Element variable = lasConfig.getElementByXPath(varpath);
if (variable == null) {
return null;
}
String gridID = variable.getChild("grid").getAttributeValue("IDREF");
Element grid = lasConfig.getElementByXPath("/lasdata/grids/grid[@ID='"+gridID+"']");
if (grid == null) {
//System.out.println("grid");
return null;
}
List axes = grid.getChildren("axis");
for (Iterator axIt = axes.iterator(); axIt.hasNext();) {
Element axis = (Element) axIt.next();
String axisID = axis.getAttributeValue("IDREF");
axis = lasConfig.getElementByXPath("/lasdata/axes/axis[@ID='"+axisID+"']");
String t = axis.getAttributeValue("type");
if ( t.equals("t") ) {
lta.setUnit(axis.getAttributeValue("units"));
Element arange = axis.getChild("arange");
if (arange == null) {
List v = axis.getChildren("v");
if(v != null){
timeStyle = "v";
lta.setStyle("v");
}
} else {
timeStyle = "arange";
lta.setStyle("arange");
double size = Double.valueOf(arange.getAttributeValue("size")).doubleValue();
double step = Double.valueOf(arange.getAttributeValue("step")).doubleValue();
lta.setSize(size);
lta.setStep(step);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return lta;
}
}
| 24,447 | 0.600949 | 0.596041 | 794 | 29.79723 | 25.750408 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.541562 | false | false | 8 |
c995ec9b78f9f996e53ef987d73e9c43fb2087e7 | 24,739,011,684,280 | 4ef1b972593f699a71e4eca7ee1010aa231f52cc | /app/src/main/java/com/hotniao/video/activity/HnGeneralizeActivity.java | cfa6ec730e5c611a5861b7a2bb742ace042c5453 | []
| no_license | LoooooG/youyou | https://github.com/LoooooG/youyou | e2e8fb0f576a6e2daf614d1186303ec7ce7bdf4a | 5bff0de57159ab3dda075343b83ff4a461df66e2 | refs/heads/master | 2020-12-03T12:52:00.462000 | 2020-02-17T10:29:59 | 2020-02-17T10:29:59 | 231,321,844 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hotniao.video.activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hn.library.base.BaseActivity;
import com.hn.library.base.BaseRequestStateListener;
import com.hn.library.loadstate.HnLoadingLayout;
import com.hn.library.refresh.PtrClassicFrameLayout;
import com.hn.library.refresh.PtrDefaultHandler2;
import com.hn.library.refresh.PtrFrameLayout;
import com.hn.library.utils.HnToastUtils;
import com.hn.library.utils.HnUtils;
import com.hotniao.video.HnApplication;
import com.hotniao.video.R;
import com.hotniao.video.adapter.HnRewardAdapter;
import com.hotniao.video.biz.share.HnShareBiz;
import com.hotniao.video.dialog.HnEarningTotalTypePopWindow;
import com.hotniao.video.model.HnGeneralizeModel;
import com.hotniao.video.model.HnRewardLogModel;
import com.hotniao.video.utils.HnUiUtils;
import com.reslibrarytwo.HnSkinTextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class HnGeneralizeActivity extends BaseActivity implements BaseRequestStateListener {
@BindView(R.id.mHnLoadingLayout)
HnLoadingLayout mHnLoadingLayout;
@BindView(R.id.recyclerview)
RecyclerView mLvBillRec;
@BindView(R.id.ptr_refresh)
PtrClassicFrameLayout mSwipeRefresh;
@BindView(R.id.tv_person_num)
TextView tvPersonNum;
@BindView(R.id.iv_arrow)
ImageView ivArrow;
@BindView(R.id.iv_reward)
ImageView ivReward;
@BindView(R.id.tv_earnings)
TextView tvEarnings;
/**
* 提现记录列表适配器
*/
private HnRewardAdapter rewardLogAdapter;
/**
* 页数
*/
private int mPage = 1;
/**
* 时间类型
*/
private String mDateType = HnEarningTotalTypePopWindow.DAY;
private HnEarningTotalTypePopWindow mPopWindow;
private TextView mTvTotal, mTvEmpty;
private HnSkinTextView mTvType;
private List<HnRewardLogModel.DBean.ItemsBean> mData = new ArrayList<>();
private HnShareBiz shareBiz;
@Override
public int getContentViewId() {
return R.layout.activity_generalize;
}
@Override
public void onCreateNew(Bundle savedInstanceState) {
setTitle("我的推广");
setShowBack(true);
shareBiz = new HnShareBiz(this);
shareBiz.setBaseRequestStateListener(this);
//初始化适配器
rewardLogAdapter = new HnRewardAdapter(mData);
mLvBillRec.setLayoutManager(new LinearLayoutManager(this));
mLvBillRec.setHasFixedSize(true);
mLvBillRec.setAdapter(rewardLogAdapter);
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
addHead();
initEvent();
}
private void initEvent() {
//刷新处理
mSwipeRefresh.setPtrHandler(new PtrDefaultHandler2() {
@Override
public void onLoadMoreBegin(PtrFrameLayout frame) {
mPage += 1;
getInitData();
}
@Override
public void onRefreshBegin(PtrFrameLayout frame) {
mPage = 1;
getInitData();
}
});
//错误重新加载
mHnLoadingLayout.setOnReloadListener(new HnLoadingLayout.OnReloadListener() {
@Override
public void onReload(View v) {
mPage = 1;
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
getInitData();
}
});
}
private void initHeaderView(HnGeneralizeModel.DBean model){
if(model != null){
mTvTotal.setText(HnUtils.setTwoPoints(model.getTotal_money()+"")+HnApplication.getmConfig().getDot());
tvPersonNum.setText(model.getUser_invite_total() + "人");
tvEarnings.setText(HnUtils.setTwoPoints(model.getUser_invite_reward()+"") + "元");
}
}
/**
* 添加头部
*/
private void addHead() {
View view = LayoutInflater.from(this).inflate(R.layout.head_earning_total, null);
mTvTotal = (TextView) view.findViewById(R.id.mTvTotal);
mTvEmpty = (TextView) view.findViewById(R.id.mTvEmpty);
mTvType = (HnSkinTextView) view.findViewById(R.id.mTvType);
view.findViewById(R.id.rl_reward_header).setVisibility(View.VISIBLE);
if (mPopWindow == null) {
mPopWindow = new HnEarningTotalTypePopWindow(this);
mPopWindow.setOnItemClickListener(new HnEarningTotalTypePopWindow.OnItemClickListener() {
@Override
public void itemClick(String name, String type) {
mTvType.setText(name);
mDateType = type;
mPage = 1;
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
getInitData();
}
@Override
public void dismissLis() {
mTvType.setRightDrawable(R.drawable.account_lower);
}
});
}
mTvType.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mPopWindow == null) {
mPopWindow = new HnEarningTotalTypePopWindow(HnGeneralizeActivity.this);
}
mPopWindow.showUp(v);
mTvType.setRightDrawable(R.drawable.account_upper);
}
});
rewardLogAdapter.addHeaderView(view);
}
@OnClick({R.id.tv_exchange,R.id.rl_invite_user,R.id.rl_get_money})
public void click(View view){
switch (view.getId()){
case R.id.tv_exchange:
openActivity(HnMyExchangeActivity.class);
break;
case R.id.rl_invite_user:
openActivity(HnMyInviteUserActivity.class);
break;
case R.id.rl_get_money:
openActivity(HnGetMoneyActivity.class);
break;
}
}
@Override
public void getInitData() {
shareBiz.rewardLog(mPage, mDateType);
shareBiz.generalizeIndex();
}
private void setEmpty() {
if (mTvEmpty == null) return;
mHnLoadingLayout.setStatus(HnLoadingLayout.Success);
mTvEmpty.setVisibility(mData.size() < 1 ? View.VISIBLE : View.GONE);
}
@Override
public void requesting() {
}
@Override
public void requestSuccess(String type, String response, Object obj) {
if (HnShareBiz.REWARD_LOG.equals(type)) {
HnRewardLogModel model = (HnRewardLogModel) obj;
try {
mSwipeRefresh.refreshComplete();
HnRewardLogModel.DBean d = model.getD();
List<HnRewardLogModel.DBean.ItemsBean> items = d.getItems();
// mTvTotal.setText( HnUtils.setTwoPoints(model.getD().getAmount_total())+HnApplication.getmConfig().getDot());
mHnLoadingLayout.setStatus(HnLoadingLayout.Success);
if (mPage == 1) {
mData.clear();
}
mData.addAll(items);
if (rewardLogAdapter != null)
rewardLogAdapter.notifyDataSetChanged();
setEmpty();
HnUiUtils.setRefreshMode(mSwipeRefresh, mPage, 20, rewardLogAdapter.getItemCount());
} catch (Exception e) {
setEmpty();
}
} else if (HnShareBiz.GENERALIZE_INDEX.equals(type)) {
HnGeneralizeModel model = (HnGeneralizeModel) obj;
initHeaderView(model.getD());
}
}
@Override
public void requestFail(String type, int code, String msg) {
if (HnShareBiz.REWARD_LOG.equals(type)) {
mSwipeRefresh.refreshComplete();
setEmpty();
} else {
HnToastUtils.showToastShort(msg);
}
}
}
| UTF-8 | Java | 8,154 | java | HnGeneralizeActivity.java | Java | []
| null | []
| package com.hotniao.video.activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hn.library.base.BaseActivity;
import com.hn.library.base.BaseRequestStateListener;
import com.hn.library.loadstate.HnLoadingLayout;
import com.hn.library.refresh.PtrClassicFrameLayout;
import com.hn.library.refresh.PtrDefaultHandler2;
import com.hn.library.refresh.PtrFrameLayout;
import com.hn.library.utils.HnToastUtils;
import com.hn.library.utils.HnUtils;
import com.hotniao.video.HnApplication;
import com.hotniao.video.R;
import com.hotniao.video.adapter.HnRewardAdapter;
import com.hotniao.video.biz.share.HnShareBiz;
import com.hotniao.video.dialog.HnEarningTotalTypePopWindow;
import com.hotniao.video.model.HnGeneralizeModel;
import com.hotniao.video.model.HnRewardLogModel;
import com.hotniao.video.utils.HnUiUtils;
import com.reslibrarytwo.HnSkinTextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class HnGeneralizeActivity extends BaseActivity implements BaseRequestStateListener {
@BindView(R.id.mHnLoadingLayout)
HnLoadingLayout mHnLoadingLayout;
@BindView(R.id.recyclerview)
RecyclerView mLvBillRec;
@BindView(R.id.ptr_refresh)
PtrClassicFrameLayout mSwipeRefresh;
@BindView(R.id.tv_person_num)
TextView tvPersonNum;
@BindView(R.id.iv_arrow)
ImageView ivArrow;
@BindView(R.id.iv_reward)
ImageView ivReward;
@BindView(R.id.tv_earnings)
TextView tvEarnings;
/**
* 提现记录列表适配器
*/
private HnRewardAdapter rewardLogAdapter;
/**
* 页数
*/
private int mPage = 1;
/**
* 时间类型
*/
private String mDateType = HnEarningTotalTypePopWindow.DAY;
private HnEarningTotalTypePopWindow mPopWindow;
private TextView mTvTotal, mTvEmpty;
private HnSkinTextView mTvType;
private List<HnRewardLogModel.DBean.ItemsBean> mData = new ArrayList<>();
private HnShareBiz shareBiz;
@Override
public int getContentViewId() {
return R.layout.activity_generalize;
}
@Override
public void onCreateNew(Bundle savedInstanceState) {
setTitle("我的推广");
setShowBack(true);
shareBiz = new HnShareBiz(this);
shareBiz.setBaseRequestStateListener(this);
//初始化适配器
rewardLogAdapter = new HnRewardAdapter(mData);
mLvBillRec.setLayoutManager(new LinearLayoutManager(this));
mLvBillRec.setHasFixedSize(true);
mLvBillRec.setAdapter(rewardLogAdapter);
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
addHead();
initEvent();
}
private void initEvent() {
//刷新处理
mSwipeRefresh.setPtrHandler(new PtrDefaultHandler2() {
@Override
public void onLoadMoreBegin(PtrFrameLayout frame) {
mPage += 1;
getInitData();
}
@Override
public void onRefreshBegin(PtrFrameLayout frame) {
mPage = 1;
getInitData();
}
});
//错误重新加载
mHnLoadingLayout.setOnReloadListener(new HnLoadingLayout.OnReloadListener() {
@Override
public void onReload(View v) {
mPage = 1;
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
getInitData();
}
});
}
private void initHeaderView(HnGeneralizeModel.DBean model){
if(model != null){
mTvTotal.setText(HnUtils.setTwoPoints(model.getTotal_money()+"")+HnApplication.getmConfig().getDot());
tvPersonNum.setText(model.getUser_invite_total() + "人");
tvEarnings.setText(HnUtils.setTwoPoints(model.getUser_invite_reward()+"") + "元");
}
}
/**
* 添加头部
*/
private void addHead() {
View view = LayoutInflater.from(this).inflate(R.layout.head_earning_total, null);
mTvTotal = (TextView) view.findViewById(R.id.mTvTotal);
mTvEmpty = (TextView) view.findViewById(R.id.mTvEmpty);
mTvType = (HnSkinTextView) view.findViewById(R.id.mTvType);
view.findViewById(R.id.rl_reward_header).setVisibility(View.VISIBLE);
if (mPopWindow == null) {
mPopWindow = new HnEarningTotalTypePopWindow(this);
mPopWindow.setOnItemClickListener(new HnEarningTotalTypePopWindow.OnItemClickListener() {
@Override
public void itemClick(String name, String type) {
mTvType.setText(name);
mDateType = type;
mPage = 1;
mHnLoadingLayout.setStatus(HnLoadingLayout.Loading);
getInitData();
}
@Override
public void dismissLis() {
mTvType.setRightDrawable(R.drawable.account_lower);
}
});
}
mTvType.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mPopWindow == null) {
mPopWindow = new HnEarningTotalTypePopWindow(HnGeneralizeActivity.this);
}
mPopWindow.showUp(v);
mTvType.setRightDrawable(R.drawable.account_upper);
}
});
rewardLogAdapter.addHeaderView(view);
}
@OnClick({R.id.tv_exchange,R.id.rl_invite_user,R.id.rl_get_money})
public void click(View view){
switch (view.getId()){
case R.id.tv_exchange:
openActivity(HnMyExchangeActivity.class);
break;
case R.id.rl_invite_user:
openActivity(HnMyInviteUserActivity.class);
break;
case R.id.rl_get_money:
openActivity(HnGetMoneyActivity.class);
break;
}
}
@Override
public void getInitData() {
shareBiz.rewardLog(mPage, mDateType);
shareBiz.generalizeIndex();
}
private void setEmpty() {
if (mTvEmpty == null) return;
mHnLoadingLayout.setStatus(HnLoadingLayout.Success);
mTvEmpty.setVisibility(mData.size() < 1 ? View.VISIBLE : View.GONE);
}
@Override
public void requesting() {
}
@Override
public void requestSuccess(String type, String response, Object obj) {
if (HnShareBiz.REWARD_LOG.equals(type)) {
HnRewardLogModel model = (HnRewardLogModel) obj;
try {
mSwipeRefresh.refreshComplete();
HnRewardLogModel.DBean d = model.getD();
List<HnRewardLogModel.DBean.ItemsBean> items = d.getItems();
// mTvTotal.setText( HnUtils.setTwoPoints(model.getD().getAmount_total())+HnApplication.getmConfig().getDot());
mHnLoadingLayout.setStatus(HnLoadingLayout.Success);
if (mPage == 1) {
mData.clear();
}
mData.addAll(items);
if (rewardLogAdapter != null)
rewardLogAdapter.notifyDataSetChanged();
setEmpty();
HnUiUtils.setRefreshMode(mSwipeRefresh, mPage, 20, rewardLogAdapter.getItemCount());
} catch (Exception e) {
setEmpty();
}
} else if (HnShareBiz.GENERALIZE_INDEX.equals(type)) {
HnGeneralizeModel model = (HnGeneralizeModel) obj;
initHeaderView(model.getD());
}
}
@Override
public void requestFail(String type, int code, String msg) {
if (HnShareBiz.REWARD_LOG.equals(type)) {
mSwipeRefresh.refreshComplete();
setEmpty();
} else {
HnToastUtils.showToastShort(msg);
}
}
}
| 8,154 | 0.624876 | 0.623266 | 244 | 32.081966 | 24.8169 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528689 | false | false | 8 |
aadedc033d35ec31c31b9a62ffe2cc8d3d8bc350 | 24,739,011,683,710 | 1ffbed96573b72a2523fffb01a5edb7464396855 | /Unidadp2/Cambios2.1/src/cambios2/pkg1/moned.java | 768324fdc7fe48a9a2d9b636fee327bb7b68fa82 | []
| no_license | GeovaniTuz/Data_Structure | https://github.com/GeovaniTuz/Data_Structure | 19e2df2957dd519065bd6f4f1640eef94ca5adb2 | e8cf71ead03559835db78ef2b84dc8ffe8f2d21c | refs/heads/master | 2020-03-29T11:11:01.779000 | 2018-10-01T02:55:05 | 2018-10-01T02:55:05 | 149,839,980 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 cambios2.pkg1;
/**
*
* @author geoal
*/
public class moned {
public static void bille(int cambi) {
int mil = 0, quinientos = 0, doscientos= 0, cien =0, cincuenta=0, veinte=0, diez=0, cinco=0, dos=0;
int peso;
if (cambi >= 1000) {
mil = cambi / 1000;
System.out.println("Numero de billetes de $1000: " + mil);
bille(cambi % 1000);
} else {
if (cambi >= 500 && cambi <= 999) {
quinientos = cambi / 500;
System.out.println("Numero de billetes de $500: " + quinientos);
bille(cambi % 500);
} else {
if (cambi >= 200 && cambi <= 499) {
doscientos = cambi / 200;
System.out.println("Numero de billetes de $200: " + doscientos);
bille(cambi % 200);
} else {
if (cambi >= 100 && cambi <= 199) {
cien = cambi / 100;
System.out.println("Numero de billetes de $100: " + cien);
bille(cambi % 100);
} else {
if (cambi >= 50 && cambi <= 99) {
cincuenta = cambi / 50;
System.out.println("Numero de billetes de $50 " + cincuenta);
bille(cambi % 50);
} else {
if (cambi >= 20 && cambi <= 49) {
veinte = cambi / 20;
System.out.println("Numero de billetes de $20 " + veinte);
bille(cambi % 20);
} else {
if (cambi >= 10 && cambi <= 19) {
diez = cambi / 10;
System.out.println("Numero de monedas de $10 " + diez);
bille(cambi % 10);
} else {
if (cambi >= 5 && cambi <= 9) {
cinco = cambi / 5;
System.out.println("Numero de monedas de $5 " + cinco);
bille(cambi % 5);
} else {
if (cambi >= 2 && cambi <= 4) {
dos = cambi / 2;
System.out.println("Numero de monedas de $2 " + dos);
bille(cambi % 2);
} else {
if (cambi == 1) {
peso = cambi / 1;
System.out.println("Numero de monedas $1 " + peso);
}else{
}
}
}
}
}
}
}
}
}
}
}
} | UTF-8 | Java | 3,528 | java | moned.java | Java | [
{
"context": " */\r\npackage cambios2.pkg1;\r\n\r\n/**\r\n *\r\n * @author geoal\r\n */\r\npublic class moned {\r\n\r\n public static voi",
"end": 241,
"score": 0.8381803035736084,
"start": 236,
"tag": "USERNAME",
"value": "geoal"
}
]
| null | []
| /*
* 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 cambios2.pkg1;
/**
*
* @author geoal
*/
public class moned {
public static void bille(int cambi) {
int mil = 0, quinientos = 0, doscientos= 0, cien =0, cincuenta=0, veinte=0, diez=0, cinco=0, dos=0;
int peso;
if (cambi >= 1000) {
mil = cambi / 1000;
System.out.println("Numero de billetes de $1000: " + mil);
bille(cambi % 1000);
} else {
if (cambi >= 500 && cambi <= 999) {
quinientos = cambi / 500;
System.out.println("Numero de billetes de $500: " + quinientos);
bille(cambi % 500);
} else {
if (cambi >= 200 && cambi <= 499) {
doscientos = cambi / 200;
System.out.println("Numero de billetes de $200: " + doscientos);
bille(cambi % 200);
} else {
if (cambi >= 100 && cambi <= 199) {
cien = cambi / 100;
System.out.println("Numero de billetes de $100: " + cien);
bille(cambi % 100);
} else {
if (cambi >= 50 && cambi <= 99) {
cincuenta = cambi / 50;
System.out.println("Numero de billetes de $50 " + cincuenta);
bille(cambi % 50);
} else {
if (cambi >= 20 && cambi <= 49) {
veinte = cambi / 20;
System.out.println("Numero de billetes de $20 " + veinte);
bille(cambi % 20);
} else {
if (cambi >= 10 && cambi <= 19) {
diez = cambi / 10;
System.out.println("Numero de monedas de $10 " + diez);
bille(cambi % 10);
} else {
if (cambi >= 5 && cambi <= 9) {
cinco = cambi / 5;
System.out.println("Numero de monedas de $5 " + cinco);
bille(cambi % 5);
} else {
if (cambi >= 2 && cambi <= 4) {
dos = cambi / 2;
System.out.println("Numero de monedas de $2 " + dos);
bille(cambi % 2);
} else {
if (cambi == 1) {
peso = cambi / 1;
System.out.println("Numero de monedas $1 " + peso);
}else{
}
}
}
}
}
}
}
}
}
}
}
} | 3,528 | 0.320011 | 0.287415 | 96 | 34.770832 | 29.853279 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447917 | false | false | 8 |
c5785601f21dfc99c336c0e6ffd3a5f126e427cd | 28,106,266,036,157 | fed075f8806bdb11c8c6eaf94682556a4adf1de4 | /src/main/java/entity/Question_Type.java | e49260e9b1c380d2294e9318fa5f2141ba7018c6 | []
| no_license | lsl-nighttide/onlineText | https://github.com/lsl-nighttide/onlineText | 92d3cc01498d7aaab6309a546e1dd6537c1fc847 | 956a5834f7692398217bf08a4f842c3f79373c9c | refs/heads/master | 2022-10-31T13:35:35.753000 | 2019-09-23T12:22:55 | 2019-09-23T12:22:55 | 208,611,239 | 0 | 0 | null | false | 2022-11-15T23:47:57 | 2019-09-15T15:04:42 | 2019-09-23T12:22:58 | 2022-11-15T23:47:56 | 21,886 | 0 | 0 | 7 | JavaScript | false | false | package entity;
public class Question_Type {
private int question_type_id;
private int question_id;
private String question_type;
public Question_Type() {
}
public Question_Type(int question_type_id, int question_id, String question_type) {
this.question_type_id = question_type_id;
this.question_id = question_id;
this.question_type = question_type;
}
public int getQuestion_type_id() {
return question_type_id;
}
public void setQuestion_type_id(int question_type_id) {
this.question_type_id = question_type_id;
}
public int getQuestion_id() {
return question_id;
}
public void setQuestion_id(int question_id) {
this.question_id = question_id;
}
public String getQuestion_type() {
return question_type;
}
public void setQuestion_type(String question_type) {
this.question_type = question_type;
}
@Override
public String toString() {
return "Question_Type{" +
"question_type_id=" + question_type_id +
", question_id=" + question_id +
", question_type='" + question_type + '\'' +
'}';
}
}
| UTF-8 | Java | 1,230 | java | Question_Type.java | Java | []
| null | []
| package entity;
public class Question_Type {
private int question_type_id;
private int question_id;
private String question_type;
public Question_Type() {
}
public Question_Type(int question_type_id, int question_id, String question_type) {
this.question_type_id = question_type_id;
this.question_id = question_id;
this.question_type = question_type;
}
public int getQuestion_type_id() {
return question_type_id;
}
public void setQuestion_type_id(int question_type_id) {
this.question_type_id = question_type_id;
}
public int getQuestion_id() {
return question_id;
}
public void setQuestion_id(int question_id) {
this.question_id = question_id;
}
public String getQuestion_type() {
return question_type;
}
public void setQuestion_type(String question_type) {
this.question_type = question_type;
}
@Override
public String toString() {
return "Question_Type{" +
"question_type_id=" + question_type_id +
", question_id=" + question_id +
", question_type='" + question_type + '\'' +
'}';
}
}
| 1,230 | 0.591057 | 0.591057 | 49 | 24.102041 | 21.577808 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367347 | false | false | 8 |
adc782318e07e7b898565f9f55d5f778448d061d | 25,142,738,562,782 | 184b07fd91702ca483e00eaa1d4eb8c10a7d4975 | /wf_salaryMail/src/com/salaryMail/entity/TempletSalaryInfo.java | a436518b171a907d3235cdfd38f27c0d05e5bcfd | []
| no_license | blueNormandie/GTSP | https://github.com/blueNormandie/GTSP | 90c69c6fac0a64dca902e55ad58b549bd124740e | 30e927f5c5ccb367c3a77102c4451fd302952f83 | refs/heads/master | 2021-01-11T05:53:24.261000 | 2017-06-19T06:33:21 | 2017-06-19T06:33:21 | 69,640,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.salaryMail.entity;
public class TempletSalaryInfo {
private Integer bigTitlePosition;//大标题位置
private String bigTitle;//大标题显示名称
private String bigRemarks;//大标题标题备注信息
private String isCount;//是否显示合计
private String bigSum;//合计
/**
* @return the bigTitlePosition
*/
public Integer getBigTitlePosition() {
return bigTitlePosition;
}
/**
* @param bigTitlePosition the bigTitlePosition to set
*/
public void setBigTitlePosition(Integer bigTitlePosition) {
this.bigTitlePosition = bigTitlePosition;
}
/**
* @return the bigTitle
*/
public String getBigTitle() {
return bigTitle;
}
/**
* @param bigTitle the bigTitle to set
*/
public void setBigTitle(String bigTitle) {
this.bigTitle = bigTitle;
}
/**
* @return the bigRemarks
*/
public String getBigRemarks() {
return bigRemarks;
}
/**
* @param bigRemarks the bigRemarks to set
*/
public void setBigRemarks(String bigRemarks) {
this.bigRemarks = bigRemarks;
}
public String getBigSum() {
return bigSum;
}
public void setBigSum(String bigSum) {
this.bigSum = bigSum;
}
/**
* @return the isCount
*/
public String getIsCount() {
return isCount;
}
/**
* @param isCount the isCount to set
*/
public void setIsCount(String isCount) {
this.isCount = isCount;
}
public TempletSalaryInfo(Integer bigTitlePosition, String bigTitle,
String bigRemarks, String bigSum,String isCount) {
super();
this.bigTitlePosition = bigTitlePosition;
this.bigTitle = bigTitle;
this.bigRemarks = bigRemarks;
this.bigSum = bigSum;
this.isCount=isCount;
}
public TempletSalaryInfo() {
super();
// TODO Auto-generated constructor stub
}
}
| UTF-8 | Java | 1,736 | java | TempletSalaryInfo.java | Java | []
| null | []
| package com.salaryMail.entity;
public class TempletSalaryInfo {
private Integer bigTitlePosition;//大标题位置
private String bigTitle;//大标题显示名称
private String bigRemarks;//大标题标题备注信息
private String isCount;//是否显示合计
private String bigSum;//合计
/**
* @return the bigTitlePosition
*/
public Integer getBigTitlePosition() {
return bigTitlePosition;
}
/**
* @param bigTitlePosition the bigTitlePosition to set
*/
public void setBigTitlePosition(Integer bigTitlePosition) {
this.bigTitlePosition = bigTitlePosition;
}
/**
* @return the bigTitle
*/
public String getBigTitle() {
return bigTitle;
}
/**
* @param bigTitle the bigTitle to set
*/
public void setBigTitle(String bigTitle) {
this.bigTitle = bigTitle;
}
/**
* @return the bigRemarks
*/
public String getBigRemarks() {
return bigRemarks;
}
/**
* @param bigRemarks the bigRemarks to set
*/
public void setBigRemarks(String bigRemarks) {
this.bigRemarks = bigRemarks;
}
public String getBigSum() {
return bigSum;
}
public void setBigSum(String bigSum) {
this.bigSum = bigSum;
}
/**
* @return the isCount
*/
public String getIsCount() {
return isCount;
}
/**
* @param isCount the isCount to set
*/
public void setIsCount(String isCount) {
this.isCount = isCount;
}
public TempletSalaryInfo(Integer bigTitlePosition, String bigTitle,
String bigRemarks, String bigSum,String isCount) {
super();
this.bigTitlePosition = bigTitlePosition;
this.bigTitle = bigTitle;
this.bigRemarks = bigRemarks;
this.bigSum = bigSum;
this.isCount=isCount;
}
public TempletSalaryInfo() {
super();
// TODO Auto-generated constructor stub
}
}
| 1,736 | 0.709774 | 0.709774 | 80 | 19.975 | 17.405441 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5375 | false | false | 8 |
a82bd074443770aac9f7a3e7424cf5c40b9751e0 | 19,250,043,423,790 | 70256617a0a608d17061aca0fa679b3847bc0982 | /samplecodes/hbaseclient/HBaseSample.java | 4677a18aae71bbf6614d4aac562e9c6e5d013901 | []
| no_license | osswangxining/osswangxining.github.io | https://github.com/osswangxining/osswangxining.github.io | b7231daf80647bf9a73daf15d3f110d738c69614 | ef36ae69dd827ad894a73da1dbc2005e99c64a4d | refs/heads/master | 2021-01-17T09:02:25.281000 | 2018-04-05T08:58:51 | 2018-04-05T08:58:51 | 83,970,691 | 3 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hbaseclient;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseSample {
private static final String TABLE_NAME = "MY_TABLE_NAME_TOO";
private static final String CF_DEFAULT = "DEFAULT_COLUMN_FAMILY";
public static void createOrOverwrite(Admin admin, HTableDescriptor table) throws IOException {
if (admin.tableExists(table.getTableName())) {
admin.disableTable(table.getTableName());
admin.deleteTable(table.getTableName());
}
admin.createTable(table);
}
public static void createSchemaTables(Configuration config) throws IOException {
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
HTableDescriptor table = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
table.addFamily(new HColumnDescriptor(CF_DEFAULT).setCompressionType(Algorithm.NONE));
table.addFamily(new HColumnDescriptor(CF_DEFAULT + 2).setCompressionType(Algorithm.NONE));
System.out.print("Creating table. ");
createOrOverwrite(admin, table);
System.out.println("Table is created.");
}
public static void modifySchema(Configuration config) throws IOException {
System.out.println("start to modifySchema ......");
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
TableName tableName = TableName.valueOf(TABLE_NAME);
if (!admin.tableExists(tableName)) {
System.out.println("Table does not exist.");
System.exit(-1);
}
HTableDescriptor table = admin.getTableDescriptor(tableName);
// Update existing table
HColumnDescriptor newColumn = new HColumnDescriptor("NEWCF");
newColumn.setCompactionCompressionType(Algorithm.GZ);
newColumn.setMaxVersions(HConstants.ALL_VERSIONS);
admin.addColumn(tableName, newColumn);
table.addFamily(newColumn);
// Update existing column family
HColumnDescriptor existingColumn = new HColumnDescriptor(CF_DEFAULT);
existingColumn.setCompactionCompressionType(Algorithm.GZ);
existingColumn.setMaxVersions(HConstants.ALL_VERSIONS);
table.modifyFamily(existingColumn);
admin.modifyTable(tableName, table);
System.out.println("end to modifySchema ......");
}
public static void drop(Configuration config) throws IOException {
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
TableName tableName = TableName.valueOf(TABLE_NAME);
if (!admin.tableExists(tableName)) {
System.out.println("Table does not exist.");
System.exit(-1);
}
// Disable an existing table
admin.disableTable(tableName);
// Delete an existing column family
admin.deleteColumn(tableName, CF_DEFAULT.getBytes("UTF-8"));
// Delete a table (Need to be disabled first)
admin.deleteTable(tableName);
}
private static void insertData(Configuration config) throws IOException {
System.out.println("start to insert data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Put put = new Put("112233bbbcccc".getBytes());
put.addColumn((CF_DEFAULT).getBytes(), "aaaaaa".getBytes(), "aaa".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "bbbbb".getBytes(), "bbbb".getBytes());
put.addColumn("NEWCF".getBytes(), "testcccc".getBytes(), "testcccccc".getBytes());
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to insert data ......");
}
private static void queryData(Configuration config) throws IOException {
System.out.println("start to query data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
try {
// Use the table as needed, for a single operation and a single thread
ResultScanner rs = table.getScanner(new Scan());
for (Result r : rs) {
System.out.println("rowkey:" + new String(r.getRow()));
Cell[] rawCells = r.rawCells();
for (Cell cell : rawCells) {
System.out.println("Rowkey:" + Bytes.toString(CellUtil.cloneRow(cell)) + " Familiy:Quilifier:"
+ Bytes.toString(CellUtil.cloneFamily(cell)) + ":" + Bytes.toString(CellUtil.cloneQualifier(cell))
+ " Value: " + Bytes.toString(CellUtil.cloneValue(cell)) + " Time: " + cell.getTimestamp());
}
}
} finally {
table.close();
connection.close();
}
System.out.println("end to query data ......");
}
private static void changeData(Configuration config) throws IOException {
System.out.println("start to update data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Put put = new Put("112233bbbcccc".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "aaaaaa".getBytes(), "aaa---new---".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "bbbbb".getBytes(), null);
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to update data ......");
}
private static void deleteData(Configuration config) throws IOException {
System.out.println("start to delete data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Delete delete = new Delete("112233bbbcccc".getBytes());
// delete.addColumn((CF_DEFAULT + 2).getBytes(), null);
try {
table.delete(delete);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to delete data ......");
}
public static void main(String... args) throws IOException {
Configuration config = HBaseConfiguration.create();
// Add any necessary configuration files (hbase-site.xml, core-site.xml)
config.addResource(new Path("/Users/xiningwang/hadoop/hbase-1.2.5/conf", "hbase-site.xml"));
config.addResource(new Path("/Users/xiningwang/hadoop/hadoop-2.7.3/etc/hadoop", "core-site.xml"));
createSchemaTables(config);
modifySchema(config);
insertData(config);
queryData(config);
changeData(config);
queryData(config);
deleteData(config);
queryData(config);
drop(config);
System.out.println("---completed......");
}
}
| UTF-8 | Java | 7,458 | java | HBaseSample.java | Java | []
| null | []
| package hbaseclient;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseSample {
private static final String TABLE_NAME = "MY_TABLE_NAME_TOO";
private static final String CF_DEFAULT = "DEFAULT_COLUMN_FAMILY";
public static void createOrOverwrite(Admin admin, HTableDescriptor table) throws IOException {
if (admin.tableExists(table.getTableName())) {
admin.disableTable(table.getTableName());
admin.deleteTable(table.getTableName());
}
admin.createTable(table);
}
public static void createSchemaTables(Configuration config) throws IOException {
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
HTableDescriptor table = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
table.addFamily(new HColumnDescriptor(CF_DEFAULT).setCompressionType(Algorithm.NONE));
table.addFamily(new HColumnDescriptor(CF_DEFAULT + 2).setCompressionType(Algorithm.NONE));
System.out.print("Creating table. ");
createOrOverwrite(admin, table);
System.out.println("Table is created.");
}
public static void modifySchema(Configuration config) throws IOException {
System.out.println("start to modifySchema ......");
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
TableName tableName = TableName.valueOf(TABLE_NAME);
if (!admin.tableExists(tableName)) {
System.out.println("Table does not exist.");
System.exit(-1);
}
HTableDescriptor table = admin.getTableDescriptor(tableName);
// Update existing table
HColumnDescriptor newColumn = new HColumnDescriptor("NEWCF");
newColumn.setCompactionCompressionType(Algorithm.GZ);
newColumn.setMaxVersions(HConstants.ALL_VERSIONS);
admin.addColumn(tableName, newColumn);
table.addFamily(newColumn);
// Update existing column family
HColumnDescriptor existingColumn = new HColumnDescriptor(CF_DEFAULT);
existingColumn.setCompactionCompressionType(Algorithm.GZ);
existingColumn.setMaxVersions(HConstants.ALL_VERSIONS);
table.modifyFamily(existingColumn);
admin.modifyTable(tableName, table);
System.out.println("end to modifySchema ......");
}
public static void drop(Configuration config) throws IOException {
Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin();
TableName tableName = TableName.valueOf(TABLE_NAME);
if (!admin.tableExists(tableName)) {
System.out.println("Table does not exist.");
System.exit(-1);
}
// Disable an existing table
admin.disableTable(tableName);
// Delete an existing column family
admin.deleteColumn(tableName, CF_DEFAULT.getBytes("UTF-8"));
// Delete a table (Need to be disabled first)
admin.deleteTable(tableName);
}
private static void insertData(Configuration config) throws IOException {
System.out.println("start to insert data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Put put = new Put("112233bbbcccc".getBytes());
put.addColumn((CF_DEFAULT).getBytes(), "aaaaaa".getBytes(), "aaa".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "bbbbb".getBytes(), "bbbb".getBytes());
put.addColumn("NEWCF".getBytes(), "testcccc".getBytes(), "testcccccc".getBytes());
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to insert data ......");
}
private static void queryData(Configuration config) throws IOException {
System.out.println("start to query data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
try {
// Use the table as needed, for a single operation and a single thread
ResultScanner rs = table.getScanner(new Scan());
for (Result r : rs) {
System.out.println("rowkey:" + new String(r.getRow()));
Cell[] rawCells = r.rawCells();
for (Cell cell : rawCells) {
System.out.println("Rowkey:" + Bytes.toString(CellUtil.cloneRow(cell)) + " Familiy:Quilifier:"
+ Bytes.toString(CellUtil.cloneFamily(cell)) + ":" + Bytes.toString(CellUtil.cloneQualifier(cell))
+ " Value: " + Bytes.toString(CellUtil.cloneValue(cell)) + " Time: " + cell.getTimestamp());
}
}
} finally {
table.close();
connection.close();
}
System.out.println("end to query data ......");
}
private static void changeData(Configuration config) throws IOException {
System.out.println("start to update data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Put put = new Put("112233bbbcccc".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "aaaaaa".getBytes(), "aaa---new---".getBytes());
put.addColumn((CF_DEFAULT + 2).getBytes(), "bbbbb".getBytes(), null);
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to update data ......");
}
private static void deleteData(Configuration config) throws IOException {
System.out.println("start to delete data ......");
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
Delete delete = new Delete("112233bbbcccc".getBytes());
// delete.addColumn((CF_DEFAULT + 2).getBytes(), null);
try {
table.delete(delete);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end to delete data ......");
}
public static void main(String... args) throws IOException {
Configuration config = HBaseConfiguration.create();
// Add any necessary configuration files (hbase-site.xml, core-site.xml)
config.addResource(new Path("/Users/xiningwang/hadoop/hbase-1.2.5/conf", "hbase-site.xml"));
config.addResource(new Path("/Users/xiningwang/hadoop/hadoop-2.7.3/etc/hadoop", "core-site.xml"));
createSchemaTables(config);
modifySchema(config);
insertData(config);
queryData(config);
changeData(config);
queryData(config);
deleteData(config);
queryData(config);
drop(config);
System.out.println("---completed......");
}
}
| 7,458 | 0.708903 | 0.704612 | 185 | 39.313515 | 28.270681 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708108 | false | false | 8 |
6dfe6de4e3461b9977a06e1b03d29118c76c3959 | 15,358,803,110,042 | 75e5d43fdc33b8e8901f3c19630a33294eee075d | /src/com/chainton/toolsbox/view/BorderImageView.java | 82a84b6b4a276c4db6f797cb6b99cc5ae18b9da1 | []
| no_license | chainton/dankeshare-app | https://github.com/chainton/dankeshare-app | 0b513b686dae31e42cf230ab6b8ddfd982ca8fc9 | a430975feaba249ce7213d2871b8a13874efd495 | refs/heads/master | 2016-08-03T19:40:23.618000 | 2014-02-27T11:38:42 | 2014-02-27T11:38:42 | 15,387,983 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chainton.toolsbox.view;
import com.chainton.shareservice.app.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ImageView;
public class BorderImageView extends ImageView {
private int mBorderColor = 0xFFFFFFFF;
private int mBorderWidth = 1;
public BorderImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BorderImageView, defStyle, 0);
mBorderColor = typedArray.getInteger(R.styleable.BorderImageView_border_color, mBorderColor);
mBorderWidth = typedArray.getDimensionPixelSize(R.styleable.BorderImageView_border_width, mBorderColor);
}
public BorderImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BorderImageView);
mBorderColor = typedArray.getInteger(R.styleable.BorderImageView_border_color, mBorderColor);
mBorderWidth = typedArray.getDimensionPixelSize(R.styleable.BorderImageView_border_width, mBorderColor);
}
public BorderImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// 画边框
Rect rec = canvas.getClipBounds();
rec.bottom--;
rec.right--;
Paint paint = new Paint();
paint.setColor(mBorderColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mBorderWidth);
canvas.drawRect(rec, paint);
}
}
| UTF-8 | Java | 1,806 | java | BorderImageView.java | Java | []
| null | []
| package com.chainton.toolsbox.view;
import com.chainton.shareservice.app.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ImageView;
public class BorderImageView extends ImageView {
private int mBorderColor = 0xFFFFFFFF;
private int mBorderWidth = 1;
public BorderImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BorderImageView, defStyle, 0);
mBorderColor = typedArray.getInteger(R.styleable.BorderImageView_border_color, mBorderColor);
mBorderWidth = typedArray.getDimensionPixelSize(R.styleable.BorderImageView_border_width, mBorderColor);
}
public BorderImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BorderImageView);
mBorderColor = typedArray.getInteger(R.styleable.BorderImageView_border_color, mBorderColor);
mBorderWidth = typedArray.getDimensionPixelSize(R.styleable.BorderImageView_border_width, mBorderColor);
}
public BorderImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// 画边框
Rect rec = canvas.getClipBounds();
rec.bottom--;
rec.right--;
Paint paint = new Paint();
paint.setColor(mBorderColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mBorderWidth);
canvas.drawRect(rec, paint);
}
}
| 1,806 | 0.787778 | 0.786111 | 53 | 32.962265 | 29.648228 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90566 | false | false | 8 |
de897e5bb91a3bb8feb29c3476c5728556e5dd57 | 13,503,377,182,641 | 6c80539ea28905aa354be31192466d71c8d88b00 | /src/main/java/com/marzmakeupver2/marzappver2/api/response/ScenarioResponse.java | 3d282e15c3ce60ccb2e6447ddb217e57de1393c2 | []
| no_license | artuzgreen/SpringRestApp-scenario-for-makeup-artist | https://github.com/artuzgreen/SpringRestApp-scenario-for-makeup-artist | ad8c41297c7075bfee578b68fafdf0d4cd605b00 | f98c07327913947a69aa2c01d602068d6cfb20ea | refs/heads/master | 2023-05-04T16:00:52.674000 | 2021-05-20T00:42:24 | 2021-05-20T00:42:24 | 368,243,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.marzmakeupver2.marzappver2.api.response;
import com.marzmakeupver2.marzappver2.domain.Styling;
import java.util.Set;
public class ScenarioResponse {
private Long id;
private int day;
private String partOfADay;
private String location;
private String comment;
private Set<Styling> stylingList;
public ScenarioResponse(Long id, int day, String partOfADay, String location, String comment, Set<Styling> stylingList) {
this.id = id;
this.day = day;
this.partOfADay = partOfADay;
this.location = location;
this.comment = comment;
this.stylingList = stylingList;
}
public Long getId() {
return id;
}
public int getDay() {
return day;
}
public String getPartOfADay() {
return partOfADay;
}
public String getLocation() {
return location;
}
public String getComment() {
return comment;
}
public Set<Styling> getStylingList() {
return stylingList;
}
}
| UTF-8 | Java | 1,041 | java | ScenarioResponse.java | Java | []
| null | []
| package com.marzmakeupver2.marzappver2.api.response;
import com.marzmakeupver2.marzappver2.domain.Styling;
import java.util.Set;
public class ScenarioResponse {
private Long id;
private int day;
private String partOfADay;
private String location;
private String comment;
private Set<Styling> stylingList;
public ScenarioResponse(Long id, int day, String partOfADay, String location, String comment, Set<Styling> stylingList) {
this.id = id;
this.day = day;
this.partOfADay = partOfADay;
this.location = location;
this.comment = comment;
this.stylingList = stylingList;
}
public Long getId() {
return id;
}
public int getDay() {
return day;
}
public String getPartOfADay() {
return partOfADay;
}
public String getLocation() {
return location;
}
public String getComment() {
return comment;
}
public Set<Styling> getStylingList() {
return stylingList;
}
}
| 1,041 | 0.639769 | 0.635927 | 48 | 20.6875 | 21.511776 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 8 |
536069d59a2f658220d18b2e25577da16d35de50 | 35,613,868,840,363 | 96ef4dcb045db15ecd904d569a60e653a7958ab5 | /cloud-repository/src/main/java/cn/threefishes/cloudrepository/entity/AdvertorialAuthorRecommendExample.java | f7a8f9ca55030deefa09d7b3f5cc67fcb7e95873 | [
"MIT"
]
| permissive | threefishes/springCloudMainService | https://github.com/threefishes/springCloudMainService | ba357ae99c92841256dadf9822e53a0e5c9bcd46 | 9b20cf8a955cc0e7f52e1a0550dac385866369f4 | refs/heads/master | 2022-12-21T12:42:50.762000 | 2021-01-21T01:12:03 | 2021-01-21T01:12:03 | 218,279,951 | 0 | 1 | MIT | false | 2022-12-16T04:56:23 | 2019-10-29T12:18:42 | 2021-01-21T01:12:12 | 2022-12-16T04:56:20 | 5,110 | 0 | 1 | 10 | Java | false | false | package cn.threefishes.cloudrepository.entity;
import java.util.ArrayList;
import java.util.List;
public class AdvertorialAuthorRecommendExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public AdvertorialAuthorRecommendExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andRecommendIdIsNull() {
addCriterion("recommend_id is null");
return (Criteria) this;
}
public Criteria andRecommendIdIsNotNull() {
addCriterion("recommend_id is not null");
return (Criteria) this;
}
public Criteria andRecommendIdEqualTo(Integer value) {
addCriterion("recommend_id =", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotEqualTo(Integer value) {
addCriterion("recommend_id <>", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdGreaterThan(Integer value) {
addCriterion("recommend_id >", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdGreaterThanOrEqualTo(Integer value) {
addCriterion("recommend_id >=", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdLessThan(Integer value) {
addCriterion("recommend_id <", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdLessThanOrEqualTo(Integer value) {
addCriterion("recommend_id <=", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdIn(List<Integer> values) {
addCriterion("recommend_id in", values, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotIn(List<Integer> values) {
addCriterion("recommend_id not in", values, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdBetween(Integer value1, Integer value2) {
addCriterion("recommend_id between", value1, value2, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotBetween(Integer value1, Integer value2) {
addCriterion("recommend_id not between", value1, value2, "recommendId");
return (Criteria) this;
}
public Criteria andMemberIdIsNull() {
addCriterion("member_id is null");
return (Criteria) this;
}
public Criteria andMemberIdIsNotNull() {
addCriterion("member_id is not null");
return (Criteria) this;
}
public Criteria andMemberIdEqualTo(Integer value) {
addCriterion("member_id =", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotEqualTo(Integer value) {
addCriterion("member_id <>", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdGreaterThan(Integer value) {
addCriterion("member_id >", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdGreaterThanOrEqualTo(Integer value) {
addCriterion("member_id >=", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdLessThan(Integer value) {
addCriterion("member_id <", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdLessThanOrEqualTo(Integer value) {
addCriterion("member_id <=", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdIn(List<Integer> values) {
addCriterion("member_id in", values, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotIn(List<Integer> values) {
addCriterion("member_id not in", values, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdBetween(Integer value1, Integer value2) {
addCriterion("member_id between", value1, value2, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotBetween(Integer value1, Integer value2) {
addCriterion("member_id not between", value1, value2, "memberId");
return (Criteria) this;
}
public Criteria andShareNumIsNull() {
addCriterion("share_num is null");
return (Criteria) this;
}
public Criteria andShareNumIsNotNull() {
addCriterion("share_num is not null");
return (Criteria) this;
}
public Criteria andShareNumEqualTo(Integer value) {
addCriterion("share_num =", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotEqualTo(Integer value) {
addCriterion("share_num <>", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumGreaterThan(Integer value) {
addCriterion("share_num >", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumGreaterThanOrEqualTo(Integer value) {
addCriterion("share_num >=", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumLessThan(Integer value) {
addCriterion("share_num <", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumLessThanOrEqualTo(Integer value) {
addCriterion("share_num <=", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumIn(List<Integer> values) {
addCriterion("share_num in", values, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotIn(List<Integer> values) {
addCriterion("share_num not in", values, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumBetween(Integer value1, Integer value2) {
addCriterion("share_num between", value1, value2, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotBetween(Integer value1, Integer value2) {
addCriterion("share_num not between", value1, value2, "shareNum");
return (Criteria) this;
}
public Criteria andCommentNumIsNull() {
addCriterion("comment_num is null");
return (Criteria) this;
}
public Criteria andCommentNumIsNotNull() {
addCriterion("comment_num is not null");
return (Criteria) this;
}
public Criteria andCommentNumEqualTo(Integer value) {
addCriterion("comment_num =", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotEqualTo(Integer value) {
addCriterion("comment_num <>", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumGreaterThan(Integer value) {
addCriterion("comment_num >", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumGreaterThanOrEqualTo(Integer value) {
addCriterion("comment_num >=", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumLessThan(Integer value) {
addCriterion("comment_num <", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumLessThanOrEqualTo(Integer value) {
addCriterion("comment_num <=", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumIn(List<Integer> values) {
addCriterion("comment_num in", values, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotIn(List<Integer> values) {
addCriterion("comment_num not in", values, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumBetween(Integer value1, Integer value2) {
addCriterion("comment_num between", value1, value2, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotBetween(Integer value1, Integer value2) {
addCriterion("comment_num not between", value1, value2, "commentNum");
return (Criteria) this;
}
public Criteria andLikeNumIsNull() {
addCriterion("like_num is null");
return (Criteria) this;
}
public Criteria andLikeNumIsNotNull() {
addCriterion("like_num is not null");
return (Criteria) this;
}
public Criteria andLikeNumEqualTo(Integer value) {
addCriterion("like_num =", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotEqualTo(Integer value) {
addCriterion("like_num <>", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumGreaterThan(Integer value) {
addCriterion("like_num >", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumGreaterThanOrEqualTo(Integer value) {
addCriterion("like_num >=", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumLessThan(Integer value) {
addCriterion("like_num <", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumLessThanOrEqualTo(Integer value) {
addCriterion("like_num <=", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumIn(List<Integer> values) {
addCriterion("like_num in", values, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotIn(List<Integer> values) {
addCriterion("like_num not in", values, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumBetween(Integer value1, Integer value2) {
addCriterion("like_num between", value1, value2, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotBetween(Integer value1, Integer value2) {
addCriterion("like_num not between", value1, value2, "likeNum");
return (Criteria) this;
}
public Criteria andFollowNumIsNull() {
addCriterion("follow_num is null");
return (Criteria) this;
}
public Criteria andFollowNumIsNotNull() {
addCriterion("follow_num is not null");
return (Criteria) this;
}
public Criteria andFollowNumEqualTo(Integer value) {
addCriterion("follow_num =", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotEqualTo(Integer value) {
addCriterion("follow_num <>", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumGreaterThan(Integer value) {
addCriterion("follow_num >", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumGreaterThanOrEqualTo(Integer value) {
addCriterion("follow_num >=", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumLessThan(Integer value) {
addCriterion("follow_num <", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumLessThanOrEqualTo(Integer value) {
addCriterion("follow_num <=", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumIn(List<Integer> values) {
addCriterion("follow_num in", values, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotIn(List<Integer> values) {
addCriterion("follow_num not in", values, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumBetween(Integer value1, Integer value2) {
addCriterion("follow_num between", value1, value2, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotBetween(Integer value1, Integer value2) {
addCriterion("follow_num not between", value1, value2, "followNum");
return (Criteria) this;
}
public Criteria andPageViewIsNull() {
addCriterion("page_view is null");
return (Criteria) this;
}
public Criteria andPageViewIsNotNull() {
addCriterion("page_view is not null");
return (Criteria) this;
}
public Criteria andPageViewEqualTo(Integer value) {
addCriterion("page_view =", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotEqualTo(Integer value) {
addCriterion("page_view <>", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewGreaterThan(Integer value) {
addCriterion("page_view >", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewGreaterThanOrEqualTo(Integer value) {
addCriterion("page_view >=", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewLessThan(Integer value) {
addCriterion("page_view <", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewLessThanOrEqualTo(Integer value) {
addCriterion("page_view <=", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewIn(List<Integer> values) {
addCriterion("page_view in", values, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotIn(List<Integer> values) {
addCriterion("page_view not in", values, "pageView");
return (Criteria) this;
}
public Criteria andPageViewBetween(Integer value1, Integer value2) {
addCriterion("page_view between", value1, value2, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotBetween(Integer value1, Integer value2) {
addCriterion("page_view not between", value1, value2, "pageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIsNull() {
addCriterion("enter_detail_page_view is null");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIsNotNull() {
addCriterion("enter_detail_page_view is not null");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewEqualTo(Integer value) {
addCriterion("enter_detail_page_view =", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotEqualTo(Integer value) {
addCriterion("enter_detail_page_view <>", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewGreaterThan(Integer value) {
addCriterion("enter_detail_page_view >", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewGreaterThanOrEqualTo(Integer value) {
addCriterion("enter_detail_page_view >=", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewLessThan(Integer value) {
addCriterion("enter_detail_page_view <", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewLessThanOrEqualTo(Integer value) {
addCriterion("enter_detail_page_view <=", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIn(List<Integer> values) {
addCriterion("enter_detail_page_view in", values, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotIn(List<Integer> values) {
addCriterion("enter_detail_page_view not in", values, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewBetween(Integer value1, Integer value2) {
addCriterion("enter_detail_page_view between", value1, value2, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotBetween(Integer value1, Integer value2) {
addCriterion("enter_detail_page_view not between", value1, value2, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andMaterialNumIsNull() {
addCriterion("material_num is null");
return (Criteria) this;
}
public Criteria andMaterialNumIsNotNull() {
addCriterion("material_num is not null");
return (Criteria) this;
}
public Criteria andMaterialNumEqualTo(Integer value) {
addCriterion("material_num =", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotEqualTo(Integer value) {
addCriterion("material_num <>", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumGreaterThan(Integer value) {
addCriterion("material_num >", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumGreaterThanOrEqualTo(Integer value) {
addCriterion("material_num >=", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumLessThan(Integer value) {
addCriterion("material_num <", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumLessThanOrEqualTo(Integer value) {
addCriterion("material_num <=", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumIn(List<Integer> values) {
addCriterion("material_num in", values, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotIn(List<Integer> values) {
addCriterion("material_num not in", values, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumBetween(Integer value1, Integer value2) {
addCriterion("material_num between", value1, value2, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotBetween(Integer value1, Integer value2) {
addCriterion("material_num not between", value1, value2, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumIsNull() {
addCriterion("material_hot_num is null");
return (Criteria) this;
}
public Criteria andMaterialHotNumIsNotNull() {
addCriterion("material_hot_num is not null");
return (Criteria) this;
}
public Criteria andMaterialHotNumEqualTo(Integer value) {
addCriterion("material_hot_num =", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotEqualTo(Integer value) {
addCriterion("material_hot_num <>", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumGreaterThan(Integer value) {
addCriterion("material_hot_num >", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumGreaterThanOrEqualTo(Integer value) {
addCriterion("material_hot_num >=", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumLessThan(Integer value) {
addCriterion("material_hot_num <", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumLessThanOrEqualTo(Integer value) {
addCriterion("material_hot_num <=", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumIn(List<Integer> values) {
addCriterion("material_hot_num in", values, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotIn(List<Integer> values) {
addCriterion("material_hot_num not in", values, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumBetween(Integer value1, Integer value2) {
addCriterion("material_hot_num between", value1, value2, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotBetween(Integer value1, Integer value2) {
addCriterion("material_hot_num not between", value1, value2, "materialHotNum");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | UTF-8 | Java | 26,784 | java | AdvertorialAuthorRecommendExample.java | Java | []
| null | []
| package cn.threefishes.cloudrepository.entity;
import java.util.ArrayList;
import java.util.List;
public class AdvertorialAuthorRecommendExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public AdvertorialAuthorRecommendExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andRecommendIdIsNull() {
addCriterion("recommend_id is null");
return (Criteria) this;
}
public Criteria andRecommendIdIsNotNull() {
addCriterion("recommend_id is not null");
return (Criteria) this;
}
public Criteria andRecommendIdEqualTo(Integer value) {
addCriterion("recommend_id =", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotEqualTo(Integer value) {
addCriterion("recommend_id <>", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdGreaterThan(Integer value) {
addCriterion("recommend_id >", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdGreaterThanOrEqualTo(Integer value) {
addCriterion("recommend_id >=", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdLessThan(Integer value) {
addCriterion("recommend_id <", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdLessThanOrEqualTo(Integer value) {
addCriterion("recommend_id <=", value, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdIn(List<Integer> values) {
addCriterion("recommend_id in", values, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotIn(List<Integer> values) {
addCriterion("recommend_id not in", values, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdBetween(Integer value1, Integer value2) {
addCriterion("recommend_id between", value1, value2, "recommendId");
return (Criteria) this;
}
public Criteria andRecommendIdNotBetween(Integer value1, Integer value2) {
addCriterion("recommend_id not between", value1, value2, "recommendId");
return (Criteria) this;
}
public Criteria andMemberIdIsNull() {
addCriterion("member_id is null");
return (Criteria) this;
}
public Criteria andMemberIdIsNotNull() {
addCriterion("member_id is not null");
return (Criteria) this;
}
public Criteria andMemberIdEqualTo(Integer value) {
addCriterion("member_id =", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotEqualTo(Integer value) {
addCriterion("member_id <>", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdGreaterThan(Integer value) {
addCriterion("member_id >", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdGreaterThanOrEqualTo(Integer value) {
addCriterion("member_id >=", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdLessThan(Integer value) {
addCriterion("member_id <", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdLessThanOrEqualTo(Integer value) {
addCriterion("member_id <=", value, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdIn(List<Integer> values) {
addCriterion("member_id in", values, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotIn(List<Integer> values) {
addCriterion("member_id not in", values, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdBetween(Integer value1, Integer value2) {
addCriterion("member_id between", value1, value2, "memberId");
return (Criteria) this;
}
public Criteria andMemberIdNotBetween(Integer value1, Integer value2) {
addCriterion("member_id not between", value1, value2, "memberId");
return (Criteria) this;
}
public Criteria andShareNumIsNull() {
addCriterion("share_num is null");
return (Criteria) this;
}
public Criteria andShareNumIsNotNull() {
addCriterion("share_num is not null");
return (Criteria) this;
}
public Criteria andShareNumEqualTo(Integer value) {
addCriterion("share_num =", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotEqualTo(Integer value) {
addCriterion("share_num <>", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumGreaterThan(Integer value) {
addCriterion("share_num >", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumGreaterThanOrEqualTo(Integer value) {
addCriterion("share_num >=", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumLessThan(Integer value) {
addCriterion("share_num <", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumLessThanOrEqualTo(Integer value) {
addCriterion("share_num <=", value, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumIn(List<Integer> values) {
addCriterion("share_num in", values, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotIn(List<Integer> values) {
addCriterion("share_num not in", values, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumBetween(Integer value1, Integer value2) {
addCriterion("share_num between", value1, value2, "shareNum");
return (Criteria) this;
}
public Criteria andShareNumNotBetween(Integer value1, Integer value2) {
addCriterion("share_num not between", value1, value2, "shareNum");
return (Criteria) this;
}
public Criteria andCommentNumIsNull() {
addCriterion("comment_num is null");
return (Criteria) this;
}
public Criteria andCommentNumIsNotNull() {
addCriterion("comment_num is not null");
return (Criteria) this;
}
public Criteria andCommentNumEqualTo(Integer value) {
addCriterion("comment_num =", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotEqualTo(Integer value) {
addCriterion("comment_num <>", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumGreaterThan(Integer value) {
addCriterion("comment_num >", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumGreaterThanOrEqualTo(Integer value) {
addCriterion("comment_num >=", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumLessThan(Integer value) {
addCriterion("comment_num <", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumLessThanOrEqualTo(Integer value) {
addCriterion("comment_num <=", value, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumIn(List<Integer> values) {
addCriterion("comment_num in", values, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotIn(List<Integer> values) {
addCriterion("comment_num not in", values, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumBetween(Integer value1, Integer value2) {
addCriterion("comment_num between", value1, value2, "commentNum");
return (Criteria) this;
}
public Criteria andCommentNumNotBetween(Integer value1, Integer value2) {
addCriterion("comment_num not between", value1, value2, "commentNum");
return (Criteria) this;
}
public Criteria andLikeNumIsNull() {
addCriterion("like_num is null");
return (Criteria) this;
}
public Criteria andLikeNumIsNotNull() {
addCriterion("like_num is not null");
return (Criteria) this;
}
public Criteria andLikeNumEqualTo(Integer value) {
addCriterion("like_num =", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotEqualTo(Integer value) {
addCriterion("like_num <>", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumGreaterThan(Integer value) {
addCriterion("like_num >", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumGreaterThanOrEqualTo(Integer value) {
addCriterion("like_num >=", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumLessThan(Integer value) {
addCriterion("like_num <", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumLessThanOrEqualTo(Integer value) {
addCriterion("like_num <=", value, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumIn(List<Integer> values) {
addCriterion("like_num in", values, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotIn(List<Integer> values) {
addCriterion("like_num not in", values, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumBetween(Integer value1, Integer value2) {
addCriterion("like_num between", value1, value2, "likeNum");
return (Criteria) this;
}
public Criteria andLikeNumNotBetween(Integer value1, Integer value2) {
addCriterion("like_num not between", value1, value2, "likeNum");
return (Criteria) this;
}
public Criteria andFollowNumIsNull() {
addCriterion("follow_num is null");
return (Criteria) this;
}
public Criteria andFollowNumIsNotNull() {
addCriterion("follow_num is not null");
return (Criteria) this;
}
public Criteria andFollowNumEqualTo(Integer value) {
addCriterion("follow_num =", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotEqualTo(Integer value) {
addCriterion("follow_num <>", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumGreaterThan(Integer value) {
addCriterion("follow_num >", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumGreaterThanOrEqualTo(Integer value) {
addCriterion("follow_num >=", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumLessThan(Integer value) {
addCriterion("follow_num <", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumLessThanOrEqualTo(Integer value) {
addCriterion("follow_num <=", value, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumIn(List<Integer> values) {
addCriterion("follow_num in", values, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotIn(List<Integer> values) {
addCriterion("follow_num not in", values, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumBetween(Integer value1, Integer value2) {
addCriterion("follow_num between", value1, value2, "followNum");
return (Criteria) this;
}
public Criteria andFollowNumNotBetween(Integer value1, Integer value2) {
addCriterion("follow_num not between", value1, value2, "followNum");
return (Criteria) this;
}
public Criteria andPageViewIsNull() {
addCriterion("page_view is null");
return (Criteria) this;
}
public Criteria andPageViewIsNotNull() {
addCriterion("page_view is not null");
return (Criteria) this;
}
public Criteria andPageViewEqualTo(Integer value) {
addCriterion("page_view =", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotEqualTo(Integer value) {
addCriterion("page_view <>", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewGreaterThan(Integer value) {
addCriterion("page_view >", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewGreaterThanOrEqualTo(Integer value) {
addCriterion("page_view >=", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewLessThan(Integer value) {
addCriterion("page_view <", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewLessThanOrEqualTo(Integer value) {
addCriterion("page_view <=", value, "pageView");
return (Criteria) this;
}
public Criteria andPageViewIn(List<Integer> values) {
addCriterion("page_view in", values, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotIn(List<Integer> values) {
addCriterion("page_view not in", values, "pageView");
return (Criteria) this;
}
public Criteria andPageViewBetween(Integer value1, Integer value2) {
addCriterion("page_view between", value1, value2, "pageView");
return (Criteria) this;
}
public Criteria andPageViewNotBetween(Integer value1, Integer value2) {
addCriterion("page_view not between", value1, value2, "pageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIsNull() {
addCriterion("enter_detail_page_view is null");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIsNotNull() {
addCriterion("enter_detail_page_view is not null");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewEqualTo(Integer value) {
addCriterion("enter_detail_page_view =", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotEqualTo(Integer value) {
addCriterion("enter_detail_page_view <>", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewGreaterThan(Integer value) {
addCriterion("enter_detail_page_view >", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewGreaterThanOrEqualTo(Integer value) {
addCriterion("enter_detail_page_view >=", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewLessThan(Integer value) {
addCriterion("enter_detail_page_view <", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewLessThanOrEqualTo(Integer value) {
addCriterion("enter_detail_page_view <=", value, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewIn(List<Integer> values) {
addCriterion("enter_detail_page_view in", values, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotIn(List<Integer> values) {
addCriterion("enter_detail_page_view not in", values, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewBetween(Integer value1, Integer value2) {
addCriterion("enter_detail_page_view between", value1, value2, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andEnterDetailPageViewNotBetween(Integer value1, Integer value2) {
addCriterion("enter_detail_page_view not between", value1, value2, "enterDetailPageView");
return (Criteria) this;
}
public Criteria andMaterialNumIsNull() {
addCriterion("material_num is null");
return (Criteria) this;
}
public Criteria andMaterialNumIsNotNull() {
addCriterion("material_num is not null");
return (Criteria) this;
}
public Criteria andMaterialNumEqualTo(Integer value) {
addCriterion("material_num =", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotEqualTo(Integer value) {
addCriterion("material_num <>", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumGreaterThan(Integer value) {
addCriterion("material_num >", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumGreaterThanOrEqualTo(Integer value) {
addCriterion("material_num >=", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumLessThan(Integer value) {
addCriterion("material_num <", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumLessThanOrEqualTo(Integer value) {
addCriterion("material_num <=", value, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumIn(List<Integer> values) {
addCriterion("material_num in", values, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotIn(List<Integer> values) {
addCriterion("material_num not in", values, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumBetween(Integer value1, Integer value2) {
addCriterion("material_num between", value1, value2, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialNumNotBetween(Integer value1, Integer value2) {
addCriterion("material_num not between", value1, value2, "materialNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumIsNull() {
addCriterion("material_hot_num is null");
return (Criteria) this;
}
public Criteria andMaterialHotNumIsNotNull() {
addCriterion("material_hot_num is not null");
return (Criteria) this;
}
public Criteria andMaterialHotNumEqualTo(Integer value) {
addCriterion("material_hot_num =", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotEqualTo(Integer value) {
addCriterion("material_hot_num <>", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumGreaterThan(Integer value) {
addCriterion("material_hot_num >", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumGreaterThanOrEqualTo(Integer value) {
addCriterion("material_hot_num >=", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumLessThan(Integer value) {
addCriterion("material_hot_num <", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumLessThanOrEqualTo(Integer value) {
addCriterion("material_hot_num <=", value, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumIn(List<Integer> values) {
addCriterion("material_hot_num in", values, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotIn(List<Integer> values) {
addCriterion("material_hot_num not in", values, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumBetween(Integer value1, Integer value2) {
addCriterion("material_hot_num between", value1, value2, "materialHotNum");
return (Criteria) this;
}
public Criteria andMaterialHotNumNotBetween(Integer value1, Integer value2) {
addCriterion("material_hot_num not between", value1, value2, "materialHotNum");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | 26,784 | 0.59375 | 0.590464 | 799 | 32.523155 | 27.387392 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.718398 | false | false | 8 |
d09659ba9ef79b3ffa3bc9fdcb3f9b946c07150a | 25,795,573,630,756 | 1d790852a1b23b0adf40ca770ffbe0220216e067 | /src/main/java/com/terljuk/io/filemanager/FileManager.java | 98ca4cb1da76cc5570f6f5e06c66afbe73acdde3 | []
| no_license | viktorterljuk/data-structure | https://github.com/viktorterljuk/data-structure | e569475641cd7313f12bab622547ded2fa7f08f4 | e885ac984c6a17c71fba672916a1130d2cb02718 | refs/heads/master | 2018-09-11T22:50:33.207000 | 2018-06-24T07:09:03 | 2018-06-24T07:09:03 | 128,687,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.terljuk.io.filemanager;
import java.io.*;
public class FileManager {
public static int calculateFiles(String path) {
int filesCount = 0;
File currentDir = new File(path);
File[] files = currentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
filesCount++;
} else {
String absolutePath = file.getAbsolutePath();
filesCount += calculateFiles(absolutePath);
}
}
}
return filesCount;
}
public static int calculateDirs(String path) {
int dirsCount = 0;
File currentDir = new File(path);
File[] files = currentDir.listFiles();
if(files != null) {
for (File file : files) {
if (file.isDirectory()) {
dirsCount++;
String absolutePath = file.getAbsolutePath();
dirsCount += calculateDirs(absolutePath);
}
}
}
return dirsCount;
}
public void copy(String from, String to) throws IOException {
File pathTo = new File(to);
File pathFrom = new File(from);
if (!pathTo.exists()) {
pathTo.mkdirs();
}
if (pathFrom.isDirectory()) {
String[] files = pathFrom.list();
for (String file : files) {
copy(new File(from, file).getPath(), new File(to, file).getPath());
}
} else {
FileInputStream inputStream = new FileInputStream(from);
FileOutputStream outputStream = new FileOutputStream(to);
try {
byte[] buffer = new byte[1024];
int count;
while ((count = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
} finally {
inputStream.close();
outputStream.close();
}
}
}
public void move(String from, String to) throws IOException {
copy(from, to);
File fileFrom = new File(from);
if (fileFrom.isDirectory()) {
delete(fileFrom);
} else {
fileFrom.delete();
}
}
private void delete(File directory) {
for (File path : directory.listFiles()) {
if (path.isDirectory()) {
delete(directory);
}
path.delete();
}
directory.delete();
}
public static void main(String[] args) throws IOException {
FileManager fileManager = new FileManager();
// System.out.println("Dirs count - " + fileManager.calculateDirs("C:\\Windows"));
System.out.println("Files count - " + fileManager.calculateFiles("C:\\Windows"));
/*fileManager.copy("D:\\testDir\\to.txt", "D:\\testDir\\first\\");
fileManager.move("D:\\testDir\\up.txt", "D:\\first\\");*/
}
}
| UTF-8 | Java | 3,053 | java | FileManager.java | Java | []
| null | []
| package com.terljuk.io.filemanager;
import java.io.*;
public class FileManager {
public static int calculateFiles(String path) {
int filesCount = 0;
File currentDir = new File(path);
File[] files = currentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
filesCount++;
} else {
String absolutePath = file.getAbsolutePath();
filesCount += calculateFiles(absolutePath);
}
}
}
return filesCount;
}
public static int calculateDirs(String path) {
int dirsCount = 0;
File currentDir = new File(path);
File[] files = currentDir.listFiles();
if(files != null) {
for (File file : files) {
if (file.isDirectory()) {
dirsCount++;
String absolutePath = file.getAbsolutePath();
dirsCount += calculateDirs(absolutePath);
}
}
}
return dirsCount;
}
public void copy(String from, String to) throws IOException {
File pathTo = new File(to);
File pathFrom = new File(from);
if (!pathTo.exists()) {
pathTo.mkdirs();
}
if (pathFrom.isDirectory()) {
String[] files = pathFrom.list();
for (String file : files) {
copy(new File(from, file).getPath(), new File(to, file).getPath());
}
} else {
FileInputStream inputStream = new FileInputStream(from);
FileOutputStream outputStream = new FileOutputStream(to);
try {
byte[] buffer = new byte[1024];
int count;
while ((count = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
} finally {
inputStream.close();
outputStream.close();
}
}
}
public void move(String from, String to) throws IOException {
copy(from, to);
File fileFrom = new File(from);
if (fileFrom.isDirectory()) {
delete(fileFrom);
} else {
fileFrom.delete();
}
}
private void delete(File directory) {
for (File path : directory.listFiles()) {
if (path.isDirectory()) {
delete(directory);
}
path.delete();
}
directory.delete();
}
public static void main(String[] args) throws IOException {
FileManager fileManager = new FileManager();
// System.out.println("Dirs count - " + fileManager.calculateDirs("C:\\Windows"));
System.out.println("Files count - " + fileManager.calculateFiles("C:\\Windows"));
/*fileManager.copy("D:\\testDir\\to.txt", "D:\\testDir\\first\\");
fileManager.move("D:\\testDir\\up.txt", "D:\\first\\");*/
}
}
| 3,053 | 0.504094 | 0.501474 | 97 | 30.453608 | 22.653837 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515464 | false | false | 8 |
16f386b615f6969bb6d9391d6cff83481dad18a3 | 38,113,539,786,557 | 21eef0202ea658b7a80f910d9da55adc1ce16e25 | /app/src/main/java/com/kyle/popularmovies/views/MovieAdapter.java | 5909e1523d348473dc9ccbf28fadb71599c0e9d7 | []
| no_license | kyle-erin/PopularMovies | https://github.com/kyle-erin/PopularMovies | 9cfae402815bbfee214430fa1d52d59eefb105ba | 32a3943d1ed9f7a665d193c8b5728a107a0c6ab4 | refs/heads/master | 2021-01-01T19:15:53.549000 | 2016-02-11T20:52:23 | 2016-02-11T20:52:23 | 39,164,779 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kyle.popularmovies.views;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.kyle.popularmovies.activities.MovieInfoActivity;
import com.kyle.popularmovies.data.Movie;
import com.squareup.picasso.Picasso;
/**
* The adapter to a GridView, that displays all the movies fetched.
*/
public class MovieAdapter extends BaseAdapter
{
/**
* The url to fetch a smaller image to display in the grid.
*/
public static final String TMDB_IMG_URL = "http://image.tmdb.org/t/p/w185";
/**
* Width of the poster ImageView.
*/
private static final int POSTER_WIDTH = 350;
/**
* Height of the poster ImageView.
*/
private static final int POSTER_HEIGHT = 500;
/**
* Context of the activity that creates this adapter.
*/
private Context mContext;
/**
* Movie data
*/
private Movie[] mData;
/**
* @param context A context of an activity that created this.
* @param data The array of movies to display.
*/
public MovieAdapter( Context context, Movie[] data )
{
mContext = context;
mData = data;
}
/**
* @return How many movies do you have?
*/
@Override
public int getCount()
{
return mData.length;
}
/**
* No reason to return anything here.
*/
@Override
public Object getItem( int position )
{
return null;
}
/**
* @param position Position of the item.
* @return What is the id of the item in this position?
*/
@Override
public long getItemId( int position )
{
return mData[ position ].id;
}
/**
* @param position The position of the item in the grid.
* @param convertView The current view.
* @param parent The parent view.
* @return A view representing a movie, that is clickable.
*/
@Override
public View getView( int position, View convertView, ViewGroup parent )
{
ImageView imageView;
if ( convertView == null )
{
imageView = new ImageView( mContext );
imageView.setLayoutParams( new GridView.LayoutParams( POSTER_WIDTH, POSTER_HEIGHT ) );
imageView.setScaleType( ImageView.ScaleType.FIT_CENTER );
imageView.setPadding( 2, 2, 2, 2 );
}
else
{
imageView = (ImageView) convertView;
}
final Movie item = mData[ position ];
if ( item != null )
{
// Load poster
Picasso.with( mContext ).load( TMDB_IMG_URL + item.poster_path ).into( imageView );
// Set onclick to bring the user to a details page
imageView.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick( View v )
{
MovieInfoActivity.mSelected = item;
mContext.startActivity( new Intent( mContext, MovieInfoActivity.class ) );
}
} );
}
return imageView;
}
}
| UTF-8 | Java | 2,966 | java | MovieAdapter.java | Java | []
| null | []
| package com.kyle.popularmovies.views;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.kyle.popularmovies.activities.MovieInfoActivity;
import com.kyle.popularmovies.data.Movie;
import com.squareup.picasso.Picasso;
/**
* The adapter to a GridView, that displays all the movies fetched.
*/
public class MovieAdapter extends BaseAdapter
{
/**
* The url to fetch a smaller image to display in the grid.
*/
public static final String TMDB_IMG_URL = "http://image.tmdb.org/t/p/w185";
/**
* Width of the poster ImageView.
*/
private static final int POSTER_WIDTH = 350;
/**
* Height of the poster ImageView.
*/
private static final int POSTER_HEIGHT = 500;
/**
* Context of the activity that creates this adapter.
*/
private Context mContext;
/**
* Movie data
*/
private Movie[] mData;
/**
* @param context A context of an activity that created this.
* @param data The array of movies to display.
*/
public MovieAdapter( Context context, Movie[] data )
{
mContext = context;
mData = data;
}
/**
* @return How many movies do you have?
*/
@Override
public int getCount()
{
return mData.length;
}
/**
* No reason to return anything here.
*/
@Override
public Object getItem( int position )
{
return null;
}
/**
* @param position Position of the item.
* @return What is the id of the item in this position?
*/
@Override
public long getItemId( int position )
{
return mData[ position ].id;
}
/**
* @param position The position of the item in the grid.
* @param convertView The current view.
* @param parent The parent view.
* @return A view representing a movie, that is clickable.
*/
@Override
public View getView( int position, View convertView, ViewGroup parent )
{
ImageView imageView;
if ( convertView == null )
{
imageView = new ImageView( mContext );
imageView.setLayoutParams( new GridView.LayoutParams( POSTER_WIDTH, POSTER_HEIGHT ) );
imageView.setScaleType( ImageView.ScaleType.FIT_CENTER );
imageView.setPadding( 2, 2, 2, 2 );
}
else
{
imageView = (ImageView) convertView;
}
final Movie item = mData[ position ];
if ( item != null )
{
// Load poster
Picasso.with( mContext ).load( TMDB_IMG_URL + item.poster_path ).into( imageView );
// Set onclick to bring the user to a details page
imageView.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick( View v )
{
MovieInfoActivity.mSelected = item;
mContext.startActivity( new Intent( mContext, MovieInfoActivity.class ) );
}
} );
}
return imageView;
}
}
| 2,966 | 0.652057 | 0.647674 | 124 | 22.919355 | 23.115976 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346774 | false | false | 8 |
c5256693c22ef0721a6a78e87585fffd1c330b41 | 19,791,209,361,650 | 62b9cab96eaadc228427110874c20cbe6b493ab7 | /app/src/main/java/com/demo/bestshopping/RegistroActivity.java | f5df53088220b10df06c6609e38003b9b8126239 | []
| no_license | juandaabril/BestShopping | https://github.com/juandaabril/BestShopping | 3ed35fd40311ebc0567f9d394887b433ec0a6bf4 | cd7739c78c950f41336eafd0659369ebdfb33cb7 | refs/heads/master | 2016-09-06T09:47:53.263000 | 2015-04-11T18:43:22 | 2015-04-11T18:43:22 | 33,759,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.bestshopping;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class RegistroActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
}
public void registrarse(View view){
EditText etNombre =(EditText)findViewById(R.id.registroNombre);
EditText etEmail =(EditText)findViewById(R.id.registroEmail);
EditText etPassword =(EditText)findViewById(R.id.registroPassword);
boolean isValid = true;
if( etNombre.getText().toString().length() == 0 ){
etNombre.setError( "El nombre es requerido" );
isValid = false;
}
if( etEmail.getText().toString().length() == 0 ){
etEmail.setError("El email es requerida" );
isValid = false;
}
if( etPassword.getText().toString().length() == 0 ) {
etPassword.setError("El email es requerida");
isValid = false;
}
if(!isValid) return;
Intent call = new Intent(this, HomeActivity.class);
call.putExtra("email", etEmail.getText().toString());
startActivity(call);
}
}
| UTF-8 | Java | 1,438 | java | RegistroActivity.java | Java | []
| null | []
| package com.demo.bestshopping;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class RegistroActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
}
public void registrarse(View view){
EditText etNombre =(EditText)findViewById(R.id.registroNombre);
EditText etEmail =(EditText)findViewById(R.id.registroEmail);
EditText etPassword =(EditText)findViewById(R.id.registroPassword);
boolean isValid = true;
if( etNombre.getText().toString().length() == 0 ){
etNombre.setError( "El nombre es requerido" );
isValid = false;
}
if( etEmail.getText().toString().length() == 0 ){
etEmail.setError("El email es requerida" );
isValid = false;
}
if( etPassword.getText().toString().length() == 0 ) {
etPassword.setError("El email es requerida");
isValid = false;
}
if(!isValid) return;
Intent call = new Intent(this, HomeActivity.class);
call.putExtra("email", etEmail.getText().toString());
startActivity(call);
}
}
| 1,438 | 0.651599 | 0.648818 | 46 | 30.26087 | 23.755489 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 8 |
4a89c31c64da840120fd0e0f85c88cd3b193424d | 15,358,803,114,060 | 126d657d182c8e5e85ac21f95224e2decb9b13ed | /Java1/Circle/src/com/hsbc/service/circle.java | 5743ae0584566f2536493d1860deeceba4cefdbf | []
| no_license | abhishekj720/HSBCLearn | https://github.com/abhishekj720/HSBCLearn | d78f230852ae7436d8260fb5eacb78bc1d6df8ec | a61084755d8d81694c7241f115fcbf62294cf349 | refs/heads/master | 2020-06-22T17:27:40.553000 | 2019-08-01T12:59:07 | 2019-08-01T12:59:07 | 197,753,451 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hsbc.service;
import com.hsbc.util.HsbcUtil;
public class circle {
private int radius;
public int getRadius() {
return radius;
}
public void setRadius(int radius) throws Exception {
HsbcUtil.validateDataGreaterThanZero(radius,"radius");
this.radius = radius;
}
public double calcArea(int radius)
{
return Math.PI*radius*radius;
}
public double calcPerimeter(int radius)
{
return HsbcUtil.TWO *Math.PI*radius;
}
}
| UTF-8 | Java | 456 | java | circle.java | Java | []
| null | []
| package com.hsbc.service;
import com.hsbc.util.HsbcUtil;
public class circle {
private int radius;
public int getRadius() {
return radius;
}
public void setRadius(int radius) throws Exception {
HsbcUtil.validateDataGreaterThanZero(radius,"radius");
this.radius = radius;
}
public double calcArea(int radius)
{
return Math.PI*radius*radius;
}
public double calcPerimeter(int radius)
{
return HsbcUtil.TWO *Math.PI*radius;
}
}
| 456 | 0.725877 | 0.725877 | 24 | 18 | 17.507141 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 8 |
e356bbdd730721d0f09bb199506918badb6b1020 | 32,255,204,453,680 | 5e8adbf4ebd14d8d0fde8b9ae62efa37f9144085 | /src/main/java/util/EncDcrpt.java | 5da9e5cbfa758d6115b65bd83e427c79e4180273 | []
| no_license | harshrajm/RSA-Entire-Flow | https://github.com/harshrajm/RSA-Entire-Flow | 6275859379b6d251bb206f33cb1008a5c249b3a0 | 8bcd80e4ae1695053f575e6d45cd272c343a4b74 | refs/heads/master | 2021-07-04T23:31:00.524000 | 2017-09-20T14:49:47 | 2017-09-20T14:49:47 | 104,228,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
/**
* Created by Administrator on 18-09-2017.
*/
public class EncDcrpt {
public String encrypt(PublicKey publicKey, String textToEnc) throws InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64String(cipher.doFinal(textToEnc.getBytes("UTF-8")));
}
public String decrypt(PrivateKey privateKey, String strToDecode) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.decodeBase64(strToDecode)), "UTF-8");
}
public String sign(PrivateKey privateKey, String data ){
Signature sig = null;
try {
sig = Signature.getInstance("SHA1WithRSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sig.initSign(privateKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
sig.update(data.getBytes("UTF8"));
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] signatureBytes = new byte[0];
try {
signatureBytes = sig.sign();
} catch (SignatureException e) {
e.printStackTrace();
}
return new BASE64Encoder().encode(signatureBytes);
}
}
| UTF-8 | Java | 2,115 | java | EncDcrpt.java | Java | []
| null | []
| package util;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
/**
* Created by Administrator on 18-09-2017.
*/
public class EncDcrpt {
public String encrypt(PublicKey publicKey, String textToEnc) throws InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64String(cipher.doFinal(textToEnc.getBytes("UTF-8")));
}
public String decrypt(PrivateKey privateKey, String strToDecode) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.decodeBase64(strToDecode)), "UTF-8");
}
public String sign(PrivateKey privateKey, String data ){
Signature sig = null;
try {
sig = Signature.getInstance("SHA1WithRSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sig.initSign(privateKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
sig.update(data.getBytes("UTF8"));
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] signatureBytes = new byte[0];
try {
signatureBytes = sig.sign();
} catch (SignatureException e) {
e.printStackTrace();
}
return new BASE64Encoder().encode(signatureBytes);
}
}
| 2,115 | 0.681324 | 0.668558 | 60 | 34.25 | 41.234138 | 225 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716667 | false | false | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.