text
stringlengths
10
2.72M
package kr.co.people_gram.app; import android.app.Activity; import android.content.Context; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.WindowManager; import java.text.DecimalFormat; import java.util.Calendar; /** * Created by 광희 on 2015-09-09. */ public class Utilities { private static String TAG = "people_gram"; public static int getPixelToDp(Context context, int pixel) { float dp = 0; try { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); dp = pixel / (metrics.densityDpi / 160f); } catch (Exception e) { } return (int) dp; } public static int getDpToPixel(Context context, int DP) { float px = 0; try { px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics()); } catch (Exception e) { } return (int) px; } public static int getDpToPixel(Context context, float DP) { float px = 0; try { px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics()); } catch (Exception e) { } return (int) px; } /** * 단말기 density 구함 * @param con * 사용법 : if(getDensity(context) == 2f && (float으로 형변환해서 사용 해야함.) */ public static float getDensity(Context con) { float density = 0.0f; density = con.getResources().getDisplayMetrics().density; Log.d(TAG, "density = " + density); return density; } /** * px을 dp로 변환 * @param con * @param px * @return dp */ public static int getPxToDp(Context con, int px) { float density = 0.0f; density = con.getResources().getDisplayMetrics().density; Log.d(TAG, "density = " + density); return (int)(px / density); } /** * dp를 px로 변환 * @param con * @param dp * @return px */ public static int getDpToPix(Context con, double dp) { float density = 0.0f; density = con.getResources().getDisplayMetrics().density; Log.d(TAG, "density = " + density); return (int)(dp * density + 0.5); } /** * 단말기 가로 해상도 구하기 * @param activity * @return width */ public static int getScreenWidth(Activity activity) { int width = 0; width = activity.getWindowManager().getDefaultDisplay().getWidth(); Log.i(TAG, "Screen width = " + width); return width; } /** * 단말기 세로 해상도 구하기 * @param activity * @return hight */ public static int getScreenHeight(Activity activity) { int height = 0; height = activity.getWindowManager().getDefaultDisplay().getHeight(); Log.i(TAG, "Screen height = " + height); return height; } /** * 단말기 가로 해상도 구하기 * @param context */ public static int getScreenWidth(Context context) { Display dis = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int width = dis.getWidth(); Log.i(TAG, "Screen Width = " + width); return width; } /** * 단말기 세로 해상도 구하기 * @param context */ public static int getScreenHeight(Context context) { Display dis = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int height = dis.getHeight(); Log.i(TAG, "Screen height = " + height); return height; } /** * 현재 네트워크 상태를 확인할 수 있는 메소드 * @return 네트워크 상태 * 1 : wifi * 2 : mibile network * 3 : 네트워크 사용불가 */ public static int getNetworkType(Context context) { int NETWORK_WIFI = 1; int NETWORK_MOBILE = 2; int NETWORK_NOT_AVAILABLE = 3; int NETWORK_CHECK = 0; try { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo.State wifi = conMan.getNetworkInfo(1).getState(); if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) NETWORK_CHECK = NETWORK_WIFI; NetworkInfo.State mobile = conMan.getNetworkInfo(0).getState(); if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) NETWORK_CHECK = NETWORK_MOBILE; } catch (NullPointerException e) { NETWORK_CHECK = NETWORK_NOT_AVAILABLE; } return NETWORK_CHECK; } public static String comma(int num) { DecimalFormat df = new DecimalFormat("#,##0"); String won = String.valueOf(df.format(num)); return won; } public static String age_return(String birthday) { Calendar cal= Calendar.getInstance(); int year = Integer.parseInt(birthday.substring(0, 4)); int month = Integer.parseInt(birthday.substring(4, 6)); int day = Integer.parseInt(birthday.substring(6, 8)); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month-1); cal.set(Calendar.DATE, day); Calendar now = Calendar.getInstance(); int age = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR); if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH))) { age--; } return String.valueOf(age) + "세"; } public static double people_match_int(float my_speed, float you_speed, float my_control, float you_control) { int type_score = 100; if(my_speed * you_speed * my_control * you_control < 0) { type_score = 90; } else { if(my_speed * you_speed < 0 && my_control * you_control < 0) { type_score = 80; } else { type_score = 100; } } double score_temp = Math.pow((my_speed - you_speed),2) + Math.pow((my_control - you_control),2); double score = 4 * Math.sqrt(2) * Math.sqrt(score_temp); double total = type_score - score; return total; } private double people_match_temp(float my_speed, float you_speed, float my_control, float you_control) { double temp = Math.pow((my_speed - you_speed),2) + Math.pow((my_control - you_control),2); return temp; } private int people_match_typescore(float my_speed, float you_speed, float my_control, float you_control) { int type_score = 100; if(my_speed * you_speed * my_control * you_control < 0) { type_score = 90; } else { if(my_speed * you_speed < 0 && my_control * you_control < 0) { type_score = 80; } else { type_score = 100; } } return type_score; } public static int getBitmapOfWidth(String fileName) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(fileName, options); return options.outWidth; } catch(Exception e) { return 0; } } public static int getBitmapOfHeight(String fileName) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(fileName, options); return options.outHeight; } catch(Exception e) { return 0; } } public static String peopleContectView(Context context, String gubun, double total_num) { String text = ""; switch (gubun) { case "P": if(total_num <= 10) { text = context.getString(R.string.p_1).toString(); } else if(total_num > 10 && total_num <= 20) { text = context.getString(R.string.p_2).toString(); } else if(total_num > 20 && total_num <= 40) { text = context.getString(R.string.p_3).toString(); } else if(total_num > 40 && total_num <= 60) { text = context.getString(R.string.p_4).toString(); } else if(total_num > 60 && total_num <= 75) { text = context.getString(R.string.p_5).toString(); } else if(total_num > 75 && total_num <= 89) { text = context.getString(R.string.p_6).toString(); } else { text = context.getString(R.string.p_7).toString(); } break; case "F": if(total_num <= 10) { text = context.getString(R.string.f_1).toString(); } else if(total_num > 10 && total_num <= 20) { text = context.getString(R.string.f_2).toString(); } else if(total_num > 20 && total_num <= 40) { text = context.getString(R.string.f_3).toString(); } else if(total_num > 40 && total_num <= 60) { text = context.getString(R.string.f_4).toString(); } else if(total_num > 60 && total_num <= 75) { text = context.getString(R.string.f_5).toString(); } else if(total_num > 75 && total_num <= 89) { text = context.getString(R.string.f_6).toString(); } else { text = context.getString(R.string.f_7).toString(); } break; case "L": if(total_num <= 10) { text = context.getString(R.string.l_1).toString(); } else if(total_num > 10 && total_num <= 20) { text = context.getString(R.string.l_2).toString(); } else if(total_num > 20 && total_num <= 40) { text = context.getString(R.string.l_3).toString(); } else if(total_num > 40 && total_num <= 60) { text = context.getString(R.string.l_4).toString(); } else if(total_num > 60 && total_num <= 75) { text = context.getString(R.string.l_5).toString(); } else if(total_num > 75 && total_num <= 89) { text = context.getString(R.string.l_6).toString(); } else { text = context.getString(R.string.l_7).toString(); } break; case "C": if(total_num <= 10) { text = context.getString(R.string.c_1).toString(); } else if(total_num > 10 && total_num <= 20) { text = context.getString(R.string.c_2).toString(); } else if(total_num > 20 && total_num <= 40) { text = context.getString(R.string.c_3).toString(); } else if(total_num > 40 && total_num <= 60) { text = context.getString(R.string.c_4).toString(); } else if(total_num > 60 && total_num <= 75) { text = context.getString(R.string.c_5).toString(); } else if(total_num > 75 && total_num <= 89) { text = context.getString(R.string.c_6).toString(); } else { text = context.getString(R.string.c_7).toString(); } break; case "S": if(total_num <= 10) { text = context.getString(R.string.s_1).toString(); } else if(total_num > 10 && total_num <= 20) { text = context.getString(R.string.s_2).toString(); } else if(total_num > 20 && total_num <= 40) { text = context.getString(R.string.s_3).toString(); } else if(total_num > 40 && total_num <= 60) { text = context.getString(R.string.s_4).toString(); } else if(total_num > 60 && total_num <= 75) { text = context.getString(R.string.s_5).toString(); } else if(total_num > 75 && total_num <= 89) { text = context.getString(R.string.s_6).toString(); } else { text = context.getString(R.string.s_7).toString(); } break; } return text; } }
package br.com.wasys.gfin.cheqfast.cliente.model; import br.com.wasys.library.model.Model; /** * Created by pascke on 23/06/17. */ public class DispositivoModel extends Model { public String token; public String pushToken; public UsuarioModel usuario; }
import java.io.File; public class DisplayFiles { public void display() { File file=new File("C:\\Users\\kchaitanya\\Desktop\\chaitanya"); String[] f=file.list(); for(String str :f) System.out.println(str); } }
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ahat; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffFieldsTest.class, DiffTest.class, DominatorsTest.class, HtmlEscaperTest.class, InstanceTest.class, NativeAllocationTest.class, ObjectHandlerTest.class, ObjectsHandlerTest.class, OverviewHandlerTest.class, PerformanceTest.class, ProguardMapTest.class, RootedHandlerTest.class, QueryTest.class, RiTest.class, SiteHandlerTest.class, SiteTest.class }) public class AhatTestSuite { public static void main(String[] args) { if (args.length == 0) { args = new String[]{"com.android.ahat.AhatTestSuite"}; } JUnitCore.main(args); } }
package junit.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cy.bean.user.Users; import com.cy.service.user.UsersService; import com.cy.utils.MD5; public class UsersServiceTest { private static UsersService usersService; @BeforeClass public static void beforeClass() { usersService = (UsersService) new ClassPathXmlApplicationContext("beans.xml").getBean("usersServiceBean"); } @Test public void save() { Users users = new Users("admin",MD5.MD5Encode("admin")); usersService.save(users); } @Test public void loginTest() { Users users = new Users("admin","admin"); Users user = usersService.login(users); System.out.println(user.getUsername()+user.getPassword()); } }
package com.jarhax.eerieentities.client.gui; import java.util.ArrayList; import java.util.List; import com.jarhax.eerieentities.EerieEntities; import com.jarhax.eerieentities.config.Config; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; public class GuiConfigEerieEntities extends GuiConfig { private static Configuration cfg = Config.cfg; public GuiConfigEerieEntities(GuiScreen parent) { super(parent, generateConfigList(), EerieEntities.MODID, false, false, GuiConfig.getAbridgedConfigPath(cfg.toString())); } public static List<IConfigElement> generateConfigList () { final ArrayList<IConfigElement> elements = new ArrayList<>(); for (final String name : cfg.getCategoryNames()) { elements.add(new ConfigElement(cfg.getCategory(name))); } return elements; } }
package com.git.cloud.iaas.hillstone.model; public class HillStoneOperation { public static final String GET_TOKEN = "getTokenHS"; public static final String GET_SERVICEBOOK = "getServiceBookHS"; public static final String GET_SERVICEBOOK_BY_NAME = "getServiceBookByNameHS"; public static final String CREATE_SERVICEBOOK = "createServiceBookHS"; public static final String CREATE_SERVICEBOOK_TCP = "createServiceBookTCPHS"; public static final String CREATE_SERVICEBOOK_UDP = "createServiceBookUDPHS"; public static final String CREATE_SERVICEBOOK_ICMP = "createServiceBookICMPHS"; public static final String CREATE_ADDRBOOK_RANGE = "createAddrBookRangeHS"; public static final String CREATE_DNAT = "createDnatHS"; public static final String DELETE_DNAT = "deleteDnatHS"; public static final String CREATE_SNAT = "createSnatHS"; public static final String DELETE_SNAT = "deleteSnatHS"; public static final String CREATE_POLICY = "createPolicyHS"; public static final String DELETE_POLICY = "deletePolicyHS"; }
package orm.integ.eao.model; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import orm.integ.dao.DataAccessObject; import orm.integ.utils.IntegError; import orm.integ.utils.MyLogger; public class EntityModelBuilder extends TableModelBuilder implements EntityConfig { private String tableKeyName; private String[] defaultListFields ; private String[] defaultDetailFields; private Set<String> detailExceptFields = new HashSet<>(); public EntityModelBuilder(Class<? extends Entity> entityClass, DataAccessObject dao) { super(entityClass, dao); tableKeyName = getTableKeyName(); setFieldColumn("id", table.keyColumn()); setFieldColumn("id", tableKeyName+"_id"); setFieldColumn("name", tableKeyName+"_name"); } private String getTableKeyName() { String tableKeyName = tableName; int pos = tableName.indexOf("_"); if (pos>=0&&pos<=3) { tableKeyName = tableName.substring(pos+1); } return tableKeyName; } @Override protected EntityModel createTableModel() { return new EntityModel(); } public EntityModel buildModel() { EntityModel model = (EntityModel) super.buildModel(); model.tableKeyName = tableKeyName; model.keyColumn = getField("id").getColumnName(); List<String> fieldNames = getAllFieldName(); model.listFields = defaultListFields; if (defaultListFields==null) { model.listFields = fieldNames.toArray(new String[0]); } model.detailFields = defaultDetailFields; if (defaultDetailFields==null) { model.detailFields = getExceptRestFields(detailExceptFields); } TableModels.putModel(model); return model; } private String[] getExceptRestFields(Collection<String> exceptFields) { List<String> fields = getAllFieldName(); List<String> excepts = new ArrayList<>(); String fieldName; for (String ef: exceptFields) { for (int i=0; i<fields.size(); i++) { fieldName = fields.get(i); if (fieldName.equalsIgnoreCase(ef)) { excepts.add(fieldName); break; } } } fields.removeAll(excepts); return fields.toArray(new String[0]); } @Override public void setListFields(String... fields) { this.defaultListFields = formatViewFields(fields); } @Override public void setDetailFields(String... fields) { this.defaultDetailFields = formatViewFields(fields); } // 格式化视图数据属性集,排除重复,固定顺序 private String[] formatViewFields(String[] fieldNames) { if (fieldNames==null||fieldNames.length==0) { return fieldNames; } LinkedHashSet<String> fieldSet = new LinkedHashSet<>(); List<String> allFields = this.getAllFieldName(); for (String field1: allFields) { for (String field2: fieldNames) { if (field1.equalsIgnoreCase(field2)) { fieldSet.add(field1); } } } if (!fieldSet.contains("id")) { fieldSet.add("id"); } return fieldSet.toArray(new String[0]); } FieldInfo getOrAddField(String fieldName) { FieldInfo field = fieldInfos.get(fieldName); if (field==null) { field = new FieldInfo(objectClass, fieldName); fieldInfos.put(fieldName, field); } return field; } @Override public void setFieldMapping(String fieldName, String foreignKeyField, String relFieldName) { FieldInfo fkField = getField(foreignKeyField); String className = objectClass.getSimpleName(); String fkFieldName = className+"."+foreignKeyField; if (fkField==null) { MyLogger.print("外键属性 "+fkFieldName+"不存在!"); return; } if (!fkField.isForeignKey()) { throw new IntegError(fkFieldName+"未设为外键!"); } FieldMapping fm = new FieldMapping(); fm.foreignKeyField = foreignKeyField; fm.masterField = relFieldName; FieldInfo field = this.getOrAddField(fieldName); field.mapping = fm; } @Override public void setNameMapping(String fieldName, String foreignKeyField) { setFieldMapping(fieldName, foreignKeyField, "name"); } @Override public void setDetailFieldExcept(String... fields) { detailExceptFields.clear(); for (String f: fields) { detailExceptFields.add(f); } } }
package com.miyatu.tianshixiaobai.activities.mine.BackstageManage; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.hjq.toast.ToastUtils; import com.miyatu.tianshixiaobai.MyApp; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.activities.BaseActivity; import com.miyatu.tianshixiaobai.activities.MainActivity; import com.miyatu.tianshixiaobai.activities.mine.Address.AddressActivity; import com.miyatu.tianshixiaobai.activities.mine.Address.SelectAddressActivity; import com.miyatu.tianshixiaobai.activities.mine.EditPersonalDataActivity; import com.miyatu.tianshixiaobai.adapter.AddXiaoBaiAdapter; import com.miyatu.tianshixiaobai.entity.AddXiaoBaiEntity; import com.miyatu.tianshixiaobai.entity.AddressEntity; import com.miyatu.tianshixiaobai.entity.BaseResultEntity; import com.miyatu.tianshixiaobai.http.api.AddressApi; import com.miyatu.tianshixiaobai.http.api.BaseInformationApi; import com.miyatu.tianshixiaobai.http.api.DemandApi; import com.miyatu.tianshixiaobai.http.api.MarketApi; import com.miyatu.tianshixiaobai.http.api.NewsApi; import com.miyatu.tianshixiaobai.http.api.ShopApi; import com.miyatu.tianshixiaobai.utils.BitmapUtil; import com.miyatu.tianshixiaobai.utils.FileUtils; import com.miyatu.tianshixiaobai.utils.ScreenUtils; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import static com.miyatu.tianshixiaobai.utils.CommonUtils.PHOTO_REQUEST_CUT; import static com.miyatu.tianshixiaobai.utils.CommonUtils.PHOTO_REQUEST_GALLERY; public class AddXiaoBaiActivity extends BaseActivity implements HttpOnNextListener { private ImageView ivPortrait; private EditText etName; private EditText etIntroduce; private TextView tvAdd; private RadioGroup rgSex; //性别选择radiogroup,添加check监听 private SwipeRefreshLayout refreshLayout; private PopupWindow popAddPhoto; private static final int ADD_PORTRAIT_PHOTO = 1; private static final int ADD_PORTRAIT_CAMERA = 2; private String strSex = "1"; //默认为男 private File filePortrait; private int changePosition; private AddXiaoBaiAdapter adapter; private RecyclerView recyclerView; private List<AddXiaoBaiEntity> addXiaoBaiEntityList; private HttpManager manager; private ShopApi shopApi; private Map<String, Object> params; private Map<String, RequestBody> bodyMap; private List<MultipartBody.Part> parts; private void initXiaoBaiListRequest() { params = new HashMap<>(); params.put("limit", limit); params.put("page", page); params.put("business_id", getUserBaseInfo().getBusiness_id()); manager = new HttpManager(this,(RxAppCompatActivity)this); shopApi = new ShopApi(ShopApi.XIAO_BAI_LIST); shopApi.setParams(params); manager.doHttpDeal(shopApi); } private void initAddXiaoBaiRequest() { bodyMap = new HashMap<>(); parts = new ArrayList<>(); manager = new HttpManager(this, (RxAppCompatActivity)this); } private void initDelXiaoBaiRequest(String xiaoBaiIDS) { params = new HashMap<>(); params.put("xiaobai_ids", xiaoBaiIDS); manager = new HttpManager(this,(RxAppCompatActivity)this); shopApi = new ShopApi(ShopApi.DEL_XIAO_BAI); shopApi.setParams(params); manager.doHttpDeal(shopApi); } public static void startActivity(Activity activity){ Intent intent = new Intent(activity, AddXiaoBaiActivity.class); activity.startActivity(intent); } @Override protected int getLayoutId() { return R.layout.activity_add_xiao_bai; } @Override protected void initView() { recyclerView = findViewById(R.id.recyclerView); rgSex = findViewById(R.id.rgSex); refreshLayout = findViewById(R.id.refreshLayout); ivPortrait = findViewById(R.id.ivPortrait); etName = findViewById(R.id.etName); etIntroduce = findViewById(R.id.etIntroduce); tvAdd = findViewById(R.id.tvAdd); initRecyclerView(); initRefreshLayout(); initPopAddPhoto(); } @Override protected void initData() { initXiaoBaiListRequest(); initAddXiaoBaiRequest(); } @Override protected void initEvent() { rgSex.setOnCheckedChangeListener(radioGrouplisten); ivPortrait.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ScreenUtils.dimBackground(AddXiaoBaiActivity.this, 1f, 0.5f); popAddPhoto.showAtLocation(v, Gravity.BOTTOM,0,0); } }); tvAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etName.getText().toString().trim(); String introduce = etIntroduce.getText().toString().trim(); if (name == null || name.equals("")) { ToastUtils.show("姓名不能为空"); return; } if (introduce == null || introduce.equals("")) { ToastUtils.show("简介不能为空"); return; } if (filePortrait == null) { ToastUtils.show("请选择头像"); return; } RequestBody strBodyName = RequestBody.create(MediaType.parse("text/plain"), name); RequestBody strBodyIntroduce = RequestBody.create(MediaType.parse("text/plain"), introduce); RequestBody strBodySex = RequestBody.create(MediaType.parse("text/plain"), strSex); bodyMap = new HashMap<>(); shopApi = new ShopApi(ShopApi.ADD_XIAO_BAI); bodyMap.put("xb_name", strBodyName); bodyMap.put("xb_sex", strBodySex); bodyMap.put("introduction", strBodyIntroduce); RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), filePortrait); MultipartBody.Part part = MultipartBody.Part.createFormData("xb_headimg", filePortrait.getName(), fileBody); parts.add(part); shopApi.setBodyMap(bodyMap); shopApi.setParts(parts); manager.doHttpDeal(shopApi); } }); } @Override protected void updateView() { } //初始化刷新控件 private void initRefreshLayout() { refreshLayout.setColorSchemeColors(Color.parseColor("#f39800")); refreshLayout.setOnRefreshListener(() -> { isRefreshing = true; page = 1; initXiaoBaiListRequest(); }); } private void initXiaoBaiList(List<AddXiaoBaiEntity.ListBean> dataBeanList) { if (isLoadMore) { isLoadMore = false; adapter.loadMoreComplete(); if (dataBeanList.size() < limit) { adapter.loadMoreEnd(); } adapter.addData(dataBeanList); } else { refreshLayout.setRefreshing(false); isRefreshing = false; adapter.setNewData(dataBeanList); } page ++; } //RadioGroup控件的初始化 private RadioGroup.OnCheckedChangeListener radioGrouplisten = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (group.getCheckedRadioButtonId()) { case R.id.radio0: //男 strSex = "1"; break; case R.id.radio1: //女 strSex = "2"; break; default: break; } } }; private void initRecyclerView() { adapter = new AddXiaoBaiAdapter(R.layout.item_add_xiao_bai, null); recyclerView.setNestedScrollingEnabled(false); recyclerView.setLayoutManager(new LinearLayoutManager(AddXiaoBaiActivity.this)); recyclerView.setAdapter(adapter); adapter.setOnLoadMoreListener(() -> { isLoadMore = true; initXiaoBaiListRequest(); }, recyclerView); adapter.setOnItemChildClickListener((adapter, view, position) -> { AddXiaoBaiEntity.ListBean listBean = (AddXiaoBaiEntity.ListBean) adapter.getData().get(position); switch (view.getId()) { case R.id.ivDelete: AlertDialog alertDialog = new AlertDialog.Builder(AddXiaoBaiActivity.this) .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { changePosition = position; initDelXiaoBaiRequest(listBean.getXiaobai_id()); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setMessage("确定删除吗?") .create(); alertDialog.show(); break; } }); } @Override public void initTitle() { super.initTitle(); setTitleCenter("添加小白"); } private void initPopAddPhoto() { View view = LayoutInflater.from(this).inflate(R.layout.pop_add_photo, null); popAddPhoto = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); popAddPhoto.setFocusable(true); popAddPhoto.setOutsideTouchable(false); popAddPhoto.setClippingEnabled(false); popAddPhoto.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //屏幕亮度变化 ScreenUtils.dimBackground(AddXiaoBaiActivity.this, 0.5f, 1f); } }); popAddPhoto.setAnimationStyle(R.style.photo_album_pop_edit); //pop动画效果 //相册 view.findViewById(R.id.pop_photo_album).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 激活系统图库,选择一张图片 Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); // 开启一个带有返回值的Activity startActivityForResult(intent, ADD_PORTRAIT_PHOTO); } }); //拍照 view.findViewById(R.id.pop_photograph).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Auto-generated method stub Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent,ADD_PORTRAIT_CAMERA); } }); //关闭 view.findViewById(R.id.pop_close).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popAddPhoto.dismiss(); } }); popAddPhoto.setFocusable(true); popAddPhoto.setOutsideTouchable(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_PORTRAIT_PHOTO) { // 从相册返回的数据 if (data != null) { // 得到图片的全路径 Uri uri = data.getData(); filePortrait = FileUtils.uriToFile(uri, this); filePortrait = BitmapUtil.compressImage(filePortrait.getAbsolutePath(), FileUtils.getFileName(filePortrait.getName())); Glide.with(this).load(filePortrait).into(ivPortrait); popAddPhoto.dismiss(); } } else if (requestCode == ADD_PORTRAIT_CAMERA) { if (data != null) { Bundle bundle = data.getExtras(); Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式 filePortrait = FileUtils.bitmapToFile(bitmap); Glide.with(this).load(filePortrait).into(ivPortrait); RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), filePortrait); MultipartBody.Part part = MultipartBody.Part.createFormData("xb_headimg", filePortrait.getName(), fileBody); parts.add(part); popAddPhoto.dismiss(); } } try { } catch (Exception e) { e.printStackTrace(); } super.onActivityResult(requestCode, resultCode, data); } @Override public void onNext(String resulte, String mothead) { if (mothead.equals(ShopApi.XIAO_BAI_LIST)) { BaseResultEntity<AddXiaoBaiEntity> dataList = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<AddXiaoBaiEntity>>(){}.getType()); if (dataList.getStatus().equals("200")) { //成功 initXiaoBaiList(dataList.getData().getList()); return; } ToastUtils.show(dataList.getMsg()); } if (mothead.equals(ShopApi.DEL_XIAO_BAI)) { BaseResultEntity dataList = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity>(){}.getType()); if (dataList.getStatus().equals("200")) { //成功 adapter.remove(changePosition); return; } ToastUtils.show(dataList.getMsg()); } if (mothead.equals(ShopApi.ADD_XIAO_BAI)) { BaseResultEntity dataList = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity>(){}.getType()); if (dataList.getStatus().equals("200")) { //成功 page = 1; initXiaoBaiListRequest(); // filePortrait = null; // Glide.with(this).load(getResources().getDrawable(R.mipmap.add_photo)).into(ivPortrait); // etName.setText(""); // etIntroduce.setText(""); return; } ToastUtils.show(dataList.getMsg()); } } @Override public void onError(ApiException e) { } }
package com.example.mschyb.clockingapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CalendarView; import android.widget.TextView; import java.text.DateFormatSymbols; import java.util.HashMap; import java.util.Map; public class ViewScheduleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_schedule); if(Config.getUserId() == 0) { startActivity(new Intent(getApplicationContext(), LoginScreenActivity.class)); } Button backButton = (Button) findViewById(R.id.backButton); //set the onClick listener for the button backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class)); } } );//end backButton.setOnClickListener //Get schedule Utilities utilities = new Utilities(); final HashMap<String, String[]> schedule = utilities.getSchedule(Config.getUserId(), "2010-01-01", "2020-01-01"); CalendarView calendar = (CalendarView) findViewById(R.id.calendarView); calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { public void onSelectedDayChange(CalendarView view, int year, int month, int day) { //Only used for testing TextView startTime = (TextView) findViewById(R.id.textView8); startTime.setVisibility(View.INVISIBLE); TextView endTime = (TextView) findViewById(R.id.textView9); endTime.setVisibility(View.INVISIBLE); String monthString, dayString; if(++month < 10) monthString = "0" + month; else monthString = String.valueOf(month); if(day < 10) dayString = "0" + day; else dayString = String.valueOf(day); String key = year + "-" + monthString + "-" + dayString; Intent intent= new Intent(getApplicationContext(), ScheduleDateActivity.class); intent.putExtra("scheduledYear", year); intent.putExtra("scheduledMonth", month); intent.putExtra("scheduledDay", day); if(schedule.containsKey(key)) { String[] startAndStopTimes = schedule.get(key); intent.putExtra("startTime", startAndStopTimes[0].split(" ")[1]); intent.putExtra("endTime", startAndStopTimes[1].split(" ")[1]); } startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_view_schedule, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.edgit.commons.network.exceptions; import java.io.IOException; public class IllegalLengthNameException extends IOException { private static final long serialVersionUID = 1L; }
package com.example.lemonimagelibrary.request; import android.content.Context; import android.widget.ImageView; import com.example.lemonimagelibrary.cache.BitmapCache; import com.example.lemonimagelibrary.config.BitmapConfig; import com.example.lemonimagelibrary.loader.LoaderMode; import com.example.lemonimagelibrary.policy.IPolicy; import com.example.lemonimagelibrary.util.MD5Utils; import java.io.File; import java.lang.ref.SoftReference; /** * Created by ShuWen on 2017/3/22. * 对请求参数的二次封装,对内部封装的暴露 */ @SuppressWarnings("ALL") public class BitmapRequest implements Comparable<BitmapRequest>{ private int requestId; private String uri; private LoaderMode loaderMode; private SoftReference<ImageView> softReference; private IPolicy policy; private String uriMD5; private int loadingResId; private BitmapCache cache; private boolean hasListener; private File file; private int resId = -1; private BitmapConfig.BitmapListener bitmapListener; private Context context; public BitmapRequest(BitmapConfig config){ this.context = config.getContext(); this.bitmapListener = config.getBitmapListener(); this.cache = config.getCache(); this.loadingResId = config.getLoadingResId(); this.hasListener = config.isHasListener(); this.policy = config.getPolicy(); this.softReference = new SoftReference<>(config.getImageView()); this.uri = config.getUrl(); this.file = config.getFile(); this.resId = config.getResId(); loaderMode = config.getLoaderMode(); uriMD5Str(); if (config.getImageView() != null){ config.getImageView().setTag(uriMD5); } } private void uriMD5Str() { switch (loaderMode){ case HTTP: this.uriMD5 = MD5Utils.toMD5(uri); break; case ASSETS: this.uriMD5 = MD5Utils.toMD5(resId+"8023"); break; case FILE: this.uriMD5 = MD5Utils.toMD5(file.getAbsolutePath()); break; } } public LoaderMode getLoaderMode() { return loaderMode; } public File getFile() { return file; } public int getResId() { return resId; } public int getRequestId() { return requestId; } public void setRequestId(int requestId) { this.requestId = requestId; } public String getUri() { return uri; } public SoftReference<ImageView> getSoftReference() { return softReference; } public ImageView getImageView() { return softReference.get(); } public IPolicy getPolicy() { return policy; } public String getUriMD5() { return uriMD5; } public int getLoadingResId() { return loadingResId; } public BitmapCache getCache() { return cache; } public boolean isHasListener() { return hasListener; } public BitmapConfig.BitmapListener getBitmapListener() { return bitmapListener; } public Context getContext() { return context; } @Override public int compareTo(BitmapRequest o) { return policy.compareTo(this,o); } }
package com.gadgetreactor.stocky; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; /** * Created by ASUS on 26/12/2014. */ public class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new StackRemoteViewsFactory(this.getApplicationContext(), intent); } } class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { private JSONArray mBuzzes; private Context mContext; public StackRemoteViewsFactory(Context context, Intent intent) { mContext = context; } public void onCreate() { } public void onDestroy() { mBuzzes = new JSONArray(); } public int getCount() { return mBuzzes.length(); } public RemoteViews getViewAt(int position) { String stockname; String symbol; String price; String change; String percentage; RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.stock_view_widget); if (position <= getCount()) { JSONObject stock = mBuzzes.optJSONObject(position); stockname = stock.optString("Name"); symbol = stock.optString("symbol"); price = stock.optString("LastTradePriceOnly"); change = stock.optString("Change"); percentage = " [" + stock.optString("ChangeinPercent") + "]"; rv.setTextViewText(R.id.stockName, stockname); rv.setTextViewText(R.id.symbol, symbol); rv.setTextViewText(R.id.price, price); rv.setTextViewText(R.id.change, change); rv.setTextViewText(R.id.change_percent, percentage); String changeamt = stock.optString("Change"); if (changeamt.substring(0, 1).equals("+")) { rv.setTextColor(R.id.change_percent, Color.parseColor("#00BA00")); } else if (changeamt.substring(0, 1).equals("-")) { rv.setTextColor(R.id.change_percent, Color.parseColor("#E00000")); } // store the ID in the extras so the main activity can use it // Bundle extras = new Bundle(); Intent fillInIntent = new Intent(); fillInIntent.putExtra("stock", stock.toString()); rv.setOnClickFillInIntent(R.id.widgetItem, fillInIntent); } return rv; } public RemoteViews getLoadingView() { return null; } public int getViewTypeCount() { return 1; } public long getItemId(int position) { return position; } public boolean hasStableIds() { return true; } public void onDataSetChanged() { mBuzzes = Widget.getData(); } }
package framework; import framework.SuperServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.xtext.xbase.lib.Exceptions; @SuppressWarnings("all") public class StartServer { /** * http://localhost:8080 * http://localhost:8080/guess/50 */ public static void main(final String[] args) { try { Server _server = new Server(8080); final Server server = _server; ServletContextHandler _servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); final ServletContextHandler context = _servletContextHandler; context.setContextPath("/"); server.setHandler(context); SuperServlet _superServlet = new SuperServlet(); ServletHolder _servletHolder = new ServletHolder(_superServlet); context.addServlet(_servletHolder, "/*"); server.start(); server.join(); } catch (Exception _e) { throw Exceptions.sneakyThrow(_e); } } }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 dk.sidereal.lumm.components.pathfinding; import java.util.ArrayList; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import dk.sidereal.lumm.architecture.LummObject; /** * A map with assymetrical access between nodes. Access can be change using * {@link #addNode(PathfindingNode)} or * {@link #addPrefab(int, int, PathfindingNode.NodePrefab, boolean)}. * * @author Claudiu Bele */ public class PathfindingMap { // region fields public PathfindingNode[][] nodes; public Rectangle bounds; public Vector2 centerAnchorPosition; private Vector2 nodeSize; public int nodesX; public int nodesY; public ArrayList<PathfindingRoute.Path> paths; public long lastUpdate; // endregion fields // region constructors public PathfindingMap(int width, int height) { paths = new ArrayList<PathfindingRoute.Path>(); nodesX = width; nodesY = height; centerAnchorPosition = Vector2.Zero; nodeSize = new Vector2(100, 100); nodes = new PathfindingNode[width][height]; for (int i = 0; i < nodes.length; i++) { for (int j = 0; j < nodes[i].length; j++) { nodes[i][j] = new PathfindingNode(this, i, j, true); } } bounds = new Rectangle(centerAnchorPosition.x - (nodesX * nodeSize.x) / 2, centerAnchorPosition.y - (nodesY * nodeSize.y) / 2, nodesX * nodeSize.x, nodesY * nodeSize.y); } // endregion constructors // region methods public Vector2 getNodePosition(int x, int y) { return new Vector2(getNodeX(x), getNodeY(y)); } public void setNodeSize(float x, float y) { nodeSize.set(x, y); bounds = new Rectangle(centerAnchorPosition.x - (nodesX * nodeSize.x) / 2, centerAnchorPosition.y - (nodesY * nodeSize.y) / 2, nodesX * nodeSize.x, nodesY * nodeSize.y); // update node position for (int nodeX = 0; nodeX < nodesX; nodeX++) { for (int nodeY = 0; nodeY < nodesY; nodeY++) { nodes[nodeX][nodeY].setPosition(getNodeX(nodeX), getNodeY(nodeY)); } } } public Vector2 getNodeSize() { return nodeSize; } public float getNodeY(int y) { float yPos = y - nodesY / 2 + ((nodesY % 2 == 0) ? 0.5f : 0); yPos *= nodeSize.y; yPos += centerAnchorPosition.y; return yPos; } public float getNodeX(int x) { float xPos = x - nodesX / 2 + ((nodesX % 2 == 0) ? 0.5f : 0f); xPos *= nodeSize.x; xPos += centerAnchorPosition.x; return xPos; } public void addNode(PathfindingNode node) { int x = node.x; int y = node.y; nodes[x][y].access = null; nodes[x][y].adjacent = null; nodes[x][y].handleAdjacent = null; nodes[x][y].x = nodes[x][y].y = 0; nodes[x][y] = node; if (x == 0) { nodes[x][y].access[0] = false; } if (x == nodesX - 1) { nodes[x][y].access[1] = false; } if (y == 0) { nodes[x][y].access[2] = false; } if (y == nodesY - 1) { nodes[x][y].access[3] = false; } paths.clear(); lastUpdate = System.currentTimeMillis(); } public void addPrefab(int x, int y, PathfindingNode.NodePrefab prefab, boolean reverse) { for (int i = 0; i < 4; i++) { if (prefab.handleAccess[i]) nodes[x][y].access[i] = (reverse) ? !prefab.access[i] : prefab.access[i]; } if (x != 0 && prefab.handleAdjacent[PathfindingNode.LEFT_ACCESS]) { nodes[x - 1][y].access[PathfindingNode.RIGHT_ACCESS] = (reverse) ? !prefab.adjacent[PathfindingNode.LEFT_ACCESS] : prefab.adjacent[PathfindingNode.LEFT_ACCESS]; } if (x != nodesX - 1 && prefab.handleAdjacent[PathfindingNode.RIGHT_ACCESS]) { nodes[x + 1][y].access[PathfindingNode.LEFT_ACCESS] = (reverse) ? !prefab.adjacent[PathfindingNode.RIGHT_ACCESS] : prefab.adjacent[PathfindingNode.RIGHT_ACCESS]; } if (y != 0 && prefab.handleAdjacent[PathfindingNode.BOTTOM_ACCESS]) { nodes[x][y - 1].access[PathfindingNode.TOP_ACCESS] = (reverse) ? !prefab.adjacent[PathfindingNode.BOTTOM_ACCESS] : prefab.adjacent[PathfindingNode.BOTTOM_ACCESS]; } if (y != nodesY - 1 && prefab.handleAdjacent[PathfindingNode.TOP_ACCESS]) { nodes[x][y + 1].access[PathfindingNode.BOTTOM_ACCESS] = (reverse) ? !prefab.adjacent[PathfindingNode.TOP_ACCESS] : prefab.adjacent[PathfindingNode.TOP_ACCESS]; } // boundries will still be maintained if (x == 0) { nodes[x][y].access[0] = false; } if (x == nodesX - 1) { nodes[x][y].access[1] = false; } if (y == 0) { nodes[x][y].access[2] = false; } if (y == nodesY - 1) { nodes[x][y].access[3] = false; } paths.clear(); lastUpdate = System.currentTimeMillis(); } public Rectangle getBounds() { return bounds; } public PathfindingNode gamePositionToNode(LummObject obj) { // outside of map bounds if (!getBounds().contains(obj.position.getX(), obj.position.getY())) return null; int nodeX = (int) ((obj.position.getX() - getBounds().x) / getNodeSize().x); int nodeY = (int) ((obj.position.getY() - getBounds().y) / getNodeSize().y); return nodes[nodeX][nodeY]; } // endregion methods }
package br.com.bottesini.comercialapi.service; import br.com.bottesini.comercialapi.model.Oportunidade; import br.com.bottesini.comercialapi.repository.OportunidadeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class OportunidadeService { @Autowired OportunidadeRepository oportunidadeRepository; public List<Oportunidade> get(){ List<Oportunidade> oportunidades = new ArrayList(); oportunidadeRepository.findAll().forEach(oportunidades::add); return oportunidades; } public Oportunidade getById(Long id) { return oportunidadeRepository.findById(id).orElse(null); } public Oportunidade salvar(Oportunidade oportunidade) { return oportunidadeRepository.save(oportunidade); } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.datasource.init; import javax.sql.DataSource; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Used to {@linkplain #setDatabasePopulator set up} a database during * initialization and {@link #setDatabaseCleaner clean up} a database during * destruction. * * @author Dave Syer * @author Sam Brannen * @since 3.0 * @see DatabasePopulator */ public class DataSourceInitializer implements InitializingBean, DisposableBean { @Nullable private DataSource dataSource; @Nullable private DatabasePopulator databasePopulator; @Nullable private DatabasePopulator databaseCleaner; private boolean enabled = true; /** * The {@link DataSource} for the database to populate when this component * is initialized and to clean up when this component is shut down. * <p>This property is mandatory with no default provided. * @param dataSource the DataSource */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * Set the {@link DatabasePopulator} to execute during the bean initialization phase. * @param databasePopulator the {@code DatabasePopulator} to use during initialization * @see #setDatabaseCleaner */ public void setDatabasePopulator(DatabasePopulator databasePopulator) { this.databasePopulator = databasePopulator; } /** * Set the {@link DatabasePopulator} to execute during the bean destruction * phase, cleaning up the database and leaving it in a known state for others. * @param databaseCleaner the {@code DatabasePopulator} to use during destruction * @see #setDatabasePopulator */ public void setDatabaseCleaner(DatabasePopulator databaseCleaner) { this.databaseCleaner = databaseCleaner; } /** * Flag to explicitly enable or disable the {@linkplain #setDatabasePopulator * database populator} and {@linkplain #setDatabaseCleaner database cleaner}. * @param enabled {@code true} if the database populator and database cleaner * should be called on startup and shutdown, respectively */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Use the {@linkplain #setDatabasePopulator database populator} to set up * the database. */ @Override public void afterPropertiesSet() { execute(this.databasePopulator); } /** * Use the {@linkplain #setDatabaseCleaner database cleaner} to clean up the * database. */ @Override public void destroy() { execute(this.databaseCleaner); } private void execute(@Nullable DatabasePopulator populator) { Assert.state(this.dataSource != null, "DataSource must be set"); if (this.enabled && populator != null) { DatabasePopulatorUtils.execute(populator, this.dataSource); } } }
package com.zantong.mobilecttx.huodong.bean; import com.zantong.mobilecttx.base.bean.BaseResult; /** * Created by zhoujie on 2017/2/17. */ public class ActivityCarResult extends BaseResult { private ActivityCar data; public ActivityCar getData() { return data; } public void setData(ActivityCar data) { this.data = data; } public class ActivityCar{ private String plateNo; public String getPlateNo() { return plateNo; } public void setPlateNo(String plateNo) { this.plateNo = plateNo; } } }
package br.mpac.controller; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import br.mpac.dados.GenericDao; import br.mpac.dados.RendaDao; import br.mpac.entidade.Renda; @Named @SessionScoped public class RendaController extends AbstractController<Renda> { private static final long serialVersionUID = 1L; @EJB private RendaDao dao; @Override public GenericDao<Renda> getDao() { return dao; } @Override public void prepareCreate() { setSelected(new Renda()); } }
import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; public class app { public static void main(String[] args) { System.out.println("Bienevenido a la segunda actividad de Java"); Scanner s = new Scanner(System.in); boolean salir = false; int opcion; //Guardaremos la opcion del usuario while (!salir) { System.out.println("1-Devolver 5 numeros en el mismo orden !"); System.out.println("2-Devolver los numeros en orden inverso !"); System.out.println("3-Media positiva, negativa y numero de 0"); System.out.println("4-Cuenta el numero de caracteres de un texto !"); System.out.println("5-Invierte el texto !"); System.out.println("6-Elimina los espacios!"); System.out.println("7-Junta dos textos"); System.out.println("8-Sustituye las vocales de un texto"); System.out.println("9-Pasa un texto a ASCII!"); System.out.println("0-Cerrar el programa"); //Las opciones con ! están acabadas System.out.println("Elige una opcion"); opcion = s.nextInt(); switch(opcion) { case 1 : metodo1(); break; case 2 : metodo2(); break; case 3 : System.out.println("Has elegido la tercera opción"); break; case 4 : metodo4(); break; case 5 : metodo5(); break; case 6 : metodo6(); break; case 7 : metodo7(); break; case 8 : metodo8(); break; case 9 : metodo9(); break; case 0 : salir = true; break; default: System.out.println("Las opciones son entre 0-9"); } } } private static void metodo1() { Scanner s = new Scanner(System.in); int [] lista1 = new int [5]; System.out.println("Di los cinco numeros uno por uno"); for (int i = 0; i<5;i++){ lista1[i] =s.nextInt(); } System.out.println(Arrays.toString(lista1)); } private static void metodo2() { Scanner s = new Scanner(System.in); int [] lista1 = new int [5]; System.out.println("Di los cinco numeros uno por uno"); for (int i = 0; i<5;i++){ lista1[i] =s.nextInt(); } List<Integer> resultado = new ArrayList<>(); for (int a = lista1.length; a >= 0; a--){ int numero = (int) a; resultado.add(numero); } System.out.println(resultado.toString()); } private static void metodo4() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); System.out.println("Escribe el texto que quieres usar"); texto1 = s.next(); int textosinespacios = texto1.replace(" ", "").length(); System.out.println("Numero de letras " + (textosinespacios-1)); } private static void metodo5() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); System.out.println("Escribe el texto que quieres usar"); texto1 = s.next(); byte[] strAsByteArray = texto1.getBytes(); byte[] result = new byte[strAsByteArray.length]; for (int i=0; i < strAsByteArray.length; i++) result[i] = strAsByteArray[strAsByteArray.length - i - 1]; System.out.println(new String (result)); } private static void metodo6() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); System.out.println("Escribe el texto que quieres usar"); texto1 = s.next(); System.out.println(texto1.replace(" ", "")); } private static void metodo7() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); String texto2 = new String(); System.out.println("Escribe la primera frase: "); texto1 = s.next(); System.out.println("Escribe la segunda frase: "); texto2 = s.next(); System.out.println(texto1+texto2); //no concatena las variables por algún motivo } private static void metodo8() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); String vocal = new String(); String str ; System.out.println("Escribe el texto que quieres usar"); texto1 = s.next(); System.out.println("Escribe la vocal que quieres"); vocal= s.next(); String textorenovado = texto1.replaceAll("[aeiou]", vocal); System.out.println(textorenovado); // Por algún motivo que no comprendo, pese a que la variable textorenovado está correcta cuando lo reviso en debug, printea bara (??) } private static void metodo9() { Scanner s = new Scanner(System.in); s.useDelimiter("\n"); String texto1 = new String(); String str ; System.out.println("Escribe el texto que quieres usar"); texto1 = s.next(); byte[] bytes = texto1.getBytes(StandardCharsets.US_ASCII); List<Integer> resultado = new ArrayList<>(); for (byte aByte : bytes) { int ascii = (int) aByte; resultado.add(ascii); } System.out.println(resultado.toString()); } }
package com.beike.core.service.trx.partner.impl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.beike.common.bean.trx.partner.Par360buyOrderParam; import com.beike.core.service.trx.partner.PartnerGoodsService; import com.beike.entity.goods.Goods; import com.beike.service.goods.GoodsService; /** * * @author 赵静龙 创建时间:2012-10-31 */ @Service("partnerGoodsService") public class PartnerGoodsServiceImpl implements PartnerGoodsService { @SuppressWarnings("unused") private static final Log logger = LogFactory.getLog(PartnerGoodsServiceImpl.class); @Autowired private GoodsService goodsService; /* (non-Javadoc) * @see com.beike.core.service.trx.partner.PartnerGoodsService#processGoodsSellCount(java.lang.Object) */ @Override public String processGoodsSellCount(Object ptop) throws Exception{ Par360buyOrderParam par360param =(Par360buyOrderParam) ptop; String venderTeamId = par360param.getVenderTeamId(); long salescount = querySellCount(venderTeamId); if(-1L == salescount){ throw new Exception("+++++++++++++++++没有找到此商品++++++++++++"); } StringBuffer responseData = new StringBuffer(); //团购销量查询 data返回报文 responseData.append("<Message xmlns=\"http://tuan.360buy.com/QueryTeamSellCountResponse\">"); responseData.append("<VenderTeamId>" + venderTeamId + "</VenderTeamId>"); //团购ID responseData.append("<SellCount>"+ salescount + "</SellCount>"); //销量 responseData.append("</Message>"); return responseData.toString(); } /* (non-Javadoc) * @see com.beike.core.service.trx.partner.PartnerGoodsService#querySellCount(java.lang.String) */ public long querySellCount(String venderTeamId) { long count = 0; Goods good = goodsService.findById(Long.parseLong(venderTeamId)); if(good == null){ return -1L; }else{ String salescount = goodsService.salesCount(Long.parseLong(venderTeamId)); if(StringUtils.isEmpty(salescount)){ salescount = "0"; } count = good.getVirtualCount() + Long.parseLong(salescount); } if(count == 0){ count = 1; } return count; } }
package com.nanyin.config.security.filter; import com.alibaba.fastjson.JSON; import com.nanyin.config.enums.ResultCodeEnum; import com.nanyin.config.exceptions.tokenException.TokenEmptyException; import com.nanyin.config.exceptions.tokenException.TokenExpiredException; import com.nanyin.config.exceptions.tokenException.TokenParseException; import com.nanyin.config.exceptions.tokenException.TokenWrongException; import com.nanyin.config.util.HttpUtils; import com.nanyin.config.util.JwtUtil; import com.nanyin.config.util.Result; import com.nanyin.config.util.SecurityUtils; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.UnsupportedJwtException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * 自定义url的过滤器,主要对token的验证 */ public class CustomAuthenticationFilter extends BasicAuthenticationFilter { private HttpServletRequest request; private HttpServletResponse response; private FilterChain chain; public CustomAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { this.request = request; this.response = response; this.chain = chain; String validateToken = null; try{ validateToken = JwtUtil.getValidateToken(request); if (validateToken!=null){ // 新token HttpUtils.setCookie(HttpUtils.buildCookie("TokenKey",validateToken)); } SecurityUtils.checkAuthentication(request); } catch (ExpiredJwtException e) { Result result = new Result(); PrintWriter writer = response.getWriter(); result.setCode(ResultCodeEnum.TOKEN_EXPIRED); writer.append(JSON.toJSONString(result)); return; } catch (MalformedJwtException|UnsupportedJwtException|IllegalArgumentException e) { Result result = new Result(); PrintWriter writer = response.getWriter(); result.setCode(ResultCodeEnum.ILLEGAL_TOKEN); writer.append(JSON.toJSONString(result)); return; } catch (Exception e){ Result result = new Result(); PrintWriter writer = response.getWriter(); result.setCode(ResultCodeEnum.FAIL); writer.append(JSON.toJSONString(result)); return; } chain.doFilter(request, response); } public HttpServletRequest getRequest() { return request; } public void setRequest(HttpServletRequest request) { this.request = request; } public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } public FilterChain getChain() { return chain; } public void setChain(FilterChain chain) { this.chain = chain; } }
package sr.hakrinbank.intranet.api.mapping; import org.modelmapper.PropertyMap; import sr.hakrinbank.intranet.api.dto.ListedPersonGreyDto; import sr.hakrinbank.intranet.api.model.ListedPersonGrey; public class ListedPersonGreyToDtoMap extends PropertyMap<ListedPersonGrey, ListedPersonGreyDto> { @Override protected void configure() { map().setNationality(source.getNationality().getId()); } }
package com.bestom.aihome.imple; import com.bestom.aihome.imple.inter.Listener.DataReceivedListener; import com.bestom.aihome.imple.inter.Obser.Observer; /** * 观察者,接收串口数据 通知服务 */ public class EnventDataObserver implements Observer { private DataReceivedListener dataReceivedListener; public EnventDataObserver(DataReceivedListener dataReceivedListener) { this.dataReceivedListener=dataReceivedListener; } @Override public void dataReceived(String dataHex) { } }
package com.fszuberski.tweets.session.adapter.lambda; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.fszuberski.LambdaTestLogger; import com.fszuberski.tweets.rest.domain.ApiException; import com.fszuberski.tweets.session.adapter.lambda.model.AuthenticationRequestModel; import com.fszuberski.tweets.session.core.domain.Session; import com.fszuberski.tweets.session.port.in.CreateSession; import org.junit.jupiter.api.*; import static com.fszuberski.tweets.session.port.in.CreateSession.CreateSessionException.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class SignInHandlerTest { private SignInHandler signInHandler; private Context context; private CreateSession createSession; @BeforeEach void setup() { createSession = mock(CreateSession.class); context = mock(Context.class); LambdaLogger loggerStub = new LambdaTestLogger(); when(context.getLogger()).thenReturn(loggerStub); signInHandler = new SignInHandler(createSession); } @Test void throw_IllegalArgument_given_null_createSession() { assertThrows(IllegalArgumentException.class, () -> new SignInHandler(null)); } @Test void return_response_containing_session_info() { String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWF0IjoxNjIxNzk0NjU1LCJpc3MiOiJmc3p1YmVyc2tpLmNvbSJ9.X8V6QfkyZs4ArqDX1_DRWmFNDHeBrqrD16rArGGwpVs"; AuthenticationRequestModel authenticationRequestModel = generateAuthenticationModel(); when(createSession.createSession(authenticationRequestModel.getUsername(), authenticationRequestModel.getPassword())) .thenReturn(new Session("username", "https://example.com/image.jpg", jwt)); Session session = signInHandler.handleRequest(authenticationRequestModel, context); assertNotNull(session); assertEquals("username", session.getUsername()); assertEquals("https://example.com/image.jpg", session.getProfilePictureUrl()); assertEquals(jwt, session.getToken()); } @Test void throw_BadRequest_exception_given_null_authenticationModel() { assertThrows(ApiException.BadRequest.class, () -> signInHandler.handleRequest(null, context)); } @Test void throw_BadRequest_exception_given_invalid_username_and_password_combination() { AuthenticationRequestModel authenticationRequestModel = generateAuthenticationModel(); when(createSession.createSession(authenticationRequestModel.getUsername(), authenticationRequestModel.getPassword())) .thenThrow(new InvalidUsernameAndPassword()); assertThrows(ApiException.BadRequest.class, () -> signInHandler.handleRequest(authenticationRequestModel, context)); } @Test void throw_InternalServerError_exception_given_generic_exception_occurs() { AuthenticationRequestModel authenticationRequestModel = generateAuthenticationModel(); when(createSession.createSession(authenticationRequestModel.getUsername(), authenticationRequestModel.getPassword())) .thenThrow(new RuntimeException()); assertThrows(ApiException.InternalServerError.class, () -> signInHandler.handleRequest(authenticationRequestModel, context)); } private AuthenticationRequestModel generateAuthenticationModel() { return new AuthenticationRequestModel("username", "password"); } }
package com.sandrapenia.business; import com.sandrapenia.entities.Entity; /** Utilizada para los mensajes de error y exito en los business **/ public class Response { private ResponseTypeEnum type; private String message; private Entity entity; private Response(ResponseTypeEnum type) { this.type = type; } private Response(ResponseTypeEnum type, String message) { this.type = type; this.setMessage(message); } private Response(ResponseTypeEnum type, Entity entity) { this.type = type; this.setEntity(entity); } public ResponseTypeEnum getType() { return type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public static Response error(String reason) { return new Response(ResponseTypeEnum.error, reason); } public static Response ok() { return new Response(ResponseTypeEnum.ok); } public static Response ok(String xmlProject) { return new Response(ResponseTypeEnum.ok, xmlProject); } public static Response ok(Entity entity) { return new Response(ResponseTypeEnum.ok, entity); } }
package com.tanon.abedjinan.springbootvue.utils; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Un DTO pour afficher un lien * * @author pakeyser * */ public class LinkDTO { private final String text; private final Long value; @JsonCreator public LinkDTO(@JsonProperty("value") Long value, @JsonProperty("text") String text) { super(); this.value = value; this.text = text; } public String getText() { return text; } public Long getValue() { return value; } }
package com.yan.coupons.dao; import java.util.Calendar; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.yan.coupons.dto.CouponDto; import com.yan.coupons.entity.Coupon; import com.yan.coupons.enums.Category; @Repository public interface CouponDao extends CrudRepository<Coupon, Long>{ @Query ("select new com.yan.coupons.dto.CouponDto(c.id, c.name, c.company.name, c.price , c.description , c.endDate) from Coupon c where c.category = ?1 ") public List<CouponDto> findByCategory(Category category); @Query ("select new com.yan.coupons.dto.CouponDto(c.id, c.name, c.company.name, c.price , c.description , c.endDate) from Coupon c where c.company.id = ?1 ") public List<CouponDto> findByCompanyId( long id); @Query ("select new com.yan.coupons.dto.CouponDto(c.id, c.name, c.company.name, c.price , c.description , c.endDate) from Coupon c where c.price > ?1 and c.price < ?2") public List<CouponDto> findCouponBetweenPrices ( float min, float max); public boolean existsByName(String name); @Query ("select new com.yan.coupons.dto.CouponDto(c.id, c.name, c.company.name, c.price , c.description , c.endDate) from Coupon c ") public List<CouponDto> getAllCoupons(); @Query ("select c from Coupon c where c.endDate < ?1") public List<Coupon> findCouponsExpired(Calendar dateNow); // need for validations public Coupon findById(long id); public Coupon findByName(String name); }
package com.jushu.video.service.impl; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.jushu.video.entity.MenuMovieType; import com.jushu.video.entity.MenuRecommend; import com.jushu.video.entity.MovieMain; import com.jushu.video.mapper.MenuMovieTypeMapper; import com.jushu.video.service.IMenuMovieTypeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 客户端-筛选菜单配置表 服务实现类 * </p> * * @author chen * @since 2020-02-13 */ @Service public class MenuMovieTypeServiceImpl extends ServiceImpl<MenuMovieTypeMapper, MenuMovieType> implements IMenuMovieTypeService { private Logger logger = LoggerFactory.getLogger(MenuRecommendServiceImpl.class); @Override public List<MenuMovieType> recommendList() { QueryWrapper queryWrapper = new QueryWrapper(); //查询所有推荐榜单列表 return baseMapper.selectList(queryWrapper); } @Override public Boolean delete(String[] ids) { if (ids == null || ids.length <= 0) { return false; } UpdateWrapper wrapper = new UpdateWrapper(); wrapper.in("id", ids); return baseMapper.delete(wrapper) > 0; } @Override public Boolean create(@Param("menuMovieType") MenuMovieType menuMovieType) { if(menuMovieType.getId().equals(0)){ return false; } return baseMapper.insert(menuMovieType) > 0; } }
package comp1110.ass2; import org.junit.jupiter.api.Test; import java.util.Arrays; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @org.junit.jupiter.api.Timeout(value = 5000, unit = MILLISECONDS) public class DrawTileFromBagTest { private static int BASE_ITERATIONS = 10000; private String errorPrefix(String[] inputState) { return "Azul.drawFromBag({\"" + inputState[0] + "\", \"" + inputState[1] + "\"})" + System.lineSeparator(); } @Test public void testDistribution() { int[] count = new int[5]; String[] state = {"AFCB2020202020D0000000000", "A0MSFB0MSF"}; String errorMessagePrefix = errorPrefix(state); for (int i = 0; i < BASE_ITERATIONS; i++) { char c = Azul.drawTileFromBag(state); assertFalse(c < 'a' || c > 'e', errorMessagePrefix + "expected a char between 'a' and 'e', but you drew " + c); count[c - 'a']++; } assertTrue(Arrays.stream(count).min().getAsInt() > 0, errorMessagePrefix + "expected you to draw at least one of each value from 'a' - 'e' in 10,000 draws, but you missed a value"); double[] expectedProbs = new double[]{1.0 / 5.0, 1.0 / 5.0, 1.0 / 5.0, 1.0 / 5.0, 1.0 / 5.0}; double chi = chiSquared(expectedProbs, BASE_ITERATIONS, count); assertTrue(chi < 9.5, errorMessagePrefix + "Distribution of tiles drawn don't appear to be uniform (chi squared value of " + chi + ")"); } private static double chiSquared(double[] expectedProbs, int samples, int[] counts) { double total = 0; for (int i = 0; i < expectedProbs.length; i++) { double mi = ((double) samples) * expectedProbs[i]; total += ((double) counts[i] - mi) * ((double) counts[i] - mi) / mi; } return total; } @Test public void testCorrectTile() { String[] state = {"BFCB0014151300D0901000011", "A1Ma04c23S0d11b22a33e34d5FbdfB0Mb01S0e11a22b13e44a5Fcccce"}; int[] count = new int[3]; String errorMessagePrefix = errorPrefix(state); for (int i = 0; i < BASE_ITERATIONS; i++) { char c = Azul.drawTileFromBag(state); assertFalse(c < 'b' || c > 'd', errorMessagePrefix + "expected a char between 'b' and 'd', but you drew: " + c); count[c - 'b']++; } assertTrue(Arrays.stream(count).min().getAsInt() > 0, errorMessagePrefix + "expected you to draw at least one of each value from 'b' - 'd' in 10,000 draws, but you missed a value"); } @Test public void testEmptyBag() { String[] state = {"AFCB0000000000D1113080909", "A5Me00c01d02a04d10b14a20b21c23e32d43S0b11c22e33a34c3FeeeB11Me00b01d03a04d10e11a13d21b23a30e32a42S1b22c23d44c3Fdf"}; int[] count = new int[5]; String errorMessagePrefix = errorPrefix(state); for (int i = 0; i < BASE_ITERATIONS; i++) { char c = Azul.drawTileFromBag(state); assertFalse(c < 'a' || c > 'e', errorMessagePrefix + "expected a char between 'a' and 'e', but you drew: " + c); count[c - 'a']++; } assertTrue(Arrays.stream(count).min().getAsInt() > 0, errorMessagePrefix + "expected you to draw at least one of each value from 'a' - 'e' in 10,000 draws, but you missed a value"); } }
package com.strings; public class ReverseWordsInString { public static void main(String[] args) { System.out.println(new ReverseWordsInString().reverseWords("Today is Sunday")); } public String reverseWords(String s) { if(s == null) return null; char[] chars = s.toCharArray(); int i=0; int word_begin = -1; int length = chars.length; while(i<length) { if(word_begin==-1 && chars[i]!=' ') { word_begin = i; } if(i+1==length || chars[i+1] ==' ' ) { chars = reverse(chars,word_begin,i); word_begin=-1; } i++; }; chars= reverse(chars,0,i-1); return new String(chars); } public char[] reverse(char[] input,int startIndex,int endIndex) { if(input ==null) throw new IllegalArgumentException(); while(startIndex<endIndex) { char temp = input[startIndex]; input[startIndex] = input[endIndex]; input[endIndex] = temp; startIndex++; endIndex--; } return input; } }
package com.bibledaily.repository; public interface UserRepository extends GenericRepository { }
import java.util.StringTokenizer; public class B4Stringtest { public static void main(String[] args) { StringTokenizer stz1 = new StringTokenizer("홍길동 김하나 오준석"); int count=stz1.countTokens(); System.out.println(count); while(stz1.hasMoreElements())//nextelements { String st = (String)stz1.nextElement(); System.out.println(st); } System.out.println("done!"); StringTokenizer stz2= new StringTokenizer("홍길동,김하나,오준석",","); while(stz2.hasMoreTokens())//nextToken //위둘다 사용가능 { System.out.println(stz2.nextToken()); } } }
package com.trump.auction.pals.api.model; import java.io.Serializable; import lombok.Data; /** * Created by IntelliJ IDEA * YhInfo : zhangsh * Date : 2016/12/26 0026 * Time : 18:00 */ public class MobilePaySendModel implements Serializable{ private static final long serialVersionUID = -8221711996982670198L; private String BACKURL; private String HOMEURL; private String REURL; public String getBACKURL() { return BACKURL; } public void setBACKURL(String bACKURL) { BACKURL = bACKURL; } public String getHOMEURL() { return HOMEURL; } public void setHOMEURL(String hOMEURL) { HOMEURL = hOMEURL; } public String getREURL() { return REURL; } public void setREURL(String rEURL) { REURL = rEURL; } }
/** * project name:cdds * file name:ScheduleService * package name:com.cdkj.schedule.schedule.service.api * date:2018/8/27 13:44 * author:ywshow * Copyright (c) CD Technology Co.,Ltd. All rights reserved. */ package com.cdkj.schedule.schedule.service.api; import com.cdkj.common.base.service.api.BaseService; import com.cdkj.model.schedule.pojo.Schedule; import com.cdkj.util.PageDTO; import com.cdkj.util.ResultInfo; import java.util.Map; /** * description: 定时任务管理 <br> * date: 2018/8/27 13:44 * * @author ywshow * @version 1.0 * @since JDK 1.8 */ public interface ScheduleService extends BaseService { /** * description: 根据ID,查询定时任务 <br> * * @param jobId 主键 * @return com.cdkj.model.schedule.pojo.Schedule */ Schedule queryObject(String jobId); /** * description: 查询定时任务列表 <br> * * @param pageDTO 查询条件信息 * @return com.cdkj.util.ResultInfo<com.cdkj.model.system.pojo.SysDict> */ ResultInfo<Schedule> selectList(PageDTO pageDTO); /** * 查询总数 */ int queryTotal(Map<String, Object> map); /** * description: 保存定时任务 <br> * * @param schedule 对象信息 * @return void */ void save(Schedule schedule); /** * description: 更新定时任务 <br> * * @param schedule 对象信息 * @return void */ void update(Schedule schedule); /** * description: 批量删除定时任务 <br> * * @param jobIds 主键数组 * @return void */ void deleteBatch(String[] jobIds); /** * description: 批量更新定时任务状态 <br> * * @param jobIds 主键 * @param status 状态 * @return int */ int updateBatch(String[] jobIds, Short status); /** * description: 立即执行 <br> * * @param jobIds 主键 * @return void */ void run(String[] jobIds); /** * description: 暂停运行 <br> * * @param jobIds 主键 * @return void */ void pause(String[] jobIds); /** * description: 恢复运行 <br> * * @param jobIds 主键 * @return void */ void resume(String[] jobIds); }
package com.doohong.shoesfit.test; import junitparams.JUnitParamsRunner; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JUnitParamsRunner.class) public class MemberTest { }
package com.sqlcipherexample.app.database; import android.content.Context; import com.sqlcipherexample.app.R; import com.sqlcipherexample.app.model.contract.ProductsContract; import com.sqlcipherexample.app.preferences.MySecurePreferences; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabaseHook; import net.sqlcipher.database.SQLiteOpenHelper; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class DatabaseHelper extends SQLiteOpenHelper { private static final String ENCRYPTED_DATABASE_NAME = "my_sqlcipher_database_encrypted.db"; private static final String UNENCRYPTED_DATABASE_NAME = "my_sqlcipher_database.db"; private static final int DATABASE_VERSION = 1; private static final String[] sTablesArray; static { sTablesArray = new String[] { ProductsContract.Table.TABLE_NAME }; } private static DatabaseHelper sDatabaseHelperInstance; private final Context mContext; private final String SEPARATOR = "#"; private DatabaseHelper(final Context context) { super(context, ENCRYPTED_DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } public static synchronized DatabaseHelper getInstance(final Context context) { if(sDatabaseHelperInstance == null) { sDatabaseHelperInstance = new DatabaseHelper(context); } return sDatabaseHelperInstance; } public static DatabaseHelper getInstance() { return sDatabaseHelperInstance; } @Override public void onCreate(SQLiteDatabase db) { setUpTables(db); } @Override public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { if(database.needUpgrade(newVersion)) { String dropQuery = "DROP TABLE IF EXISTS %s;"; for(String table : sTablesArray) { database.execSQL(String.format(dropQuery, table)); } setUpTables(database); } } public SQLiteDatabase getWritableDatabase() { return super.getWritableDatabase(MySecurePreferences.getInstance(mContext).getDatabaseAccessKey()); } public SQLiteDatabase getReadableDatabase() { return super.getReadableDatabase(MySecurePreferences.getInstance(mContext).getDatabaseAccessKey()); } private String[] getTablesArray() { final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(openDatabaseMetaResource())); String line; final StringBuilder queryBuilder = new StringBuilder(); try { while((line = bufferedReader.readLine()) != null) { queryBuilder.append(line); } final String databaseString = queryBuilder.toString(); return databaseString.split(SEPARATOR); } catch(IOException e) { e.printStackTrace(); throw new IllegalStateException(getClass().getSimpleName() + ": cannot create database!"); } finally { try { bufferedReader.close(); } catch (IOException e) { } } } private final InputStream openDatabaseMetaResource() { final InputStream inputStream = mContext.getResources().openRawResource(R.raw.database); return inputStream; } private void setUpTables(SQLiteDatabase db) { final String[] tables = getTablesArray(); for(final String query : tables) { db.execSQL(query.trim()); } } public static void encryptDatabaseIfUnencrypted(final Context context, final String newDatabaseAccesKey) { final File unencryptedDatabaseFile = context.getDatabasePath(UNENCRYPTED_DATABASE_NAME); final File encryptedDatabaseFile = context.getDatabasePath(ENCRYPTED_DATABASE_NAME); if(unencryptedDatabaseFile.exists() && !encryptedDatabaseFile.exists()) { SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(unencryptedDatabaseFile, "", null); database.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';", unencryptedDatabaseFile.getAbsolutePath(), newDatabaseAccesKey)); database.rawExecSQL("SELECT sqlcipher_export('encrypted')"); database.rawExecSQL("DETACH DATABASE encrypted;"); int version = database.getVersion(); database.close(); context.deleteDatabase(database.getPath()); final MySecurePreferences securePreferences = MySecurePreferences.getInstance(context); database = SQLiteDatabase.openOrCreateDatabase(encryptedDatabaseFile, newDatabaseAccesKey, null, new SQLiteDatabaseHook() { @Override public void preKey(SQLiteDatabase sqLiteDatabase) { } @Override public void postKey(SQLiteDatabase sqLiteDatabase) { securePreferences.setDatabaseAccessKey(newDatabaseAccesKey); } }); database.setVersion(version); database.close(); } } public static void changePassphrase(final String currentPassword, final String newPassword, final Context context) { final File databaseFile = context.getDatabasePath(ENCRYPTED_DATABASE_NAME); final SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, currentPassword, null); database.execSQL(String.format("PRAGMA rekey = '%s'", newPassword)); database.close(); } }
package samwho.perf; import battlecode.common.*; public class BytecodeCounter { private RobotController rc; private int bytecodes; private int round; private int total; public BytecodeCounter(RobotController rc) { this.rc = rc; this.bytecodes = Clock.getBytecodeNum(); this.round = rc.getRoundNum(); this.total = 0; } /** * Gets the number of bytecodes elapsed since the last time this method was * called. */ public int lap() { int b = Clock.getBytecodeNum(); int ret = b - this.bytecodes; int rdiff = rc.getRoundNum() - this.round; ret += rc.getType().bytecodeLimit * rdiff; if (rdiff > 0) { this.round += rdiff; } this.bytecodes = b; this.total += ret; return ret; } /** * Gets the total number of bytecodes elapsed in the lifetime of this object. */ public int total() { return this.total; } }
package vision.model; /** * 3-dimensional vector */ public class Position { /** * @uml.property name="x" */ private float x; public Position(float f, float g, float h) { x = f; y = g; z = h; } /** * Getter of the property <tt>x</tt> * * @return Returns the x. * @uml.property name="x" */ public float getX() { return x; } /** * Setter of the property <tt>x</tt> * * @param x * The x to set. * @uml.property name="x" */ public void setX(float x) { this.x = x; } /** * @uml.property name="y" */ private float y; /** * Getter of the property <tt>y</tt> * * @return Returns the y. * @uml.property name="y" */ public float getY() { return y; } /** * Setter of the property <tt>y</tt> * * @param y * The y to set. * @uml.property name="y" */ public void setY(float y) { this.y = y; } /** * @uml.property name="z" */ private float z; /** * Getter of the property <tt>z</tt> * * @return Returns the z. * @uml.property name="z" */ public float getZ() { return z; } /** * Setter of the property <tt>z</tt> * * @param z * The z to set. * @uml.property name="z" */ public void setZ(float z) { this.z = z; } public String toString() { String s = "Position X: " + this.x + "\nPosition Y: " + this.y + "\nPosition Z: " + this.z; return s; } }
package com.SearchHouse.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.SearchHouse.dao.QualityDao; import com.SearchHouse.pojo.Quality; @Repository public class QualityImpl implements QualityDao { @Autowired SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public void updateQuality(Quality quality) { // TODO Auto-generated method stub Session session=getSession(); session.update(quality); } @Override public void deleteQuality(Integer qualityId) { // TODO Auto-generated method stub Session session=getSession(); Quality quality=(Quality) session.get(Quality.class, qualityId); session.delete(quality); } @Override public Quality getQualityById(Integer qualityId) { // TODO Auto-generated method stub Session session=getSession(); Quality quality=(Quality) session.get(Quality.class, qualityId); return quality; } @Override public List<Quality> queryAllQualities() { // TODO Auto-generated method stub Session session=getSession(); Query query = session.createQuery("from Quality q left join fetch q.user"); List<Quality> qualities=query.list(); return qualities; } }
package com.alibaba.druid.bvt.sql; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.sql.PagerUtils; import com.alibaba.druid.util.JdbcConstants; public class PagerUtilsTest_Limit_oracle_0 extends TestCase { public void test_oracle_oderby_0() throws Exception { String sql = "select * from t order by id"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 0, 10); Assert.assertEquals("SELECT XX.*, ROWNUM AS RN\n" + "FROM (\n" + "\tSELECT *\n" + "\tFROM t\n" + "\tORDER BY id\n" + ") XX\n" + "WHERE ROWNUM <= 10", result); } public void test_oracle_0() throws Exception { String sql = "select * from t"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 0, 10); Assert.assertEquals("SELECT *" + // "\nFROM t" + // "\nWHERE ROWNUM <= 10", result); } public void test_oracle_1() throws Exception { String sql = "select * from t"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 10, 10); Assert.assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT XX.*, ROWNUM AS RN\n" + "\tFROM (\n" + "\t\tSELECT *\n" + "\t\tFROM t\n" + "\t) XX\n" + "\tWHERE ROWNUM <= 20\n" + ") XXX\n" + "WHERE RN > 10", result); } public void test_oracle_2() throws Exception { String sql = "select * from t"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 20, 10); Assert.assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT XX.*, ROWNUM AS RN\n" + "\tFROM (\n" + "\t\tSELECT *\n" + "\t\tFROM t\n" + "\t) XX\n" + "\tWHERE ROWNUM <= 30\n" + ") XXX\n" + "WHERE RN > 20", result); } public void test_oracle_3() throws Exception { String sql = "select id, name, salary from t order by id, name"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 20, 10); Assert.assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT XX.*, ROWNUM AS RN\n" + "\tFROM (\n" + "\t\tSELECT id, name, salary\n" + "\t\tFROM t\n" + "\t\tORDER BY id, name\n" + "\t) XX\n" + "\tWHERE ROWNUM <= 30\n" + ") XXX\n" + "WHERE RN > 20", result); } public void test_oracle_4() throws Exception { String sql = "SELECT TO_CHAR(ADD_MONTHS(TO_DATE('2014', 'yyyy'), (ROWNUM) * 12), 'yyyy') as YEAR\n" + "FROM DUAL\n" + "CONNECT BY ROWNUM <=\n" + "months_between(to_date(to_char(sysdate,'yyyy'),'yyyy') ,\n" + "to_date('2014', 'yyyy')) / 12"; String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 20, 10); Assert.assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT XX.*, ROWNUM AS RN\n" + "\tFROM (\n" + "\t\tSELECT TO_CHAR(ADD_MONTHS(TO_DATE('2014', 'yyyy'), ROWNUM * 12), 'yyyy') AS YEAR\n" + "\t\tFROM DUAL\n" + "\t\tCONNECT BY ROWNUM <= months_between(to_date(to_char(SYSDATE, 'yyyy'), 'yyyy'), to_date('2014', 'yyyy')) / 12\n" + "\t) XX\n" + "\tWHERE ROWNUM <= 30\n" + ") XXX\n" + "WHERE RN > 20", result); } }
package ar.com.trazabilidad.servicio; import java.util.List; import javax.inject.Inject; import ar.com.trazabilidad.dominio.Usuarios; import com.google.gson.Gson; import io.jsonwebtoken.Jwts; import java.util.Date; import javax.ejb.Stateless; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static ar.com.trazabilidad.util.Constants.TOKEN_EXPIRATION_TIME; import static ar.com.trazabilidad.util.Constants.SECRET_KEY; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.SignatureAlgorithm; @Path("/usuarios") @Stateless public class UsuarioServiceRS { @Inject private UsuarioServiceRemote usuarioService; /*@GET @Produces(MediaType.APPLICATION_JSON) public JsonObject listarUsuarios() { List<Usuarios> asd = usuarioService.listarUsuarios(); JsonObjectBuilder response = Json.createObjectBuilder(); response.add("estado","todo ok"); response.add("usuarios", asd.toString()); JsonObject asd1 = response.build(); return asd1; }*/ @POST @Path("/autenticarUsuario") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response usuarioAutenticado(JsonObject body){ JsonObjectBuilder msg = Json.createObjectBuilder(); Gson gson = new Gson(); try { String token = body.getString("token"); System.out.println(token); int idUsuario = Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody() .get("id",Integer.class); System.out.println("FLAG ID USUARIO RECUPERADO: "+ idUsuario); Usuarios usuario = usuarioService.encontrarUsuarioPorId(idUsuario); String json = gson.toJson(usuario); //return Response.status(Response.Status.OK).entity(token).build(); return Response.ok().entity(json).build(); } catch (Exception e) { msg.add("msg", "Usuario no esta autenticado o la sesion expiro"); return Response.status(Response.Status.BAD_REQUEST).entity(msg.build()).build(); } } @POST @Path("/validarUsuario") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response validarLogin(JsonObject body){ JsonObjectBuilder msg = Json.createObjectBuilder(); try { System.out.println("FLAG - BODY: "+body); String dni = body.getString("dni"); String pass = body.getString("password"); Usuarios usuario = usuarioService.encontrarUsuarioPorDni(Integer.parseInt(dni)); System.out.println("FLAG - USUARIO: "+usuario.toString()); if(!usuario.getPassword().equals(pass)){ msg.add("msg", "Usuario o password incorrecto"); return Response.status(Response.Status.BAD_REQUEST).entity(msg.build()).build(); } String token = generarToken(usuario); System.out.println("FLAG - TOKEN GENERADO: "+ token); msg.add("token", token); //return Response.status(Response.Status.OK).entity(token).build(); return Response.ok().entity(msg.build()).build(); } catch (Exception e) { System.out.println("FLAG ERROR - USUARIO NO EXISTE"); msg.add("msg", "Usuario o password incorrecto"); return Response.status(Response.Status.BAD_REQUEST).entity(msg.build()).build(); } } @POST @Path("/registrarUsuario") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response registrarUsuario(Usuarios usuario){ JsonObjectBuilder msg = Json.createObjectBuilder(); try { Usuarios user = usuarioService.registrarUsuario(usuario); System.out.print("FLAG - USUARIO REGISTRADO:" + user.toString()); String token = generarToken(user); msg.add("token", token); return Response.ok().entity(msg.build()).build(); } catch (Exception e) { e.printStackTrace(System.out); msg.add("msg", "Ocurrio un error con la solicitud"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg.build()).build(); } } public String generarToken(Usuarios usuario){ return Jwts.builder() .setIssuedAt(new Date()) .setSubject(usuario.getNombre()+" "+usuario.getApellido()) .setExpiration(new Date(System.currentTimeMillis() + 900000)) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .claim("id", usuario.getIdusuario()) .compact(); } }
package com.capstone.videoeffect; import android.annotation.TargetApi; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; import android.widget.ImageView; import com.capstone.videoeffect.Adapters.CreationAdapter; import com.capstone.videoeffect.utils.Glob; import java.io.File; import java.util.Collections; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; public class FragmentTabsPhotos extends Fragment { private static final int MY_REQUEST_CODE = 5; private CreationAdapter galleryAdapter; private GridView lstList; private ImageView noImage; public FragmentTabsPhotos() { // Required empty public constructor } public static FragmentTabsPhotos newInstance() { FragmentTabsPhotos fragment = new FragmentTabsPhotos(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View main_view = inflater.inflate(R.layout.fragment_tabs_photos, container, false); this.noImage = (ImageView) main_view.findViewById(R.id.novideoimg); this.lstList = (GridView) main_view.findViewById(R.id.lstList); getImages(); if (Glob.IMAGEALLARY.size() <= 0) { this.noImage.setVisibility(View.VISIBLE); this.lstList.setVisibility(View.GONE); } else { this.noImage.setVisibility(View.GONE); this.lstList.setVisibility(View.VISIBLE); } Collections.sort(Glob.IMAGEALLARY); Collections.reverse(Glob.IMAGEALLARY); this.galleryAdapter = new CreationAdapter(getActivity(), Glob.IMAGEALLARY); this.lstList.setAdapter(this.galleryAdapter); return main_view; } private void getImages() { if (Build.VERSION.SDK_INT < 23) { fetchImage(); } else if (getContext().checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) { fetchImage(); } else if (getContext().checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{"android.permission.READ_EXTERNAL_STORAGE"}, 5); } } private void fetchImage() { Glob.IMAGEALLARY.clear(); Glob.listAllImages(new File("/storage/emulated/0/" + Glob.Edit_Folder_name + "/")); } @TargetApi(23) public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 5: if (grantResults[0] == 0) { fetchImage(); return; } else if (getContext().checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{"android.permission.READ_EXTERNAL_STORAGE"}, 5); return; } else { return; } default: return; } } }
package com.gxtc.huchuan.adapter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.gxtc.commlibrary.base.BaseTitleFragment; import com.gxtc.huchuan.Constant; import java.util.List; public class CircleMainPageAdapter extends FragmentPagerAdapter { private int id; private String title [] ; private List<BaseTitleFragment> fragments; public CircleMainPageAdapter(FragmentManager fm,List<BaseTitleFragment> fragments , String title [],int id) { super(fm); this.fragments = fragments; this.title = title; this.id = id; } @Override public Fragment getItem(int position) { BaseTitleFragment fragment = fragments.get(position); Bundle bundle = new Bundle(); bundle.putInt(Constant.INTENT_DATA,id); fragment.setArguments(bundle); return fragment; } @Override public int getCount() { return fragments.size(); } @Override public CharSequence getPageTitle(int position) { return title[position]; } }
package technicalTest.impl; import java.math.BigDecimal; import technicalTest.interfaces.Offer; public class MultipleOffer implements Offer { private int count; private BigDecimal totalPrice; public MultipleOffer(int count, BigDecimal totalPrice) { this.count = count; this.totalPrice = totalPrice; } @Override public BigDecimal totalSavings(int quantity, BigDecimal itemPrice) { if (quantity < count) { return null; } else { int times = quantity / count; BigDecimal totalSave = itemPrice.multiply (new BigDecimal(times * count)).subtract(totalPrice.multiply( new BigDecimal(times))); return totalSave; } } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } @Override public int hashCode() { // TODO Auto-generated method stub return super.hashCode(); } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); } @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } }
package com.gammazero.signalrocket; import android.app.Activity; import android.app.ListActivity; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.security.acl.Group; import java.util.ArrayList; /** * Created by Jamie on 9/21/2016. */ public class GroupAdminActivity extends AppCompatActivity { private static final String TAG = "GroupAdminActivity"; private static final String PREFERENCE_FILE = "com.gammazero.signalrocket.prefs"; Menu menu; SimpleCursorAdapter mAdapter; static final String[] PROJECTION = new String[] {ContactsContract.Data._ID, ContactsContract.Data.DISPLAY_NAME}; // This is the select criteria static final String SELECTION = "((" + ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME + " != '' ))"; SharedPreferences appPrefs; SharedPreferences.Editor prefsEditor; String myUserID; String myUserName; String myGroupID; String myGroupName; String data = ""; ListView listView ; String[] values; String[] group_ids; String groupID = ""; String group_type = ""; Float zoomLevel; Double dlatitude; Double dlongitude; String group_relation = ""; String newActiveGroup = ""; String newActiveGroupID = ""; Context context; Boolean[] memberChecked = new Boolean[50]; String groupList = ""; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "Starting GroupAdminActivity"); context = this; appPrefs = PreferenceManager.getDefaultSharedPreferences(this); prefsEditor = appPrefs.edit(); Bundle extras = getIntent().getExtras(); String group_type = extras.getString("GROUP_TYPE"); // myGroupName = extras.getString("GROUP_NAME"); // myGroupID = extras.getString("GROUP_ID"); zoomLevel = extras.getFloat("ZOOMLEVEL"); dlatitude = extras.getDouble("LATITUDE"); dlongitude = extras.getDouble("LONGITUDE"); group_relation = extras.getString("GROUP_RELATION"); if (group_relation.equals("OWNER")) { setContentView(R.layout.groups_activity); } else if (group_relation.equals("MEMBER")){ setContentView(R.layout.groups_activity_member);} String group_url = ""; Context context = this; myUserName = appPrefs.getString("myUserName", ""); myUserID = appPrefs.getString("myUserID", ""); myGroupName = appPrefs.getString("myGroupName", ""); myGroupID = appPrefs.getString("myGroupID", ""); if (group_type.equals("myGroups")) { group_url = "http://www.sandbistro.com/signalrocket/getOwnedGroups.php?group_owner_id=" + myUserID; } else { group_url = "http://www.sandbistro.com/signalrocket/getMemberGroups.php?user_id=" + myUserID; } new DownloadTask().execute(group_url); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. return new CursorLoader(this, ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, null, null); } // Called when a previously created loader is reset, making the data unavailable public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } public class DownloadTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); // initialize the dialog } @Override protected String doInBackground(String... parms) { URL url = null; String Content = ""; String groupUrl = parms[0]; try { url = new URL(groupUrl ); } catch (MalformedURLException e) { e.printStackTrace(); } BufferedReader reader = null; try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the server response reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + " "); } reader.close(); Content = sb.toString(); } catch (IOException e) { e.printStackTrace(); } return Content; } protected void onPostExecute(String userData) { //if (!userData.equals("[] ")) { String group_name = ""; String group_id = ""; JSONArray jsonMainNode = null; JSONObject jsonResponse = null; JSONArray jArray = null; int lengthJsonArr = 0; /*********** Process each JSON Node ************/ /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/ /***** Returns the value mapped by name if it exists and is a JSONArray. ***/ /******* Returns null otherwise. *******/ try { //jsonResponse = new JSONObject(userData); jArray = new JSONArray(userData); lengthJsonArr = jArray.length(); if (lengthJsonArr == 0) { GoHome(); } } catch (JSONException e) { e.printStackTrace(); GoHome(); } //jsonMainNode = jsonResponse.optJSONArray("AllMyGroups"); /****************** End Parse Response JSON Data *************/ values = new String[lengthJsonArr]; group_ids = new String[lengthJsonArr]; JSONObject jObject = null; for (int i = 0; i < lengthJsonArr; i++) { /****** Get Object for each JSON node.***********/ try { jObject = jArray.getJSONObject(i); values[i] = jObject.getString("name"); group_ids[i] = jObject.getString("id"); try { String owner_name = jObject.getString("owner_name"); values[i] = values[i] + " / " + owner_name; prefsEditor.putString(values[i], group_ids[i]); if (! prefsEditor.commit()) { Toast.makeText(context, "Groups save failed", Toast.LENGTH_LONG).show(); } } catch (Exception e) { values[i] = values[i]; prefsEditor.putString(values[i], group_ids[i]); if (! prefsEditor.commit()) { Toast.makeText(context, "Groups save failed", Toast.LENGTH_LONG).show(); } } } catch (NullPointerException npe) { Log.e(TAG, npe.getMessage()); values[i] = "Not currently a member of any groups"; group_ids[i] = null; } catch (JSONException e) { Log.e(TAG, e.getMessage()); GoHome(); } } listView = (ListView) findViewById(R.id.mobile_list); ArrayAdapter adapter = new ArrayAdapter<String>(GroupAdminActivity.this,R.layout.group_activity_listview, values); listView.setAdapter(adapter); registerForContextMenu(listView); // ListView Item Click Listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // ListView Clicked item index if (memberChecked[position] == null) { memberChecked[position] = true; } else if (memberChecked[position]) { memberChecked[position] = false; } else if (!memberChecked[position]) { memberChecked[position] = true; } if (memberChecked[position]) { groupList = groupList + group_ids[position] + ":" ; listView.getChildAt(position).setBackgroundColor(Color.parseColor("#aaaaaa")); } else if (!memberChecked[position]) { groupList = groupList.replace(group_ids[position], ""); listView.getChildAt(position).setBackgroundColor(Color.TRANSPARENT); } // ListView Clicked item value // final String itemValue = (String) listView.getItemAtPosition(position); } }); } } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.group_long_press_menu, menu); } @Override public boolean onContextItemSelected(final MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int id = (int) info.id; final String groupName = (String) listView.getItemAtPosition(id); final String groupID = group_ids[id]; switch (item.getItemId()) { case R.id.list_members: Intent UserAdminIntent = new Intent(getBaseContext(), UserAdminActivity.class); Bundle extras = getIntent().getExtras(); UserAdminIntent.putExtra("ZOOMLEVEL", extras.getFloat("ZOOMLEVEL")); UserAdminIntent.putExtra("LATITUDE", extras.getDouble("LATITUDE")); UserAdminIntent.putExtra("LONGITUDE", extras.getDouble("LONGITUDE")); UserAdminIntent.putExtra("GROUP_RELATION", group_relation); UserAdminIntent.putExtra("GROUP_NAME", groupName); UserAdminIntent.putExtra("GROUP_ID", groupID); startActivity(UserAdminIntent); return true; case R.id.make_active: prefsEditor.putString("myGroupName", groupName); prefsEditor.putString("myGroupID", groupID); prefsEditor.commit(); // appPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (! prefsEditor.commit()) { Toast.makeText(context, "Preference save failed", Toast.LENGTH_LONG).show(); } Intent mainIntent = new Intent(getBaseContext(), MapsActivity.class); extras = getIntent().getExtras(); mainIntent.putExtra("ZOOMLEVEL", extras.getFloat("ZOOMLEVEL")); mainIntent.putExtra("LATITUDE", extras.getDouble("LATITUDE")); mainIntent.putExtra("LONGITUDE", extras.getDouble("LONGITUDE")); startActivity(mainIntent); return true; case R.id.go_home: Intent mapsIntent = new Intent(getBaseContext(), MapsActivity.class); extras = getIntent().getExtras(); mapsIntent.putExtra("ZOOMLEVEL", extras.getFloat("ZOOMLEVEL")); mapsIntent.putExtra("LATITUDE", extras.getDouble("LATITUDE")); mapsIntent.putExtra("LONGITUDE", extras.getDouble("LONGITUDE")); startActivity(mapsIntent); } return true; } private void GoHome() { Intent MapsActivityIntent = new Intent(getBaseContext(), MapsActivity.class); Bundle extras = getIntent().getExtras(); MapsActivityIntent.putExtra("ZOOMLEVEL", extras.getFloat("ZOOMLEVEL")); MapsActivityIntent.putExtra("LATITUDE", extras.getDouble("LATITUDE")); MapsActivityIntent.putExtra("LONGITUDE", extras.getDouble("LONGITUDE")); startActivity(MapsActivityIntent); } //================================================================================================== @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); if (group_relation.equals("OWNER")) { inflater.inflate(R.menu.my_groups_menu, menu); } else { inflater.inflate(R.menu.group_member_menu, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { // case R.id.main_activity: // Intent mainIntent = new Intent(this, MainActivity.class); // startActivity(mainIntent); // return true; case R.id.preferences_activity: Intent preferencesIntent = new Intent(this, MyPreferencesActivity.class); preferencesIntent.putExtra("ZOOMLEVEL", zoomLevel); preferencesIntent.putExtra("LATITUDE", dlatitude); preferencesIntent.putExtra("LONGITUDE", dlongitude); startActivity(preferencesIntent); return true; case R.id.main_activity: Intent mainIntent = new Intent(this, MapsActivity.class); mainIntent.putExtra("ZOOMLEVEL", zoomLevel); mainIntent.putExtra("LATITUDE", dlatitude); mainIntent.putExtra("LONGITUDE", dlongitude); return true; case R.id.create_group: new CreateNewGroup().execute(myUserID); return true; case R.id.delete_group: deleteGroup(groupList); return true; } return true; } //================================================================================================== public class CreateNewGroup extends AsyncTask<String, Void, String[]> { String response = ""; protected void onPreExecute(final String user_id) { super.onPreExecute(); setContentView(R.layout.create_new_group_activity); Button new_group = (Button) findViewById(R.id.new_group_button); // final EditText my_user_name = (EditText) findViewById(R.id.my_user_name); final EditText my_group_name = (EditText) findViewById(R.id.new_group_name); new_group.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // myUserName = my_user_name.getText().toString(); String newGroupName = my_group_name.getText().toString(); String[] new_group_info = new String[2]; new_group_info[0] = user_id; new_group_info[1] = newGroupName; new CreateNewGroup().execute(new_group_info); } }); // initialize the dialog } protected String[] doInBackground(String[] parms) { URL url = null; String[] groupInfo = new String[2]; String userId = parms[0]; groupInfo[1] = parms[1]; String groupName = ""; try { groupName = URLEncoder.encode(parms[1], "UTF-8"); url = new URL("http://www.sandbistro.com/signalrocket/createGroup.php?user_id=" + userId + "&group_name=" + groupName); } catch (MalformedURLException e) { Log.d(TAG, e.getMessage()); } catch (UnsupportedEncodingException uee) { Log.d(TAG, uee.getMessage()); } BufferedReader reader = null; try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the server response reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + " "); } reader.close(); groupInfo[0] = sb.toString(); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } return groupInfo; } @Override protected void onPostExecute (String[] result){ /*********** Process each JSON Node ************/ if (! result[1].equals("Error")) { Toast.makeText(getApplicationContext(), "New group created", Toast.LENGTH_LONG).show(); prefsEditor.putString(result[1], result[0]); prefsEditor.commit(); } else { Toast.makeText(getApplicationContext(), "Failed to create new group", Toast.LENGTH_LONG).show(); } Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class); mapsIntent.putExtra("ZOOMLEVEL", zoomLevel); mapsIntent.putExtra("LATITUDE", dlatitude); mapsIntent.putExtra("LONGITUDE", dlongitude); startActivity(mapsIntent); } } //================================================================================================== public void deleteGroup(String groupList) { if (groupList.equals("")) { Toast.makeText(this, "No groups selected to delete", Toast.LENGTH_LONG).show(); } else { new DeleteGroup().execute(groupList); } } public class DeleteGroup extends AsyncTask<String, Void, String> { String response = ""; @Override protected void onPreExecute() { super.onPreExecute(); // initialize the dialog } protected String doInBackground(String... parms) { String result = ""; BufferedReader reader; String groupIds= parms[0]; try { // initialize the dialog String data = ""; String groupIDs = URLEncoder.encode(groupIds, "UTF-8"); URL url = new URL("http://www.sandbistro.com/signalrocket/deleteGroups.php?groupList=" + groupIDs); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the server response reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + " "); } reader.close(); result = sb.toString(); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } return result; } protected void onPostExecute (String result){ /*********** Process each JSON Node ************/ if (result.startsWith("Success")) { Toast.makeText(getApplicationContext(), "Groups deleted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Failed to delete groups", Toast.LENGTH_LONG).show(); } Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class); mapsIntent.putExtra("ZOOMLEVEL", zoomLevel); mapsIntent.putExtra("LATITUDE", dlatitude); mapsIntent.putExtra("LONGITUDE", dlongitude); startActivity(mapsIntent); } } //================================================================================================== public class GetGroupId extends AsyncTask<String, Void, String[]> { public void onPreExecute() { super.onPreExecute(); } public String[] doInBackground(String[] parms) { String[] result = new String[2]; URL url = null; String userID = parms[0]; String groupName = parms[1]; try { String myUserName = URLEncoder.encode(groupName, "UTF-8"); url = new URL("http://www.sandbistro.com/signalrocket/getGroupID.php?user_id=" + userID + "&group_name=" + groupName); } catch (MalformedURLException e) { Log.d(TAG, e.getMessage()); } catch (UnsupportedEncodingException uee) { Log.d(TAG, uee.getMessage()); } BufferedReader reader = null; try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the server response reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + " "); } reader.close(); result[0] = sb.toString(); result[1] = groupName; } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } return result; } public void onPostExecute(String[] result) { if (result[1].equals("Error")) { Toast.makeText(getApplicationContext(), "Error activating group", Toast.LENGTH_LONG).show(); } else { appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); prefsEditor = appPrefs.edit(); prefsEditor.putString("myGroupID", result[0]); prefsEditor.putString("myGroupName", result[1]); prefsEditor.commit(); } Intent mainIntent = new Intent(getApplicationContext(), MapsActivity.class); mainIntent.putExtra("ZOOMLEVEL", zoomLevel); mainIntent.putExtra("LATITUDE", dlatitude); mainIntent.putExtra("LONGITUDE", dlongitude); startActivity(mainIntent); } } }
//package DisasterAlert; // //import java.io.BufferedReader; //import java.io.BufferedWriter; //import java.io.File; //import java.io.FileReader; //import java.io.FileWriter; //import java.io.IOException; //import java.text.ParseException; //import java.text.SimpleDateFormat; //import java.util.Date; // //public class DigLogCounter { // // protected static final SimpleDateFormat YMD = new SimpleDateFormat("yyyy-MM-dd");//change time format // // public static void dislogcount(File in, File out) throws IOException, ParseException{ // BufferedReader br = new BufferedReader(new FileReader(in)); // BufferedWriter bw = new BufferedWriter(new FileWriter(out)); // String line = br.readLine(); // while((line = br.readLine())!= null){ // String[] tokens = line.split(","); // String[] ymd = tokens[0].split("/"); // String daytime = ymd[2]; // String[] d_t = daytime.split(" "); // String dt = ymd[0]+"-"+ymd[1]+"-"+d_t[0]; // Date disdate = YMD.parse(dt); // String type = tokens[1]; // // } // br.close(); // bw.close(); // } // //}
package com.seva.framework.login; import java.util.ArrayList; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.seva.Persistence.UserDAO; import com.seva.models.LoginDTO; @Service("userDetailsServiceTx") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserDAO userDAO; /** * To load user details. */ @Override public UserDetails loadUserByUsername(String username) { LoginDTO loginDTO = null; loginDTO = userDAO.fetchLoginCredentialsByLoginId(username); if (loginDTO == null) { throw new UsernameNotFoundException("user not found"); } return populateUserEntity(loginDTO); } /** * for (SecurityRoleEntity role : userEntity.getRoles()) { * authorities.add(new GrantedAuthorityImpl(role.getRoleName())); } * * @param loginVO * @return */ private User populateUserEntity(LoginDTO loginVO) { String username = loginVO.getUserId(); String password = loginVO.getUserPassword(); boolean enabled = true; boolean accountNonExpired = enabled; boolean credentialsNonExpired = enabled; boolean accountNonLocked = enabled; Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_APP")); User user = new UserImpl(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); return user; } }
package com.example.demo.application.server; import com.example.demo.Constant; import com.auth0.jwt.JWTVerifier; import io.grpc.*; import java.util.Map; public class JwtServerInterceptor implements ServerInterceptor { private static final ServerCall.Listener NOOP_LISTENER = new ServerCall.Listener() { }; private final String secret; private final JWTVerifier verifier; public JwtServerInterceptor(String secret) { this.secret = secret; this.verifier = new JWTVerifier(secret); } @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) { String jwt = metadata.get(Constant.JWT_METADATA_KEY); if (jwt == null) { serverCall.close(Status.UNAUTHENTICATED.withDescription("JWT Token is missing from Metadata"), metadata); return NOOP_LISTENER; } Context ctx; try { Map<String, Object> verified = verifier.verify(jwt); ctx = Context.current().withValue(Constant.USER_ID_CTX_KEY, verified.getOrDefault("sub", "anonymous").toString()) .withValue(Constant.JWT_CTX_KEY, jwt); } catch (Exception e) { System.out.println("Verification failed - Unauthenticated!"); serverCall.close(Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e), metadata); return NOOP_LISTENER; } return Contexts.interceptCall(ctx, serverCall, metadata, serverCallHandler); } }
package cn.edu.cqut.controller; import org.springframework.web.bind.annotation.CrossOrigin; 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.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import cn.edu.cqut.entity.Menu; import cn.edu.cqut.entity.Role; import cn.edu.cqut.service.IMenuService; import cn.edu.cqut.service.IRoleService; import cn.edu.cqut.util.CrmResult; import io.swagger.annotations.ApiParam; import springfox.documentation.annotations.ApiIgnore; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * <p> * 前端控制器 * </p> * * @author CQUT SE 2020 * @since 2020-06-10 */ @RestController @CrossOrigin @RequestMapping("/menu") public class MenuController { @Autowired private IMenuService iMenuService; @RequestMapping(value = "/search") public CrmResult<Menu> getAllMenu( @ApiParam(value = "要查询的页码", required = true) @RequestParam(defaultValue = "1") Integer page, //page请求的页码,默认为1 @ApiParam(value = "每页的行数", required = true) @RequestParam(defaultValue = "8") Integer limit,//limit每页的行数,默认为10 Menu menu) { QueryWrapper<Menu> qw = new QueryWrapper<>(); if (menu.getName() != null && menu.getStage() != null) { qw.like("name", menu.getName()); qw.or(); qw.like("stage", menu.getStage()); //第一个参数是字段名 } Page<Menu> pageMenu = iMenuService.page( new Page<>(page, limit), qw); CrmResult<Menu> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg(""); ret.setCount(pageMenu.getTotal());//表里的记录总数 ret.setData(pageMenu.getRecords()); //这页的数据列表 return ret; } // 自定义方法 @ApiIgnore @RequestMapping(value="/selectParent",method = RequestMethod.GET) public CrmResult<Menu> selectFirstMenu(Integer parentId){ CrmResult<Menu> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg(""); // ret.setCount(pageMenu.getTotal());//表里的记录总数 ret.setData(iMenuService.selectFirstMenu(parentId)); //这页的数据列表 return ret; } @ApiIgnore @RequestMapping("/update") public CrmResult<Menu> updateMenu(Menu menu) { iMenuService.updateById(menu); //根据主键更新表 CrmResult<Menu> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("更新菜单成功"); return ret; } @ApiIgnore @RequestMapping("/add") public CrmResult<Menu> addMenu(Menu menu) { iMenuService.save(menu); CrmResult<Menu> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("新增菜单成功"); return ret; } @ApiIgnore @RequestMapping("/del") public CrmResult<Menu> delMenu(String[] ids) { iMenuService.removeByIds(Arrays.asList(ids)); CrmResult<Menu> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("删除成功"); return ret; } }
package com.company; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Kitchen extends JFrame{ private JButton mantiButton; private JButton borschtButton; private JPanel Kitchen; private JButton pilafButton; private JTable table1; private JButton lagmanButton; private JButton backButton; private JFormattedTextField formattedTextField1; private JTextField totalPrice; public JPanel getKitchen(){ return Kitchen; } public Kitchen() { CreateTable(); add(Kitchen); setTitle("Kitchen Menu"); setSize(400, 500); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); MainMenu mainMenu = new MainMenu(); mainMenu .setVisible(true); } }); pilafButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); } public void CreateTable(){ Object[][] data = { {"Pilaf",700}, {"Lagman",1000}, {"Manti",600}, {"Borscht",500} }; DefaultTableModel model = (DefaultTableModel) table1.getModel(); //Object[] columns = {"Name","Price"}; model.setDataVector(data,new String[] {"Name","Price","sad"}); table1.setTableHeader(null); table1.getTableHeader(); } }
package testfxml; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Plant implements ICrosser { private final double Weight = 5.0 ; private final int EatingRank = 0 ; private BufferedImage[] imgs = new BufferedImage[5]; @Override public boolean canSail() { return false; } @Override public double getWeight() { // TODO Auto-generated method stub return this.Weight; } @Override public int getEatingRank() { // TODO Auto-generated method stub return this.EatingRank; } @Override public BufferedImage[] getImages() { try { imgs[0] = ImageIO.read(new File("images/plantLeft.png")); imgs[1] = ImageIO.read(new File("images/plantRight.png")); }catch(IOException e) { e.printStackTrace(); } return imgs; } @Override public ICrosser makeCopy() { // TODO Auto-generated method stub return null; } @Override public void setLabelToBeShown(String label) { // TODO Auto-generated method stub } @Override public String getLabelToBeShown() { // TODO Auto-generated method stub return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.toolkit.plugin; import java.io.IOException; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.apache.servicecomb.toolkit.common.ContractComparator; import org.apache.servicecomb.toolkit.common.ContractsUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Mojo(name = "verifyContracts", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE) @Execute(goal = "verifyContracts", phase = LifecyclePhase.COMPILE ) public class VerifyContractsMojo extends AbstractMojo { private final static Logger LOGGER = LoggerFactory.getLogger(VerifyContractsMojo.class); @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; @Parameter(defaultValue = "contracts") private String outputDir; @Parameter(defaultValue = ".yaml") private String format; @Parameter(defaultValue = "sourceContracts") private String sourceContractsDir; @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("outputDir : " + outputDir); ContractGenerator contractGenerator = new ContractGenerator(project); contractGenerator.generateAndOutput(outputDir, format); try { Map<String, byte[]> currentContracts = ContractsUtils.getFilesGroupByFilename(outputDir); Map<String, byte[]> sourceContracts = ContractsUtils.getFilesGroupByFilename(sourceContractsDir); currentContracts.forEach((contractName, swagger) -> { byte[] sourceSwagger = sourceContracts.get(contractName); ContractComparator contractComparator = new ContractComparator(new String(sourceSwagger), new String(swagger)); if (!contractComparator.equals()) { getLog().info("contract is not matched, difference is as follows"); getLog().info(sourceContractsDir + "/" + contractName + " vs " + outputDir + "/" + contractName); contractComparator.splitPrintToScreen(); } else { getLog().info("succee, contract verification passed"); } }); } catch (IOException e) { LOGGER.error(e.getMessage()); } } }
package com.dbs.db.dao; public enum FieldType { String ("String"), Long ("Long"), Integer ("Integer"), BigDecimal ("BigDecimal"), Boolean ("Boolean"), Time ("Time"), Timestamp ("Timestamp"), Date ("Date"); private FieldType(String type){ this.type = type; } private String type; public String getType(){ return this.type; } }
/* * 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 logico; import java.util.ArrayList; import java.util.Iterator; public class Categoria { String codigo; String nombre; ArrayList<SubCategoria> subCategorias; /** * El constructor pide como parámetros el código de la categoría y el * nombre. El constructor además, instancia el ArrayList de subcategorias. * * @param codigo * @param nombre */ public Categoria(String codigo, String nombre) { this.codigo = codigo; this.nombre = nombre; subCategorias = new ArrayList<>(); } /** * Método que se encarga de añadir un objecto producto proveniente de la * lectura de acrhivos a una subcategoria. * * @param producto * @param codigoSubCategoria */ public void addProducto(Producto producto, String codigoSubCategoria) { Iterator<SubCategoria> it = this.subCategorias.iterator(); while (it.hasNext()) { SubCategoria sub = it.next(); if (sub.getCodigo().equals(codigoSubCategoria)) { sub.addProducto(producto); } } } /** * Método el cual se encarga de añadir un nuevo producto a una Sub Categoria * especifica. Retornara true si se añadio correctamente y retornara false * si esto no se realizó. * * @param nombreSubCategoria * @param nombreProducto * @param precio * @return boolean */ public boolean addNewProducto(String nombreSubCategoria, String nombreProducto, int precio) { boolean estado = false; Iterator<SubCategoria> it = this.subCategorias.iterator(); while (it.hasNext()) { SubCategoria sub = it.next(); if (sub.getNombre().equals(nombreSubCategoria)) { sub.addNewProducto(nombreProducto, precio); estado = true; } } return estado; } /** * Método para agregar una nueva subcategoría dentro de la categoría. * * @param subCategoria */ public void addSubCategoria(SubCategoria subCategoria) { this.subCategorias.add(subCategoria); } /** * Retorna el código de la categoría. * * @return int */ public String getCodigo() { return this.codigo; } /** * Retorna el nombre de la categoría. * * @return String */ public String getNombre() { return this.nombre; } /** * Retorna el arreglo de Sub Categorias. * * @return */ public ArrayList<SubCategoria> getSubCategorias() { return this.subCategorias; } }
package jenkins.plugins.office365connector; import static jenkins.plugins.office365connector.Office365ConnectorWebhookNotifierIntegrationTest.mockJob; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import hudson.model.Job; import hudson.model.Run; import hudson.model.TaskListener; import hudson.scm.ChangeLogSet; import mockit.Deencapsulation; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author Damian Szczepanik (damianszczepanik@github) */ public class Office365ConnectorWebhookNotifierTest { private static final String CUSTOM_RUN_NAME = "myCustomRunName"; private static final String JOB_NAME = "myFirstJob"; private static final String MULTI_BRANCH_NAME = "myFirstMultiBranchProject"; @Rule public ExpectedException thrown = ExpectedException.none(); private Run run; private TaskListener listener; @Before public void setUp() { run = mock(Run.class); listener = mock(TaskListener.class); } @Test public void getAffectedFiles_ReturnsAffectedFiles() { // given ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class); Object patternFiles = Collections.emptyList(); doReturn(patternFiles).when(entry).getAffectedFiles(); Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, listener); // when, Collection<ChangeLogSet.AffectedFile> files = Deencapsulation.invoke(notifier, "getAffectedFiles", entry); // then verify(entry, times(1)).getAffectedFiles(); assertThat(files).isSameAs(patternFiles); } @Test public void getAffectedFiles_OnException_ReturnsEmptyCollection() { // given PrintStream stream = mock(PrintStream.class); when(listener.getLogger()).thenReturn(stream); ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class); when(entry.getAffectedFiles()).thenThrow(UnsupportedOperationException.class); Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, listener); // when, Collection<ChangeLogSet.AffectedFile> files = Deencapsulation.invoke(notifier, "getAffectedFiles", entry); // then verify(entry, times(1)).getAffectedFiles(); assertThat(files).isEmpty(); } @Test public void getDisplayName_ParentWithoutName() { // given Job job = mockJob(""); when(run.getParent()).thenReturn(job); Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, listener); // when, String getDisplayName = Deencapsulation.invoke(notifier, "getDisplayName"); // then assertThat(getDisplayName).isEqualTo(JOB_NAME); } @Test public void getDisplayName_ParentWithName() { // given Job job = mockJob(MULTI_BRANCH_NAME); when(run.getParent()).thenReturn(job); Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, listener); // when, String getJobDisplayName = Deencapsulation.invoke(notifier, "getDisplayName"); // then assertThat(getJobDisplayName).isEqualTo(MULTI_BRANCH_NAME + " » " + JOB_NAME); } @Test public void getDisplayName_RunWithCustomName() throws Exception { // given when(run.hasCustomDisplayName()).thenReturn(true); when(run.getDisplayName()).thenReturn(CUSTOM_RUN_NAME); Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, listener); // when, String getDisplayName = Deencapsulation.invoke(notifier, "getDisplayName"); // then assertThat(getDisplayName).isEqualTo(CUSTOM_RUN_NAME); } }
package com.example.TRUsell; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity { private Button loginButton; private EditText emailET, passwET; private ProgressDialog progress; private Button createAccountLinkButton; private FirebaseAuth firebaseAuth; private ImageView googleIV, phoneIV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); createAccountLinkButton = findViewById(R.id.login_register_button); emailET = findViewById(R.id.login_email_ET); passwET = findViewById(R.id.login_pass_ET); loginButton = findViewById(R.id.login_account_button); progress = new ProgressDialog(this); firebaseAuth = FirebaseAuth.getInstance(); createAccountLinkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendToSignUpActivity(); } }); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AttemptLogin(); } }); } private void AttemptLogin() { String email = emailET.getText().toString(); String password = passwET.getText().toString(); if(TextUtils.isEmpty(email)) { Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(password)) { Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show(); } else { progress.setTitle("Login"); progress.setMessage("Please wait, while we attempt to login"); progress.setCanceledOnTouchOutside(true); progress.show(); firebaseAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { SendToMainActivity(); Toast.makeText(LoginActivity.this, "Logged In successfully!", Toast.LENGTH_SHORT).show(); progress.dismiss(); } else { String message = task.getException().getMessage(); Toast.makeText(LoginActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show(); progress.dismiss(); } } }); } } @Override protected void onStart() { super.onStart(); FirebaseUser currentUser = firebaseAuth.getCurrentUser(); if(currentUser != null) { SendToMainActivity(); } } private void SendToMainActivity() { Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } private void sendToSignUpActivity() { Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class); startActivity(loginIntent); } }
public class 구구단 { public static void main(String[] args) { // for (int i = 0; i < 9; i++) { int number1 = i + 1; System.out.println("\n" + number1 + "단"); for (int j = 0; j < 9; j++) { int number2 = j + 1; int result = number1 + number2; System.out.println(number1 + "X" + number2 + "=" + result); } } } } // 39 + 4 = 43 // "" + 39 + 4 = "394"
package controllers.message; import java.util.ArrayList; import java.util.Collection; import javax.swing.JOptionPane; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import controllers.AbstractController; import services.ActorService; import services.MessageBoxService; import services.MessageService; import services.PriorityService; import domain.Actor; import domain.Message; import domain.MessageBox; import domain.Priority; @Controller @RequestMapping("/message") public class MessageController extends AbstractController { @Autowired private MessageService messageService; @Autowired private ActorService actorService; @Autowired private MessageBoxService messageBoxService; @Autowired private PriorityService priorityService; @ExceptionHandler(TypeMismatchException.class) public ModelAndView handleMismatchException(final TypeMismatchException oops) { JOptionPane.showMessageDialog(null, "Forbidden operation"); return new ModelAndView("redirect:/"); } @InitBinder protected void initBinder(final WebDataBinder binder) { binder.registerCustomEditor(Collection.class, "recipients", new CustomCollectionEditor(Collection.class) { @Override protected Object convertElement(final Object element) { Integer id = null; if (element instanceof String && !((String) element).equals("")) //From the JSP 'element' will be a String try { id = Integer.parseInt((String) element); } catch (final NumberFormatException e) { System.out.println("Element was " + ((String) element)); e.printStackTrace(); } else if (element instanceof Integer) //From the database 'element' will be a Long id = (Integer) element; return id != null ? MessageController.this.actorService.findOne(id) : null; } }); } // List ------------------------------------------------------------- @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView list(@RequestParam final int messageBoxID) { final ModelAndView result; Collection<Message> messages; MessageBox msgBox; try { final Actor principal = this.actorService.getActorLogged(); msgBox = this.messageBoxService.findOne(messageBoxID); Assert.isTrue(principal.getBoxes().contains(msgBox)); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } messages = this.messageService.findAllByMessageBox(messageBoxID); result = new ModelAndView("message/list"); result.addObject("messageBox", messageBoxID); result.addObject("nestedBoxes", msgBox.getSons()); result.addObject("messages", messages); result.addObject("requestURI", "message/list.do"); return result; } // Create ----------------------------------------------------------- @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView create() { ModelAndView result; Message mesage; mesage = this.messageService.create(); result = this.createModelAndView(mesage); return result; } // Create Broadcast ------------------------------------------------------------------------ @RequestMapping(value = "/broadcast", method = RequestMethod.GET) public ModelAndView broadcast() { ModelAndView result; Message mesage; mesage = this.messageService.create(); final Collection<Priority> priorityList = this.priorityService.findAll(); result = new ModelAndView("message/broadcast"); result.addObject("mesage", mesage); result.addObject("priorityList", priorityList); return result; } // Send Broadcast ------------------------------------------------------------- @RequestMapping(value = "/broadcast", method = RequestMethod.POST, params = "send") public ModelAndView sendBroadcast(@ModelAttribute("mesage") final Message mesage, final BindingResult binding) { ModelAndView result; Message msg; try { mesage.setRecipients(this.actorService.findAll()); msg = this.messageService.reconstruct(mesage, binding); if (binding.hasErrors()) result = this.createModelAndView(mesage); else { this.messageService.save(msg); final int messageBoxID = this.actorService.getActorLogged().getMessageBox("OUTBOX").getId(); result = new ModelAndView("redirect:list.do?messageBoxID=" + messageBoxID + ""); } } catch (final Throwable oops) { result = this.createModelAndView(mesage, "message.commit.error"); } return result; } // Send ------------------------------------------------------------- @RequestMapping(value = "/create", method = RequestMethod.POST, params = "save") public ModelAndView save(@ModelAttribute("mesage") final Message mesage, final BindingResult binding) { ModelAndView result; Message msg; try { msg = this.messageService.reconstruct(mesage, binding); if (binding.hasErrors()) result = this.createModelAndView(mesage); else { this.messageService.save(msg); final int messageBoxID = this.actorService.getActorLogged().getMessageBox("OUTBOX").getId(); result = new ModelAndView("redirect:list.do?messageBoxID=" + messageBoxID + ""); } } catch (final Throwable oops) { result = this.createModelAndView(mesage, "message.commit.error"); } return result; } // Display --------------------------------------- @RequestMapping(value = "/display", method = RequestMethod.GET) public ModelAndView display(@RequestParam final int messageID, @RequestParam final int messageBoxID) { ModelAndView result; Message message; MessageBox msgBox; Collection<MessageBox> actorBoxes; try { final Actor principal = this.actorService.getActorLogged(); msgBox = this.messageBoxService.findOne(messageBoxID); message = this.messageService.findOne(messageID); Assert.isTrue(principal.getBoxes().contains(msgBox)); Assert.isTrue(principal.getMessageBox(msgBox.getName()).getMessages().contains(message)); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } final Collection<MessageBox> messageBoxes = new ArrayList<MessageBox>(); message = this.messageService.findOne(messageID); actorBoxes = this.messageBoxService.findAllByActor(this.actorService.getActorLogged().getId()); for (final MessageBox b : actorBoxes) if (!b.getMessages().contains(message) && b.getIsSystem() == false) messageBoxes.add(b); result = new ModelAndView("message/display"); result.addObject("messageBoxes", messageBoxes); result.addObject("messageBoxID", messageBoxID); result.addObject("mesage", message); result.addObject("mesageRecipients", message.getRecipients()); return result; } // Delete ------------------------------------------------------ @RequestMapping(value = "/delete", method = RequestMethod.GET) public ModelAndView delete(@RequestParam final int messageID, @RequestParam final int messageBoxID) { ModelAndView result; MessageBox messageBox; Message message; try { try { final Actor principal = this.actorService.getActorLogged(); messageBox = this.messageBoxService.findOne(messageBoxID); message = this.messageService.findOne(messageID); Assert.isTrue(principal.getBoxes().contains(messageBox)); Assert.isTrue(principal.getMessageBox(messageBox.getName()).getMessages().contains(message)); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } this.messageService.delete(message, messageBox); result = new ModelAndView("redirect:list.do?messageBoxID=" + messageBoxID + ""); result.addObject("messageBox", messageBoxID); } catch (final Throwable oops) { message = this.messageService.findOne(messageID); result = this.createModelAndView(message, "messageBox.commit.error"); } return result; } // Move ------------------------------------------------------ @RequestMapping(value = "/move", method = RequestMethod.GET) public ModelAndView move(@RequestParam final int messageID, @RequestParam final int srcBoxID, @RequestParam final int destBoxID) { ModelAndView result; MessageBox srcBox; MessageBox destBox; Message message; try { try { final Actor principal = this.actorService.getActorLogged(); srcBox = this.messageBoxService.findOne(srcBoxID); destBox = this.messageBoxService.findOne(destBoxID); message = this.messageService.findOne(messageID); Assert.isTrue(principal.getBoxes().contains(srcBox)); Assert.isTrue(principal.getMessageBox(srcBox.getName()).getMessages().contains(message)); Assert.isTrue(principal.getBoxes().contains(destBox)); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } this.messageService.moveMessage(message, srcBox, destBox); result = new ModelAndView("redirect:list.do?messageBoxID=" + destBoxID + ""); result.addObject("messageBox", srcBoxID); } catch (final Throwable oops) { message = this.messageService.findOne(messageID); result = this.createModelAndView(message, "messageBox.commit.error"); } return result; } // Copy ------------------------------------------------------ @RequestMapping(value = "/copy", method = RequestMethod.GET) public ModelAndView copy(@RequestParam final int messageID, @RequestParam final int srcBoxID, @RequestParam final int destBoxID) { ModelAndView result; MessageBox srcBox; MessageBox destBox; Message message; try { try { final Actor principal = this.actorService.getActorLogged(); srcBox = this.messageBoxService.findOne(srcBoxID); destBox = this.messageBoxService.findOne(destBoxID); message = this.messageService.findOne(messageID); Assert.isTrue(principal.getBoxes().contains(srcBox)); Assert.isTrue(principal.getMessageBox(srcBox.getName()).getMessages().contains(message)); Assert.isTrue(principal.getBoxes().contains(destBox)); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } this.messageService.copyMessage(message, srcBox, destBox); result = new ModelAndView("redirect:list.do?messageBoxID=" + destBoxID + ""); result.addObject("messageBox", srcBoxID); } catch (final Throwable oops) { message = this.messageService.findOne(messageID); result = this.createModelAndView(message, "messageBox.commit.error"); } return result; } // Ancillary methods ------------------------------------------------------ protected ModelAndView createModelAndView(final Message mesage) { ModelAndView result; result = this.createModelAndView(mesage, null); return result; } protected ModelAndView createModelAndView(final Message mesage, final String message) { ModelAndView result; final Collection<Actor> actorList = this.actorService.findAll(); final Collection<Priority> priorityList = this.priorityService.findAll(); result = new ModelAndView("message/create"); result.addObject("mesage", mesage); result.addObject("message", message); result.addObject("priorityList", priorityList); result.addObject("actorList", actorList); return result; } private ModelAndView forbiddenOperation() { return new ModelAndView("redirect:/messageBox/list.do"); } }
import java.util.Arrays; /** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-12 * Time: 上午9:33 * To change this template use File | Settings | File Templates. */ public class DynamicMedian<Key extends Comparable<Key>> { private MaxPQ<Key> maxPQ; private MinPQ<Key> minPQ; private Key _median; public DynamicMedian() { maxPQ = new MaxPQ<Key>(); minPQ = new MinPQ<Key>(); } public void insert(Key item) { if(maxPQ.size() == 0 && minPQ.size() == 0) { maxPQ.insert(item); _median = item; return; } if(item.compareTo(_median) >= 0) minPQ.insert(item); else maxPQ.insert(item); if(maxPQ.size() < minPQ.size()) { _median = minPQ.delMin(); maxPQ.insert(_median); }else if(maxPQ.size() > minPQ.size() + 1) { minPQ.insert(maxPQ.delMax()); _median = maxPQ.max(); } } public void delMedian() { maxPQ.delMax(); if(maxPQ.size() < minPQ.size()) { _median = minPQ.delMin(); maxPQ.insert(_median); } else _median = minPQ.min(); } public Key median() { return _median; } public static void main(String[] args) { DynamicMedian<Integer> dynamicMedian = new DynamicMedian<Integer>(); int N = 3; Integer[] a = new Integer[N]; for(int i = 0; i < N; ++i) a[i] = i; StdRandom.shuffle(a); StdOut.println(Arrays.toString(a)); for(int i = 0; i < N; ++i) { dynamicMedian.insert(a[i]); StdOut.println(dynamicMedian.median()); } } }
package br.com.fiap.dao; import java.util.List; import br.com.fiap.entity.Cliente; public interface ClienteDAO extends DAO<Cliente,Integer>{ List<Cliente> listar(); List<Cliente> buscarPorNome(String nome); List<Cliente> buscarPorEstado(String uf); List<Cliente> buscarPorDiasReserva(int dias); List<Object[]> buscarNomeCPF(String nome); Long contarTotal(); List<Cliente> getClientePorNome(String nome, String cidade); List<Cliente> getClientePorEstado(List<String> estados); }
package com.mahang.weather.util; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; public class PermissionUtils { private PermissionUtils() { } @TargetApi(Build.VERSION_CODES.M) public static boolean requestLocationPermission(Activity activity){ if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED){ ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0); return false; } else { return true; } } }
package com.juilyoon.discoverwaterloo; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); // Set up TabLayout TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.setupWithViewPager(mViewPager); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** Lists of attractions */ private ArrayList<Location> restaurantList = new ArrayList<>(); private ArrayList<Location> activityList = new ArrayList<>(); private ArrayList<Location> attractionList = new ArrayList<>(); private ArrayList<Location> shoppingList = new ArrayList<>(); public PlaceholderFragment() { } /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // List of locations to display. // NOTE: Update String[] title in SectionsPagerAdapter and generateLists() generateLists(); ArrayList<Location> locationList = new ArrayList<>(); switch (getArguments().getInt(ARG_SECTION_NUMBER)) { case 1: // Restaurants locationList = restaurantList; break; case 2: // Activities locationList = activityList; break; case 3: // Attractions locationList = attractionList; break; case 4: // Shopping locationList = shoppingList; break; } LocationArrayAdapter locationAdapter = new LocationArrayAdapter(getActivity(), locationList); View rootView = inflater.inflate(R.layout.fragment_main, container, false); ListView listView = (ListView) rootView.findViewById(R.id.location_list); listView.setAdapter(locationAdapter); return rootView; } private void generateLists() { switch (getArguments().getInt(ARG_SECTION_NUMBER)) { case 1: if (restaurantList.isEmpty()) { // Add restaurants Log.v("PlaceholderFragment", "Restaurants generated."); restaurantList.add(new Location(getString(R.string.ennios_name), 4, getString(R.string.ennios_desc), getString(R.string.ennios_reviewUrl), getString(R.string.ennios_mapUrl), R.drawable.ennios)); restaurantList.add(new Location(getString(R.string.bao_name), 5, getString(R.string.bao_desc), getString(R.string.bao_reviewUrl), getString(R.string.bao_mapUrl), R.drawable.bao)); restaurantList.add(new Location(getString(R.string.mozys_name), 4, getString(R.string.mozys_desc), getString(R.string.mozys_reviewUrl), getString(R.string.mozys_mapUrl), R.drawable.mozys)); restaurantList.add(new Location(getString(R.string.mortys_name), 4, getString(R.string.mortys_desc), getString(R.string.mozys_reviewUrl), getString(R.string.mozys_mapUrl), R.drawable.mortys)); } break; case 2: if (activityList.isEmpty()) { // Add activities Log.v("PlaceholderFragment", "Activities generated."); activityList.add(new Location(getString(R.string.cleverArcher_name), 4, getString(R.string.cleverArcher_desc), getString(R.string.cleverArcher_reviewUrl), getString(R.string.cleverArcher_mapUrl), R.drawable.clever_archer)); activityList.add(new Location(getString(R.string.eloraQuarry_name), 4, getString(R.string.eloraQuarry_dsec), getString(R.string.eloraQuarry_reviewUrl), getString(R.string.eloraQuarry_mapUrl), R.drawable.elora_quarry)); } break; case 3: if (attractionList.isEmpty()) { // Add attractions Log.v("PlaceholderFragment", "Attractions generated."); attractionList.add(new Location(getString(R.string.oktoberfest_name), 4, getString(R.string.oktoberfest_desc), getString(R.string.oktoberfest_reviewUrl), getString(R.string.oktoberfest_mapUrl), R.drawable.oktoberfest)); attractionList.add(new Location(getString(R.string.elmiraMaple_name), 4, getString(R.string.elmiraMaple_desc), getString(R.string.elmiraMaple_reviewUrl), getString(R.string.elmiraMaple_mapUrl), R.drawable.elmira)); } break; case 4: if (shoppingList.isEmpty()) { // Add shopping locations Log.v("PlaceholderFragment", "Shopping generated."); shoppingList.add(new Location(getString(R.string.stJacobs_name), 5, getString(R.string.stJacobs_desc), getString(R.string.stJacobs_reviewUrl), getString(R.string.stJacobs_mapUrl), R.drawable.stjacobs)); shoppingList.add(new Location(getString(R.string.nikeFactory_name), 5, getString(R.string.nikeFactory_desc), getString(R.string.nikeFactory_reviewUrl), getString(R.string.nikeFactory_mapUrl), R.drawable.nike)); } break; } } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { private String[] title = new String[]{getString(R.string.category_restaurants), getString(R.string.category_activities), getString(R.string.category_attractions), getString(R.string.category_shopping)}; public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { return title.length; } @Override public CharSequence getPageTitle(int position) { return title[position]; } } }
package edu.neu.ccis.cs5010.assignment7; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.Map; import java.util.concurrent.BlockingQueue; import static org.junit.Assert.*; /** * Created by wenfei on 11/19/17. */ public class SkiDataProcessorTest { private SkiDataProcessor skiDataProcessor; private String file; @Before public void setUp() throws Exception { file = new String("PDPAssignment.csv"); skiDataProcessor = new SkiDataProcessor(); } @Test public void process() throws Exception { file = "testFile.csv"; skiDataProcessor.process(file); file = "PDPAssignment.csv"; skiDataProcessor.process(file); } @Test public void processThread() throws Exception { skiDataProcessor.process(file, 1); } @Test public void output() throws Exception { skiDataProcessor.process(file); skiDataProcessor.output(); } @Test public void outputThread() throws Exception { skiDataProcessor.process(file, 1); skiDataProcessor.output(1); } @Test public void main() throws Exception { //skiDataProcessor.main(null); } }
import java.util.Date; public class House implements Comparable<House>, Cloneable{ private int ID; private double area; private Date whenBuilt; public House(int ID, double area){ this.ID=ID; this.area=area; whenBuilt= new Date(); } public double getArea(){ return area; } public Date getwhenBuilt(){ return whenBuilt; } @Override public int compareTo(House o) { if(getArea()>o.getArea()) return 1; else if(getArea()<o.getArea()) return -1; else return 0; } @Override public Object clone() throws CloneNotSupportedException{ // creating a shallow copy House houseClone = (House)super.clone(); // deep copy on the Date reference variable houseClone.whenBuilt = (Date)whenBuilt.clone(); return houseClone; } @Override public boolean equals(Object e){ if(((House) e).getArea()==getArea() && ((House)e).whenBuilt.toString().equals(whenBuilt.toString())){ return true; } else return false; } public static void main(String[] args) throws CloneNotSupportedException { House house1 = new House(123,456.7); // performs a deep copy since clone was overridden // Separately clones the Date object House house2 = (House)house1.clone(); // the equals method was overridden System.out.println(house1.equals(house2)); // the overridden clone method creates another Date object // the following checks if they both point at the same object // they do not System.out.println(house1.whenBuilt==house2.whenBuilt); } }
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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 ffm.slc.model; /** * A basic Link resource associated with an Entity. * * @author asaarela */ public class BasicLink { private final String rel; private final String href; /** * Construct a new link * * @param rel Name of the link. * @param href StringResource for the link. */ public BasicLink(final String rel, final String href) { this.rel = rel; this.href = href; } public String getRel() { return rel; } public String getHref() { return href; } @Override public String toString() { return "rel=" + rel + ",href=" + href; } }
package com.kusu.ticksee.Activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Toast; import com.kusu.ticksee.Adapters.TickAdapter; import com.kusu.ticksee.Managers.DBSingletone; import com.kusu.ticksee.Managers.SettingManager; import com.kusu.ticksee.Models.Tick; import com.kusu.ticksee.Models.TickDB; import com.kusu.ticksee.Models.Trade; import com.kusu.ticksee.R; import com.kusu.ticksee.Retrofit.API; import com.kusu.ticksee.Utils.Constants; import java.sql.SQLException; import java.util.List; import java.util.Timer; import java.util.TimerTask; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ListTick extends Activity implements View.OnClickListener, TickAdapter.TradeClick { RecyclerView recyclerView; private Timer timer = new Timer(); TickAdapter adapter; boolean autorized = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a_list); SettingManager.create(this); findViewById(R.id.buttonBag).setOnClickListener(this); recyclerView = (RecyclerView) findViewById(R.id.list); recyclerView.setLayoutManager(new LinearLayoutManager(this)); try { adapter = new TickAdapter(this, DBSingletone.getHelper(this).getTickDBDAO().queryForAll(), this); recyclerView.setAdapter(adapter); startTimer(); } catch (SQLException e) { e.printStackTrace(); Toast.makeText(this, R.string.bad_bd, Toast.LENGTH_SHORT).show(); } } private void startTimer() { timer.cancel(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { Call<List<Tick>> call; if (autorized) call = API.getAuth().getTicks(); else call = API.get().getTicks(); call.enqueue(new Callback<List<Tick>>() { @Override public void onResponse(Call<List<Tick>> call, Response<List<Tick>> response) { if (response.body() == null) { if (autorized) { Toast.makeText(ListTick.this, response.message(), Toast.LENGTH_SHORT).show(); autorized = false; startTimer(); } } else { try { DBSingletone.getHelper(getApplicationContext()).onClear(ListTick.this); for (Tick tick : response.body()) DBSingletone.getHelper().getTickDBDAO().createOrUpdate(new TickDB(tick)); adapter.update(DBSingletone.getHelper().getTickDBDAO().queryForAll()); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<List<Tick>> call, Throwable t) { Toast.makeText(getApplicationContext(), R.string.bad_internet, Toast.LENGTH_SHORT).show(); timer.cancel(); } }); } }); } }, 1000, Constants.UPDATE_TIME); } @Override public void onStop() { timer.cancel(); super.onStop(); } @Override public void onResume() { super.onResume(); startTimer(); } @Override public void onPause() { timer.cancel(); super.onPause(); } @Override public void onDestroy() { timer.cancel(); super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.buttonBag: Intent intent = new Intent(this, Briefcase.class); startActivityForResult(intent, Constants.IN_BRIEFCASE); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (RESULT_OK != resultCode) return; switch (requestCode) { case Constants.IN_BRIEFCASE: if (data.getBooleanExtra(Constants.GOOD_SAVE, false)) { autorized = true; startTimer(); } break; } } @Override public void onClick(String Symbol, final boolean isBuy) { if (autorized) { Trade trade = new Trade(isBuy, Symbol); Constants.cont = trade.getJsonObject().toString(); API.getAuth().trade(trade.getJsonObject()).enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { if (response.body() == null) { Toast.makeText(ListTick.this, response.message(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ListTick.this, isBuy ? R.string.buy_good : R.string.sell_good, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<String> call, Throwable t) { Toast.makeText(getApplicationContext(), R.string.bad_internet, Toast.LENGTH_SHORT).show(); } }); } } }
package com.hr.overtime.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import com.hr.login.model.LoginModel; import com.hr.overtime.model.OverTimePending; import com.hr.overtime.repository.Impl.OverTimePendingRepository; import com.hr.overtime.service.OverTimeService; import com.hr.overtime.service.bean.PublicReponse; @Controller @SessionAttributes("loginModel") public class ManagerController { @Autowired OverTimeService overTimeService; @Autowired HttpServletRequest request; //管理員審核(抓當下id) @PostMapping(path = "/manageAudit") @ResponseBody public void saveOvertimeAuditted(@RequestParam("type")String type ,@RequestParam("id")int id ,LoginModel loginModel) { // HttpSession httpSession = request.getSession(true); // String empNo = (String)httpSession.getAttribute("empNo"); // empNo = "123"; OverTimePending overTimePending = overTimeService.findById(id); overTimeService.saveAuditted(overTimePending ,type); overTimeService.deletePending(overTimePending); System.out.println("finished"); } @Autowired OverTimePendingRepository overTimePendingRepository; //管理員查詢屬於自己部門所有未審核資料 @GetMapping(path = "/manageQuery") public @ResponseBody PublicReponse findOvertimeByResult(@RequestParam(value="pageNo",required = false)String pageNo, @RequestParam(value="depart",required = false)String depart, @RequestParam(value="keyword",required = false)String keyword,@RequestParam(value="date",required = false)String date, LoginModel loginModel){ int pageNumber = pageNo == null || "null".equals(pageNo) ? 0 : Integer.parseInt(pageNo) -1; Sort sort = Sort.by(Direction.DESC, "id"); Pageable page = PageRequest.of(pageNumber, 5 ,sort); int managerEmpId = loginModel.getDepartmentDetail().getManagerEmpId(); String empNo = loginModel.getEmpNo(); Page<OverTimePending> result = overTimePendingRepository.findAlldelEmpNo(page, empNo, date, depart,managerEmpId); List<OverTimePending> overtimepending = result.getContent(); PublicReponse response = new PublicReponse(); response.setResult(overtimepending); response.setTotalPage(result.getTotalPages()); response.setCurrentPage(pageNumber + 1); return response; } @GetMapping(path = "/ManagersystemOvertime") public String Test() { return "overtime/managerQuery"; } }
package online.lahloba.www.lahloba.data.model.vm_helper; import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import online.lahloba.www.lahloba.BR; import online.lahloba.www.lahloba.data.model.AddressItem; public class CartVMHelper extends BaseObservable { public static final String FREE_SHIPPING = "free_shipping"; public static final String HYPERLOCAL_SHIPPING = "hyperlocal_shipping"; private double total; private AddressItem addressSelected; private String shippingMethodSelected; private double hyperlocalCost = 0; private String pay_method; @Bindable public double getTotal() { return total; } @Bindable public String getShippingMethodSelected() { return shippingMethodSelected; } @Bindable public double getHyperlocalCost() { return hyperlocalCost; } @Bindable public AddressItem getAddressSelected() { return addressSelected; } public String getPay_method() { return pay_method; } public void setTotal(double total) { this.total = total; notifyPropertyChanged(BR.total); } public void setShippingMethodSelected(String shippingMethodSelected) { this.shippingMethodSelected = shippingMethodSelected; notifyPropertyChanged(BR.shippingMethodSelected); } public void setHyperlocalCost(double hyperlocalCost) { this.hyperlocalCost = hyperlocalCost; notifyPropertyChanged(BR.hyperlocalCost); } public void setAddressSelected(AddressItem addressSelected) { this.addressSelected = addressSelected; notifyPropertyChanged(BR.addressSelected); } public void setPay_method(String pay_method) { this.pay_method = pay_method; } }
package com.brajagopal.rmend.data.beans; import org.apache.commons.collections4.MapUtils; import java.util.Map; /** * @author <bxr4261> */ public class RelationsBean extends BaseContent { private String careerType; private String status; public RelationsBean() { this(ContentType.DISCARDED); } private RelationsBean(ContentType _contentType) { super(_contentType); } @Override public void process(Map<String, ? extends Object> _value) { this.type = MapUtils.getString(_value, "_type", null); this.forEndUserDisplay = MapUtils.getBoolean(_value, "forenduserdisplay", false); this.careerType = MapUtils.getString(_value, "careertype", null); this.status = MapUtils.getString(_value, "status", null); } @Override public BaseContent getInstance() { return new RelationsBean(); } @Override public double getScore() { throw new UnsupportedOperationException(); } @Override public String toString() { return "RelationsBean {" + "contentType=" + getContentType() + ", type='" + getType() + '\'' + ", forEndUserDisplay=" + isForEndUserDisplay() + ", careerType='" + getCareerType() + '\'' + ", status='" + getStatus() + '\'' + '}'; } @Override public String getName() { throw new UnsupportedOperationException("getName() not supported by "+getClass()); } public String getCareerType() { return careerType; } public String getStatus() { return status; } }
import java.io.BufferedReader; import java.net.MalformedURLException; import java.net.URL; import java.io.InputStreamReader; import java.net.URLConnection; public class Document{ public String getDocument(String target){ char[] output = new char[1000]; try{ URL url = new URL(target); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) { reader.read(output); } catch(Exception e){ e.printStackTrace(); } }catch(MalformedURLException s){ s.printStackTrace(); } return new String(output); } }
package com.goldenasia.lottery.pattern; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.goldenasia.lottery.R; import com.goldenasia.lottery.view.LhcNumberGroupView; import java.util.ArrayList; /** * 对选号列的View的相关操作的封装 * Created by Alashi on 2016/1/13. */ public class LhcPickNumber implements View.OnClickListener { private static final String TAG = LhcPickNumber.class.getSimpleName(); private LhcNumberGroupView numberGroupView; private LinearLayout viewGroup; private RelativeLayout pickColumnArea; private TextView columnTitle; private LhcNumberGroupView.OnChooseItemClickListener onChooseItem; public LhcPickNumber(View topView, String title) { columnTitle = (TextView) topView.findViewById(R.id.pick_column_title); columnTitle.setText(title); numberGroupView = (LhcNumberGroupView) topView.findViewById(R.id.pick_column_NumberGroupView); viewGroup = (LinearLayout) topView.findViewById(R.id.pick_column_control); pickColumnArea = (RelativeLayout) topView.findViewById(R.id.pick_column_area); for (int i = 0, count = viewGroup.getChildCount(); i < count; i++) { viewGroup.getChildAt(i).setOnClickListener(this); } } public LhcNumberGroupView getNumberGroupView() { return numberGroupView; } public ArrayList<Integer> getCheckedNumber() { return numberGroupView.getCheckedNumber(); } /** * 显示文字 */ public void setDisplayText(String[] displayText) { numberGroupView.setDisplayText(displayText); } /** * 显示方式 */ public void setNumberStyle(Boolean flagStyle) { numberGroupView.setNumberStyle(flagStyle); } /** * 选择模式 */ public void setChooseMode(boolean chooseMode) { numberGroupView.setChooseMode(chooseMode); } /** * 背景设置 */ public void setUncheckedDrawable(Drawable uncheckedDrawable) { numberGroupView.setUncheckedDrawable(uncheckedDrawable); } public void setCheckedDrawable(Drawable checkedDrawable) { numberGroupView.setCheckedDrawable(checkedDrawable); } public void onClearPick() { numberGroupView.setCheckNumber(new ArrayList<>()); } public void onRandom(ArrayList<Integer> list) { numberGroupView.setCheckNumber(list); } /** * 选择监听 */ public void setChooseItemClickListener(LhcNumberGroupView.OnChooseItemClickListener onChooseItem) { this.onChooseItem = onChooseItem; numberGroupView.setChooseItemListener(onChooseItem); } @Override public void onClick(View v) { int max = numberGroupView.getMaxNumber(); int min = numberGroupView.getMinNumber(); ArrayList<Integer> list = new ArrayList<>(); switch (v.getId()) { case R.id.pick_column_big: for (int i = min + (max - min + 1) / 2; i <= max; i++) { list.add(i); } break; case R.id.pick_column_small: for (int i = min, end = min + (max - min + 1) / 2; i < end; i++) { list.add(i); } break; case R.id.pick_column_singular: for (int i = min; i <= max; i++) { if (i % 2 != 0) { list.add(i); } } break; case R.id.pick_column_evenNumbers: for (int i = min; i <= max; i++) { if (i % 2 == 0) { list.add(i); } } break; case R.id.pick_column_all: for (int i = min; i <= max; i++) { list.add(i); } break; case R.id.pick_column_clear: break; default: Log.d(TAG, "onClick: nonsupport view id:" + v.getId()); return; } numberGroupView.setCheckNumber(list); onChooseItem.onChooseItemClick(); } public void setLableText(String text) { columnTitle.setText(text); } public void setColumnAreaHideOrShow(boolean flag) { if (flag) { viewGroup.setVisibility(View.VISIBLE); } else { viewGroup.setVisibility(View.GONE); } } public void setPickColumnArea(boolean flag) { if (flag) { pickColumnArea.setVisibility(View.VISIBLE); } else { pickColumnArea.setVisibility(View.GONE); } } }
package com.example.programmer2.votingsystem; /** * Created by PROGRAMMER2 on 4/22/2017. */ public class Voter { // private int voterId; private String voterNumber; private String voterPassword; public Voter() { } public Voter(String voterNumber, String voterPassword) { //this.voterId = voterId; this.voterNumber = voterNumber; this.voterPassword = voterPassword; } // public int getVoterId() { // return voterId; // } // // public void setVoterId(int voterId) { // this.voterId = voterId; // } public String getVoterPassword() { return voterPassword; } public void setVoterPassword(String voterPassword) { this.voterPassword = voterPassword; } public String getVoterNumber() { return voterNumber; } public void setVoterNumber(String voterNumber) { this.voterNumber = voterNumber; } }
package diabetes.aclass.utils; public class Component { // public static final String API_BASE = "http://192.168.1.73/api/v1/"; // public static final String API_BASE = "http://192.168.43.70/"; // public static final String API_BASE = "http://192.168.1.7/"; public static final String API_BASE = "http://192.168.1.5/"; public static final String API_GET_USERS = API_BASE + "users"; public static final String API_GET_USER_BYID = API_BASE + "users/getuserbyid?user_id="; public static final String API_POST_USER = API_BASE + "users/saveuser"; public static final String API_GET_MEDICS = API_BASE + "medics"; public static final String API_GET_MEDIC_BYID = API_BASE + "medics/getbyid?medic_id="; public static final String API_GET_MEDICINES = API_BASE + "medicines"; public static final String API_GET_MEASUREMENTS = API_BASE + "measurements"; public static final String API_POST_MEASUREMENTS = API_BASE + "measurements/save"; public static final String API_GET_MEASUREMENTS_BYID = API_BASE + "measurements/getbyuid?patient_id="; public static final String API_GET_LASTMONTH_MEASUREMENT_BYID = API_BASE + "measurements/patientmeasord?patient_id="; public static final String GOOGLE_AUTH = "http://dbts.com/auth/google_oauth2/"; }
package dnoguchi.parkingticket; public class ParkingMeter { private long purchasedTime; public ParkingMeter(long purchasedTime) { this.purchasedTime = purchasedTime; } public void setPurchasedTime(long purchasedTime) { this.purchasedTime = purchasedTime; } public long getPurchasedTime() { return purchasedTime; } }
/* * Copyright 2014 Brian Roach <roach at basho dot com>. * * 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.basho.riak.client.api.cap; import com.basho.riak.client.api.cap.UnresolvedConflictException; import com.basho.riak.client.api.cap.DefaultResolver; import com.basho.riak.client.api.cap.ConflictResolverFactory; import com.basho.riak.client.api.cap.ConflictResolver; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * * @author Brian Roach <roach at basho dot com> */ public class ConflictResolverFactoryTest { @Before public void setUp() { ConflictResolverFactory factory = ConflictResolverFactory.getInstance(); factory.unregisterConflictResolver(Pojo.class); } @Test public void getDefaultResolver() throws UnresolvedConflictException { ConflictResolverFactory factory = ConflictResolverFactory.getInstance(); ConflictResolver<Pojo> resolver = factory.getConflictResolver(Pojo.class); assertTrue(resolver instanceof DefaultResolver); resolver.resolve(Arrays.asList(new Pojo())); } @Test public void registerResolverClass() throws UnresolvedConflictException { ConflictResolverFactory factory = ConflictResolverFactory.getInstance(); MyResolver resolver = new MyResolver(); factory.registerConflictResolver(Pojo.class, resolver); ConflictResolver<Pojo> resolver2 = factory.getConflictResolver(Pojo.class); assertTrue(resolver2 instanceof MyResolver); assertEquals(resolver, resolver2); } public static class Pojo { public Pojo(){} String foo; int bar; } public static class MyResolver implements ConflictResolver<Pojo> { @Override public Pojo resolve(List<Pojo> objectList) throws UnresolvedConflictException { return objectList.get(0); } } }
public interface ShapeVisitor { }
package leetcode.solution; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** * 20. 有效的括号 * <p> * https://leetcode-cn.com/problems/valid-parentheses/ * <p> * 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 * <p> * 有效字符串需满足: * <p> * 左括号必须用相同类型的右括号闭合。 * 左括号必须以正确的顺序闭合。 * 注意空字符串可被认为是有效字符串。 * * <p> * 示例: * <p> * 输入: "()" * 输出: true * <p> * 输入: "()[]{}" * 输出: true * <p> * Solution: 使用栈,初始放入一个!,防止pop抛异常,在使用一个map存放括号组合 * 之后将开始括号挨个入栈,若是其它符号则出栈,如果出栈元素为!或对应不上括号则提前返回false * 最后判断栈如果还有其它元素则返回false */ public class Solution20 { public boolean isValid(String s) { if (s.length() <= 1) { return false; } Map<Character, Character> charMap = new HashMap<>(); charMap.put('{','}'); charMap.put('[',']'); charMap.put('(',')'); Deque<Character> stack = new LinkedList<>(); stack.push('!'); for (Character c : s.toCharArray()) { if (charMap.containsKey(c)) { stack.push(c); } else { Character popChar = stack.pop(); if (popChar == '!' || !c.equals(charMap.get(popChar))) { return false; } } } return stack.peek() == null || stack.peek() == '!'; } public static void main(String[] args) { Solution20 solution21 = new Solution20(); System.out.println(solution21.isValid("((")); } }
package edu.neu.ccs.cs5010; import org.junit.Before; import org.junit.Test; import java.math.BigInteger; import java.security.interfaces.RSAKey; import static org.junit.Assert.*; /** * Created by wenfei on 10/29/17. */ public class ClientTest { private Client client; private BigInteger[][] keyPair; private RSAKeyGenerator keyGenerator; private RandomNumber randomNum; @Before public void setUp() throws Exception { keyGenerator = new RSAKeyGenerator(); keyPair = keyGenerator.generateKey(); randomNum = new RandomNumber(); client = new Client( 102193, keyPair[RSAKeyGenerator.publicKeyIndex], keyPair[RSAKeyGenerator.privateKeyIndex], 1000, 300 ); } @Test public void getClientID() throws Exception { assertEquals(client.clientID, 102193); } @Test public void getPublicKey() throws Exception { System.out.println(client.getPublicKey()[RSASignature.keyPart]); System.out.println(client.getPublicKey()[RSASignature.publicPart]); } @Test public void getPrivateKey() throws Exception { System.out.println(client.getPrivateKey()[RSASignature.keyPart]); System.out.println(client.getPrivateKey()[RSASignature.publicPart]); } @Test public void getDepositLimt() throws Exception { assertEquals(client.getDepositLimt(), 1000); } @Test public void getWithdrawalLimt() throws Exception { assertEquals(client.getWithdrawalLimt(), 300); } @Test public void printInfo() throws Exception { client.printInfo(); } }
package com.aaa.house.service; import com.aaa.house.dao.AMenuMapping; import com.aaa.house.entity.Tree; import com.aaa.house.utils.CusUtil; import com.aaa.house.utils.ISysConstants; import com.aaa.house.utils.ResultUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * FileName: AMenuSeviceImpl * Author: 曹康 * Date: 2019/7/28 16:13 * Description: 权限菜单 */ @Service public class AMenuSeviceImpl implements AMenuService{ @Autowired private AMenuMapping aMenuMapping; /** * 权限菜单 * @return */ @Override public ResultUtil getPowers() { //查询得到数据 List<Tree> powers = aMenuMapping.getPowers(CusUtil.getStaff().getStaff_id()); //定义临时集合,存放并拼装后台数据 List<Tree> tmpData=new ArrayList<>(); //判断是否查到值 if (powers!=null&&powers.size()>0){ //遍历值 for (Tree power : powers) { //判断是否是一级节点 if (power.getPer_id()==0){ //添加一级节点 tmpData.add(power); //查找孩子节点 并绑定 bingClidren(power,powers); } } } //调用交互类 ResultUtil resultUtil=new ResultUtil(); //设置状态码 resultUtil.setCode(ISysConstants.SUCCESSCODE); //数据 resultUtil.setObject(tmpData); return resultUtil; } @Override public ResultUtil getPowersAll() { //查询得到数据 List<Tree> powers = aMenuMapping.getPowersAll(); //定义临时集合,存放并拼装后台数据 List<Tree> tmpData=new ArrayList<>(); //判断是否查到值 if (powers!=null&&powers.size()>0){ //遍历值 for (Tree power : powers) { //判断是否是一级节点 if (power.getPer_id()==0){ //添加一级节点 tmpData.add(power); //查找孩子节点 并绑定 bingClidren(power,powers); } } } //调用交互类 ResultUtil resultUtil=new ResultUtil(); //设置状态码 resultUtil.setCode(ISysConstants.SUCCESSCODE); //数据 resultUtil.setObject(tmpData); return resultUtil; } /** * 添加权限 * @return */ @Override public ResultUtil inPowers(Map map) { //获取session map.put("per_staffName",CusUtil.getStaff().getStaff_num()); int a=aMenuMapping.inPowers(map); ResultUtil resultUtil=new ResultUtil(); if (a>0){ resultUtil.setCode(ISysConstants.SUCCESSCODE); return resultUtil; } resultUtil.setCode(ISysConstants.OTHERTIPS); return resultUtil; } /** * 修改权限 * @param map * @return */ @Override public ResultUtil upPowers(Map map) { int a=aMenuMapping.upPowers(map); ResultUtil resultUtil=new ResultUtil(); if (a>0){ resultUtil.setCode(ISysConstants.SUCCESSCODE); return resultUtil; } resultUtil.setCode(ISysConstants.OTHERTIPS); return resultUtil; } /** * 删除权限 * @param id * @return */ @Override public ResultUtil deletePowers(int id) { int a=aMenuMapping.deletePowers(id); ResultUtil resultUtil=new ResultUtil(); if (a>0){ resultUtil.setCode(ISysConstants.SUCCESSCODE); return resultUtil; } resultUtil.setCode(ISysConstants.OTHERTIPS); return resultUtil; } /** * 递归绑定孩子节点 * @param tree * @param powers */ private void bingClidren(Tree tree,List<Tree> powers){ //创建子节点 用于保存 List<Tree> temChildrens=null; //遍历所有节点 for (Tree power : powers) { //判断 如果父节点id等于当前节点pid,那就是该节点父节点 if (tree.getId()==power.getPer_id()){ power.setPer_name(tree.getLabel()); //获取所有子节点 List<Tree> children = tree.getChildren(); //判断子节点是否有孩子 没有就创建 if (children==null||children.size()==0){ //创建 temChildrens=new ArrayList<>(); //添加子节点 temChildrens.add(power); //在父节点中设置孩子节点 tree.setChildren(temChildrens); }else { //存在孩子 children.add(power); } //递归 无线节点 bingClidren(power,powers); } } } }
package com.shahinnazarov.gradle.models; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Map; @Data @NoArgsConstructor public class K8sMetadata { private String name; private String namespace; private Map<String, String> labels; private Map<String, String> annotations; public K8sMetadata(String name, Map<String, String> annotations) { this.name = name; this.annotations = annotations; } public K8sMetadata(String name, String namespace, Map<String, String> labels, Map<String, String> annotations) { this.name = name; this.namespace = namespace; this.labels = labels; this.annotations = annotations; } public K8sMetadata(String name, String namespace) { this.name = name; this.namespace = namespace; } public K8sMetadata(Map<String, String> labels) { this.labels = labels; } public K8sMetadata(String name, String namespace, Map<String, String> labels) { this.name = name; this.namespace = namespace; this.labels = labels; } }
package com.ros.employees.apis; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.ros.employees.entities.Employee; @Component @Path("/employees") public class EmployeeAccessAPI { EmployeeDataAccess employeeDataAccess; public EmployeeDataAccess getEmployeeDataAccess() { return employeeDataAccess; } @Autowired public void setEmployeeDataAccess(EmployeeDataAccess employeeDataAccess) { this.employeeDataAccess = employeeDataAccess; } @POST @Path("/register") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Employee addEmployee(@BeanParam Employee emp) { return getEmployeeDataAccess().registerEmployee(emp); } @PUT @Path("/update") @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Employee updateEmployee(Employee emp) { return getEmployeeDataAccess().registerEmployee(emp); } @GET @Path("/list") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Iterable<Employee> fetchAllEmployees() { return getEmployeeDataAccess().getAllEmployees(); } @GET @Path("/find/{employeeNumber}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Employee getByEmployeeNumber(@PathParam("employeeNumber") int empNumber) { return getEmployeeDataAccess().findByEmployeeNumber(empNumber); } @DELETE @Path("/delete/{employeeNumber}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Employee deleteEmployee(@PathParam("employeeNumber") int empNumber) { return getEmployeeDataAccess().removeEmployee(empNumber); } }
package com.karachevtsev.mayaghostsballs; import com.badlogic.gdx.graphics.g2d.SpriteBatch; /** * Created by root on 27.01.2017. */ public interface IScene { public boolean render(SpriteBatch sb); public void show(); public RetCommand getRetCommand(); public void breakRetCommand(); public void resize(int width, int height); }
package com.example.university.model; public enum Degree { assistant,associate_professor,professor }
package netty.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class NIOMessageClient { class SendThread implements Runnable{ @Override public void run() { Scanner in = new Scanner(System.in); ByteBuffer buffer = ByteBuffer.allocate(1024); try { while (in.hasNext()){ String content = in.nextLine(); System.out.println(content); buffer.put(content.getBytes()); buffer.flip(); System.out.println(buffer.position()+","+buffer.limit()); channel.write(buffer); //channel.write(buffer);被阻塞了 if (buffer.hasRemaining()){ System.out.println("还有数据没发送完"); handlerTCPError(); //暂时先不处理 } else { System.out.println("发送完成"); } buffer.clear();// buffer.compact(); } } catch (IOException e){ //todo } } private void handlerTCPError(){} private SocketChannel channel; SendThread(SocketChannel channel){ this.channel = channel; } } class ReactorThread implements Runnable{ @Override public void run() { doConnect(); while (true) { try { while (selector.select() > 0){ System.err.println("有事件发生"); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIt = selectionKeys.iterator(); while (keyIt.hasNext()){ SelectionKey currentKey = keyIt.next(); keyIt.remove(); try { channelHandler(currentKey); } finally { shutDownGracefully(currentKey); } } } }catch (IOException e){ //todo } } } public void channelHandler(SelectionKey currentKey) throws IOException{ if (!currentKey.isValid()){ System.exit(-1); } SocketChannel socketChannel = (SocketChannel)currentKey.channel(); if (currentKey.isConnectable()){ System.err.println("isConnectable"); if (socketChannel.finishConnect()){ socketChannel.register(selector, SelectionKey.OP_READ); // socketChannel.register(selector, SelectionKey.OP_WRITE); System.err.println(socketChannel.validOps()); doWrite(socketChannel); } else { System.out.println("链接失败"); System.exit(-1); } } if (currentKey.isReadable()){ System.err.println("isReadable"); ByteBuffer buffer = ByteBuffer.allocate(1024); int readBytes = socketChannel.read(buffer); if (readBytes > 0){ buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String inputContent = new String(bytes, "utf-8"); System.out.println(inputContent); } else if(readBytes < 0) { shutDownGracefully(currentKey); } else{ //todo } } if (currentKey.isWritable()){ System.err.println("isWritable"); System.err.println("11111111111111111"); } } private void shutDownGracefully(SelectionKey currentKey) throws IOException{ if (currentKey != null){ currentKey.cancel(); if (currentKey.channel() != null){ currentKey.channel().close(); } } } private void doConnect(){ try { if (socketChannel.connect(new InetSocketAddress(host,port))){ socketChannel.register(selector, SelectionKey.OP_READ); doWrite(socketChannel); } else { System.out.println("1111"); socketChannel.register(selector, SelectionKey.OP_CONNECT); } }catch (IOException e){ //todo } } private void doWrite(SocketChannel channel){ System.out.println("开始准备发送数据"); new Thread(new SendThread(channel)).start(); } } private String host; private int port; private SocketChannel socketChannel; private Selector selector; private SendThread sendThread ; private ReactorThread acceptThread; public NIOMessageClient(String host, int port){ this(port); this.host = host; } public NIOMessageClient(int port){ this.host = "127.0.0.1"; this.port = port; try { socketChannel = SocketChannel.open(); selector = Selector.open(); } catch (IOException e) { //todo } } public void startUp(){ acceptThread = new ReactorThread(); Thread thread = new Thread(acceptThread); thread.start(); } public static void main (String[] args) throws IOException{ NIOMessageClient client = new NIOMessageClient(9090); client.socketChannel.configureBlocking(false); client.startUp(); } }
package com.encdata.corn.niblet.domain; import java.io.Serializable; /** * blog_tag * @author */ public class BlogTag implements Serializable { /** * 文章id */ private Long contentId; /** * 标签类型 1 白色 2 绿色 */ private int type; /** * 标签 */ private String tag; private static final long serialVersionUID = 1L; public Long getContentId() { return contentId; } public void setContentId(Long contentId) { this.contentId = contentId; } public Integer getType() { return type; } public void setType(int type) { this.type = type; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } BlogTag other = (BlogTag) that; return (this.getContentId() == null ? other.getContentId() == null : this.getContentId().equals(other.getContentId())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getTag() == null ? other.getTag() == null : this.getTag().equals(other.getTag())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getContentId() == null) ? 0 : getContentId().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getTag() == null) ? 0 : getTag().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", contentId=").append(contentId); sb.append(", type=").append(type); sb.append(", tag=").append(tag); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package com.yunhetong.sdk.tool; public final class YhtLog { public static boolean DEBUG = false; public static void d(String tag, String msg) { if (YhtLog.DEBUG) android.util.Log.d(tag, msg); } public static void e(String tag, String msg) { if (YhtLog.DEBUG) { android.util.Log.e(tag, msg); } } public static void e(String tag, String msg, Throwable tr) { if (YhtLog.DEBUG) { android.util.Log.e(tag, msg, tr); tr.printStackTrace(); } } public static void i(String tag, String msg) { if (YhtLog.DEBUG) android.util.Log.i(tag, msg); } }
package com.clone.mango.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.clone.mango.dbdata.FoodInfo; import com.clone.mango.dbdata.Review; public interface ReviewRepository extends JpaRepository<Review, Long>{ }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.listener; import io.micrometer.core.instrument.binder.jms.DefaultJmsProcessObservationConvention; import io.micrometer.core.instrument.binder.jms.JmsObservationDocumentation; import io.micrometer.core.instrument.binder.jms.JmsProcessObservationContext; import io.micrometer.core.instrument.binder.jms.JmsProcessObservationConvention; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import jakarta.jms.Connection; import jakarta.jms.Destination; import jakarta.jms.ExceptionListener; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageListener; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.jms.Topic; import org.springframework.jms.support.JmsUtils; import org.springframework.jms.support.QosSettings; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import org.springframework.util.ErrorHandler; /** * Abstract base class for Spring message listener container implementations. * Can either host a standard JMS {@link jakarta.jms.MessageListener} or Spring's * {@link SessionAwareMessageListener} for actual message processing. * * <p>Usually holds a single JMS {@link Connection} that all listeners are supposed * to be registered on, which is the standard JMS way of managing listener sessions. * Can alternatively also be used with a fresh Connection per listener, for Jakarta EE * style XA-aware JMS messaging. The actual registration process is up to concrete * subclasses. * * <p><b>NOTE:</b> The default behavior of this message listener container is to * <b>never</b> propagate an exception thrown by a message listener up to the JMS * provider. Instead, it will log any such exception at {@code WARN} level. * This means that from the perspective of the attendant JMS provider no such * listener will ever fail. However, if error handling is necessary, then * an implementation of the {@link ErrorHandler} strategy may be provided to * the {@link #setErrorHandler(ErrorHandler)} method. Note that JMSExceptions * <b>will</b> be passed to the {@code ErrorHandler} in addition to (but after) * being passed to an {@link ExceptionListener}, if one has been provided. * * <p>The listener container offers the following message acknowledgment options: * <ul> * <li>"sessionAcknowledgeMode" set to "AUTO_ACKNOWLEDGE" (default): * This mode is container-dependent: For {@link DefaultMessageListenerContainer}, * it means automatic message acknowledgment <i>before</i> listener execution, with * no redelivery in case of an exception and no redelivery in case of other listener * execution interruptions either. For {@link SimpleMessageListenerContainer}, * it means automatic message acknowledgment <i>after</i> listener execution, with * no redelivery in case of a user exception thrown but potential redelivery in case * of the JVM dying during listener execution. In order to consistently arrange for * redelivery with any container variant, consider "CLIENT_ACKNOWLEDGE" mode or - * preferably - setting "sessionTransacted" to "true" instead. * <li>"sessionAcknowledgeMode" set to "DUPS_OK_ACKNOWLEDGE": * <i>Lazy</i> message acknowledgment during ({@link DefaultMessageListenerContainer}) * or shortly after ({@link SimpleMessageListenerContainer}) listener execution; * no redelivery in case of a user exception thrown but potential redelivery in case * of the JVM dying during listener execution. In order to consistently arrange for * redelivery with any container variant, consider "CLIENT_ACKNOWLEDGE" mode or - * preferably - setting "sessionTransacted" to "true" instead. * <li>"sessionAcknowledgeMode" set to "CLIENT_ACKNOWLEDGE": * Automatic message acknowledgment <i>after</i> successful listener execution; * best-effort redelivery in case of a user exception thrown as well as in case * of other listener execution interruptions (such as the JVM dying). * <li>"sessionTransacted" set to "true": * Transactional acknowledgment after successful listener execution; * <i>guaranteed redelivery</i> in case of a user exception thrown as well as * in case of other listener execution interruptions (such as the JVM dying). * </ul> * * <p>There are two solutions to the duplicate message processing problem: * <ul> * <li>Either add <i>duplicate message detection</i> to your listener, in the * form of a business entity existence check or a protocol table check. This * usually just needs to be done in case of the JMSRedelivered flag being * set on the incoming message (otherwise just process straightforwardly). * Note that with "sessionTransacted" set to "true", duplicate messages will * only appear in case of the JVM dying at the most unfortunate point possible * (i.e. after your business logic executed but before the JMS part got committed), * so duplicate message detection is just there to cover a corner case. * <li>Or wrap your <i>entire processing with an XA transaction</i>, covering the * reception of the JMS message as well as the execution of the business logic in * your message listener (including database operations etc). This is only * supported by {@link DefaultMessageListenerContainer}, through specifying * an external "transactionManager" (typically a * {@link org.springframework.transaction.jta.JtaTransactionManager}, with * a corresponding XA-aware JMS {@link jakarta.jms.ConnectionFactory} passed in * as "connectionFactory"). * </ul> * Note that XA transaction coordination adds significant runtime overhead, * so it might be feasible to avoid it unless absolutely necessary. * * <p><b>Recommendations:</b> * <ul> * <li>The general recommendation is to set "sessionTransacted" to "true", * typically in combination with local database transactions triggered by the * listener implementation, through Spring's standard transaction facilities. * This will work nicely in Tomcat or in a standalone environment, often * combined with custom duplicate message detection (if it is unacceptable * to ever process the same message twice). * <li>Alternatively, specify a * {@link org.springframework.transaction.jta.JtaTransactionManager} as * "transactionManager" for a fully XA-aware JMS provider - typically when * running on a Jakarta EE server, but also for other environments with a JTA * transaction manager present. This will give full "exactly-once" guarantees * without custom duplicate message checks, at the price of additional * runtime processing overhead. * </ul> * * <p>Note that the "sessionTransacted" flag is strongly recommended over * {@link org.springframework.jms.connection.JmsTransactionManager}, provided * that transactions do not need to be managed externally. As a consequence, * set the transaction manager only if you are using JTA or if you need to * synchronize with custom external transaction arrangements. * * @author Juergen Hoeller * @author Stephane Nicoll * @author Brian Clozel * @since 2.0 * @see #setMessageListener * @see jakarta.jms.MessageListener * @see SessionAwareMessageListener * @see #handleListenerException * @see DefaultMessageListenerContainer * @see SimpleMessageListenerContainer * @see org.springframework.jms.listener.endpoint.JmsMessageEndpointManager */ public abstract class AbstractMessageListenerContainer extends AbstractJmsListeningContainer implements MessageListenerContainer { private static final boolean micrometerCorePresent = ClassUtils.isPresent( "io.micrometer.core.instrument.binder.jms.JmsInstrumentation", AbstractMessageListenerContainer.class.getClassLoader()); @Nullable private volatile Object destination; @Nullable private volatile String messageSelector; @Nullable private volatile Object messageListener; private boolean subscriptionDurable = false; private boolean subscriptionShared = false; @Nullable private String subscriptionName; @Nullable private Boolean replyPubSubDomain; @Nullable private QosSettings replyQosSettings; private boolean pubSubNoLocal = false; @Nullable private MessageConverter messageConverter; @Nullable private ExceptionListener exceptionListener; @Nullable private ErrorHandler errorHandler; @Nullable private ObservationRegistry observationRegistry; private boolean exposeListenerSession = true; private boolean acceptMessagesWhileStopping = false; /** * Specify concurrency limits. */ public abstract void setConcurrency(String concurrency); /** * Set the destination to receive messages from. * <p>Alternatively, specify a "destinationName", to be dynamically * resolved via the {@link org.springframework.jms.support.destination.DestinationResolver}. * <p>Note: The destination may be replaced at runtime, with the listener * container picking up the new destination immediately (works e.g. with * DefaultMessageListenerContainer, as long as the cache level is less than * CACHE_CONSUMER). However, this is considered advanced usage; use it with care! * @see #setDestinationName(String) */ public void setDestination(@Nullable Destination destination) { this.destination = destination; if (destination instanceof Topic && !(destination instanceof Queue)) { // Clearly a Topic: let's set the "pubSubDomain" flag accordingly. setPubSubDomain(true); } } /** * Return the destination to receive messages from. Will be {@code null} * if the configured destination is not an actual {@link Destination} type; * c.f. {@link #setDestinationName(String) when the destination is a String}. */ @Nullable public Destination getDestination() { return (this.destination instanceof Destination _destination ? _destination : null); } /** * Set the name of the destination to receive messages from. * <p>The specified name will be dynamically resolved via the configured * {@link #setDestinationResolver destination resolver}. * <p>Alternatively, specify a JMS {@link Destination} object as "destination". * <p>Note: The destination may be replaced at runtime, with the listener * container picking up the new destination immediately (works e.g. with * DefaultMessageListenerContainer, as long as the cache level is less than * CACHE_CONSUMER). However, this is considered advanced usage; use it with care! * @see #setDestination(jakarta.jms.Destination) */ public void setDestinationName(@Nullable String destinationName) { this.destination = destinationName; } /** * Return the name of the destination to receive messages from. * Will be {@code null} if the configured destination is not a * {@link String} type; c.f. {@link #setDestination(Destination) when * it is an actual Destination}. */ @Nullable public String getDestinationName() { return (this.destination instanceof String name ? name : null); } /** * Return a descriptive String for this container's JMS destination * (never {@code null}). */ protected String getDestinationDescription() { Object destination = this.destination; return (destination != null ? destination.toString() : ""); } /** * Set the JMS message selector expression (or {@code null} if none). * Default is none. * <p>See the JMS specification for a detailed definition of selector expressions. * <p>Note: The message selector may be replaced at runtime, with the listener * container picking up the new selector value immediately (works e.g. with * DefaultMessageListenerContainer, as long as the cache level is less than * CACHE_CONSUMER). However, this is considered advanced usage; use it with care! */ public void setMessageSelector(@Nullable String messageSelector) { this.messageSelector = messageSelector; } /** * Return the JMS message selector expression (or {@code null} if none). */ @Nullable public String getMessageSelector() { return this.messageSelector; } /** * Set the message listener implementation to register. * This can be either a standard JMS {@link MessageListener} object * or a Spring {@link SessionAwareMessageListener} object. * <p>Note: The message listener may be replaced at runtime, with the listener * container picking up the new listener object immediately (works e.g. with * DefaultMessageListenerContainer, as long as the cache level is less than * CACHE_CONSUMER). However, this is considered advanced usage; use it with care! * @throws IllegalArgumentException if the supplied listener is not a * {@link MessageListener} or a {@link SessionAwareMessageListener} * @see jakarta.jms.MessageListener * @see SessionAwareMessageListener */ public void setMessageListener(@Nullable Object messageListener) { checkMessageListener(messageListener); this.messageListener = messageListener; if (messageListener != null && this.subscriptionName == null) { this.subscriptionName = getDefaultSubscriptionName(messageListener); } } /** * Return the message listener object to register. */ @Nullable public Object getMessageListener() { return this.messageListener; } /** * Check the given message listener, throwing an exception * if it does not correspond to a supported listener type. * <p>By default, only a standard JMS {@link MessageListener} object or a * Spring {@link SessionAwareMessageListener} object will be accepted. * @param messageListener the message listener object to check * @throws IllegalArgumentException if the supplied listener is not a * {@link MessageListener} or a {@link SessionAwareMessageListener} * @see jakarta.jms.MessageListener * @see SessionAwareMessageListener */ protected void checkMessageListener(@Nullable Object messageListener) { if (messageListener != null && !(messageListener instanceof MessageListener || messageListener instanceof SessionAwareMessageListener)) { throw new IllegalArgumentException( "Message listener needs to be of type [" + MessageListener.class.getName() + "] or [" + SessionAwareMessageListener.class.getName() + "]"); } } /** * Determine the default subscription name for the given message listener. * @param messageListener the message listener object to check * @return the default subscription name * @see SubscriptionNameProvider */ protected String getDefaultSubscriptionName(Object messageListener) { if (messageListener instanceof SubscriptionNameProvider subscriptionNameProvider) { return subscriptionNameProvider.getSubscriptionName(); } else { return messageListener.getClass().getName(); } } /** * Set whether to make the subscription durable. The durable subscription name * to be used can be specified through the "subscriptionName" property. * <p>Default is "false". Set this to "true" to register a durable subscription, * typically in combination with a "subscriptionName" value (unless * your message listener class name is good enough as subscription name). * <p>Only makes sense when listening to a topic (pub-sub domain), * therefore this method switches the "pubSubDomain" flag as well. * @see #setSubscriptionName * @see #setPubSubDomain */ public void setSubscriptionDurable(boolean subscriptionDurable) { this.subscriptionDurable = subscriptionDurable; if (subscriptionDurable) { setPubSubDomain(true); } } /** * Return whether to make the subscription durable. */ public boolean isSubscriptionDurable() { return this.subscriptionDurable; } /** * Set whether to make the subscription shared. The shared subscription name * to be used can be specified through the "subscriptionName" property. * <p>Default is "false". Set this to "true" to register a shared subscription, * typically in combination with a "subscriptionName" value (unless * your message listener class name is good enough as subscription name). * Note that shared subscriptions may also be durable, so this flag can * (and often will) be combined with "subscriptionDurable" as well. * <p>Only makes sense when listening to a topic (pub-sub domain), * therefore this method switches the "pubSubDomain" flag as well. * <p><b>Requires a JMS 2.0 compatible message broker.</b> * @since 4.1 * @see #setSubscriptionName * @see #setSubscriptionDurable * @see #setPubSubDomain */ public void setSubscriptionShared(boolean subscriptionShared) { this.subscriptionShared = subscriptionShared; if (subscriptionShared) { setPubSubDomain(true); } } /** * Return whether to make the subscription shared. * @since 4.1 */ public boolean isSubscriptionShared() { return this.subscriptionShared; } /** * Set the name of a subscription to create. To be applied in case * of a topic (pub-sub domain) with a shared or durable subscription. * <p>The subscription name needs to be unique within this client's * JMS client id. Default is the class name of the specified message listener. * <p>Note: Only 1 concurrent consumer (which is the default of this * message listener container) is allowed for each subscription, * except for a shared subscription (which requires JMS 2.0). * @since 4.1 * @see #setPubSubDomain * @see #setSubscriptionDurable * @see #setSubscriptionShared * @see #setClientId * @see #setMessageListener */ public void setSubscriptionName(@Nullable String subscriptionName) { this.subscriptionName = subscriptionName; } /** * Return the name of a subscription to create, if any. * @since 4.1 */ @Nullable public String getSubscriptionName() { return this.subscriptionName; } /** * Set the name of a durable subscription to create. This method switches * to pub-sub domain mode and activates subscription durability as well. * <p>The durable subscription name needs to be unique within this client's * JMS client id. Default is the class name of the specified message listener. * <p>Note: Only 1 concurrent consumer (which is the default of this * message listener container) is allowed for each durable subscription, * except for a shared durable subscription (which requires JMS 2.0). * @see #setPubSubDomain * @see #setSubscriptionDurable * @see #setSubscriptionShared * @see #setClientId * @see #setMessageListener */ public void setDurableSubscriptionName(@Nullable String durableSubscriptionName) { this.subscriptionName = durableSubscriptionName; this.subscriptionDurable = (durableSubscriptionName != null); } /** * Return the name of a durable subscription to create, if any. */ @Nullable public String getDurableSubscriptionName() { return (this.subscriptionDurable ? this.subscriptionName : null); } /** * Set whether to inhibit the delivery of messages published by its own connection. * Default is "false". * @since 4.1 * @see jakarta.jms.Session#createConsumer(jakarta.jms.Destination, String, boolean) */ public void setPubSubNoLocal(boolean pubSubNoLocal) { this.pubSubNoLocal = pubSubNoLocal; } /** * Return whether to inhibit the delivery of messages published by its own connection. * @since 4.1 */ public boolean isPubSubNoLocal() { return this.pubSubNoLocal; } /** * Configure the reply destination type. By default, the configured {@code pubSubDomain} * value is used (see {@link #isPubSubDomain()}). * <p>This setting primarily indicates what type of destination to resolve if dynamic * destinations are enabled. * @param replyPubSubDomain "true" for the Publish/Subscribe domain ({@link Topic Topics}), * "false" for the Point-to-Point domain ({@link Queue Queues}) * @since 4.2 * @see #setDestinationResolver */ public void setReplyPubSubDomain(boolean replyPubSubDomain) { this.replyPubSubDomain = replyPubSubDomain; } /** * Return whether the Publish/Subscribe domain ({@link jakarta.jms.Topic Topics}) is used * for replies. Otherwise, the Point-to-Point domain ({@link jakarta.jms.Queue Queues}) * is used. * @since 4.2 */ @Override public boolean isReplyPubSubDomain() { if (this.replyPubSubDomain != null) { return this.replyPubSubDomain; } else { return isPubSubDomain(); } } /** * Configure the {@link QosSettings} to use when sending a reply. Can be set to * {@code null} to indicate that the broker's defaults should be used. * @param replyQosSettings the QoS settings to use when sending a reply, or * {@code null} to use the default value * @since 5.0 */ public void setReplyQosSettings(@Nullable QosSettings replyQosSettings) { this.replyQosSettings = replyQosSettings; } @Override @Nullable public QosSettings getReplyQosSettings() { return this.replyQosSettings; } /** * Set the {@link MessageConverter} strategy for converting JMS Messages. * @since 4.1 */ public void setMessageConverter(@Nullable MessageConverter messageConverter) { this.messageConverter = messageConverter; } @Override @Nullable public MessageConverter getMessageConverter() { return this.messageConverter; } /** * Set the JMS ExceptionListener to notify in case of a JMSException thrown * by the registered message listener or the invocation infrastructure. */ public void setExceptionListener(@Nullable ExceptionListener exceptionListener) { this.exceptionListener = exceptionListener; } /** * Return the JMS ExceptionListener to notify in case of a JMSException thrown * by the registered message listener or the invocation infrastructure, if any. */ @Nullable public ExceptionListener getExceptionListener() { return this.exceptionListener; } /** * Set the {@link ErrorHandler} to be invoked in case of any uncaught exceptions * thrown while processing a {@link Message}. * <p>By default, there will be <b>no</b> ErrorHandler so that error-level * logging is the only result. */ public void setErrorHandler(@Nullable ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Return the {@link ErrorHandler} to be invoked in case of any uncaught exceptions * thrown while processing a {@link Message}. * @since 4.1 */ @Nullable public ErrorHandler getErrorHandler() { return this.errorHandler; } /** * Return the {@link ObservationRegistry} used for recording * {@link JmsObservationDocumentation#JMS_MESSAGE_PUBLISH JMS message processing observations}. * @since 6.1 */ @Nullable public ObservationRegistry getObservationRegistry() { return this.observationRegistry; } /** * Set the {@link ObservationRegistry} to be used for recording * {@link JmsObservationDocumentation#JMS_MESSAGE_PUBLISH JMS message processing observations}. * Defaults to no-op observations if the registry is not set. * @since 6.1 */ public void setObservationRegistry(@Nullable ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } /** * Set whether to expose the listener JMS Session to a registered * {@link SessionAwareMessageListener} as well as to * {@link org.springframework.jms.core.JmsTemplate} calls. * <p>Default is "true", reusing the listener's {@link Session}. * Turn this off to expose a fresh JMS Session fetched from the same * underlying JMS {@link Connection} instead, which might be necessary * on some JMS providers. * <p>Note that Sessions managed by an external transaction manager will * always get exposed to {@link org.springframework.jms.core.JmsTemplate} * calls. So in terms of JmsTemplate exposure, this setting only affects * locally transacted Sessions. * @see SessionAwareMessageListener */ public void setExposeListenerSession(boolean exposeListenerSession) { this.exposeListenerSession = exposeListenerSession; } /** * Return whether to expose the listener JMS {@link Session} to a * registered {@link SessionAwareMessageListener}. */ public boolean isExposeListenerSession() { return this.exposeListenerSession; } /** * Set whether to accept received messages while the listener container * in the process of stopping. * <p>Default is "false", rejecting such messages through aborting the * receive attempt. Switch this flag on to fully process such messages * even in the stopping phase, with the drawback that even newly sent * messages might still get processed (if coming in before all receive * timeouts have expired). * <p><b>NOTE:</b> Aborting receive attempts for such incoming messages * might lead to the provider's retry count decreasing for the affected * messages. If you have a high number of concurrent consumers, make sure * that the number of retries is higher than the number of consumers, * to be on the safe side for all potential stopping scenarios. */ public void setAcceptMessagesWhileStopping(boolean acceptMessagesWhileStopping) { this.acceptMessagesWhileStopping = acceptMessagesWhileStopping; } /** * Return whether to accept received messages while the listener container * in the process of stopping. */ public boolean isAcceptMessagesWhileStopping() { return this.acceptMessagesWhileStopping; } @Override protected void validateConfiguration() { if (this.destination == null) { throw new IllegalArgumentException("Property 'destination' or 'destinationName' is required"); } } @Override public void setupMessageListener(Object messageListener) { setMessageListener(messageListener); } //------------------------------------------------------------------------- // Template methods for listener execution //------------------------------------------------------------------------- /** * Execute the specified listener, * committing or rolling back the transaction afterwards (if necessary). * @param session the JMS Session to operate on * @param message the received JMS {@link Message} * @see #invokeListener * @see #commitIfNecessary * @see #rollbackOnExceptionIfNecessary * @see #handleListenerException */ protected void executeListener(Session session, Message message) { try { doExecuteListener(session, message); } catch (Throwable ex) { handleListenerException(ex); } } /** * Execute the specified listener, * committing or rolling back the transaction afterwards (if necessary). * @param session the JMS Session to operate on * @param message the received JMS {@link Message} * @throws JMSException if thrown by JMS API methods * @see #invokeListener * @see #commitIfNecessary * @see #rollbackOnExceptionIfNecessary * @see #convertJmsAccessException */ protected void doExecuteListener(Session session, Message message) throws JMSException { if (!isAcceptMessagesWhileStopping() && !isRunning()) { if (logger.isWarnEnabled()) { logger.warn("Rejecting received message because of the listener container " + "having been stopped in the meantime: " + message); } rollbackIfNecessary(session); throw new MessageRejectedWhileStoppingException(); } try { Observation observation = createObservation(message); observation.observeChecked(() -> invokeListener(session, message)); } catch (JMSException | RuntimeException | Error ex) { rollbackOnExceptionIfNecessary(session, ex); throw ex; } commitIfNecessary(session, message); } private Observation createObservation(Message message) { if (micrometerCorePresent) { return ObservationFactory.create(this.observationRegistry, message); } else { return Observation.NOOP; } } /** * Invoke the specified listener: either as standard JMS MessageListener * or (preferably) as Spring SessionAwareMessageListener. * @param session the JMS Session to operate on * @param message the received JMS {@link Message} * @throws JMSException if thrown by JMS API methods * @see #setMessageListener */ @SuppressWarnings("rawtypes") protected void invokeListener(Session session, Message message) throws JMSException { Object listener = getMessageListener(); if (listener instanceof SessionAwareMessageListener sessionAwareMessageListener) { doInvokeListener(sessionAwareMessageListener, session, message); } else if (listener instanceof MessageListener msgListener) { doInvokeListener(msgListener, message); } else if (listener != null) { throw new IllegalArgumentException( "Only MessageListener and SessionAwareMessageListener supported: " + listener); } else { throw new IllegalStateException("No message listener specified - see property 'messageListener'"); } } /** * Invoke the specified listener as Spring SessionAwareMessageListener, * exposing a new JMS Session (potentially with its own transaction) * to the listener if demanded. * @param listener the Spring SessionAwareMessageListener to invoke * @param session the JMS Session to operate on * @param message the received JMS {@link Message} * @throws JMSException if thrown by JMS API methods * @see SessionAwareMessageListener * @see #setExposeListenerSession */ @SuppressWarnings({"rawtypes", "unchecked"}) protected void doInvokeListener(SessionAwareMessageListener listener, Session session, Message message) throws JMSException { Connection conToClose = null; Session sessionToClose = null; Observation observation = createObservation(message); try { Session sessionToUse = session; if (!isExposeListenerSession()) { // We need to expose a separate Session. conToClose = createConnection(); sessionToClose = createSession(conToClose); sessionToUse = sessionToClose; } observation.start(); // Actually invoke the message listener... listener.onMessage(message, sessionToUse); // Clean up specially exposed Session, if any. if (sessionToUse != session) { if (sessionToUse.getTransacted() && isSessionLocallyTransacted(sessionToUse)) { // Transacted session created by this container -> commit. JmsUtils.commitIfNecessary(sessionToUse); } } } catch (JMSException exc) { observation.error(exc); throw exc; } finally { observation.stop(); JmsUtils.closeSession(sessionToClose); JmsUtils.closeConnection(conToClose); } } /** * Invoke the specified listener as standard JMS {@link MessageListener}. * <p>Default implementation performs a plain invocation of the * {@code onMessage} method. * @param listener the JMS {@code MessageListener} to invoke * @param message the received JMS {@link Message} * @throws JMSException if thrown by JMS API methods * @see jakarta.jms.MessageListener#onMessage */ protected void doInvokeListener(MessageListener listener, Message message) throws JMSException { listener.onMessage(message); } /** * Perform a commit or message acknowledgement, as appropriate. * @param session the JMS {@link Session} to commit * @param message the {@link Message} to acknowledge * @throws jakarta.jms.JMSException in case of commit failure */ protected void commitIfNecessary(Session session, @Nullable Message message) throws JMSException { // Commit session or acknowledge message. if (session.getTransacted()) { // Commit necessary - but avoid commit call within a JTA transaction. if (isSessionLocallyTransacted(session)) { // Transacted session created by this container -> commit. JmsUtils.commitIfNecessary(session); } } else if (message != null && isClientAcknowledge(session)) { message.acknowledge(); } } /** * Perform a rollback, if appropriate. * @param session the JMS Session to rollback * @throws jakarta.jms.JMSException in case of a rollback error */ protected void rollbackIfNecessary(Session session) throws JMSException { if (session.getTransacted()) { if (isSessionLocallyTransacted(session)) { // Transacted session created by this container -> rollback. JmsUtils.rollbackIfNecessary(session); } } else if (isClientAcknowledge(session)) { session.recover(); } } /** * Perform a rollback, handling rollback exceptions properly. * @param session the JMS Session to rollback * @param ex the thrown application exception or error * @throws jakarta.jms.JMSException in case of a rollback error */ protected void rollbackOnExceptionIfNecessary(Session session, Throwable ex) throws JMSException { try { if (session.getTransacted()) { if (isSessionLocallyTransacted(session)) { // Transacted session created by this container -> rollback. if (logger.isDebugEnabled()) { logger.debug("Initiating transaction rollback on application exception", ex); } JmsUtils.rollbackIfNecessary(session); } } else if (isClientAcknowledge(session)) { session.recover(); } } catch (IllegalStateException ex2) { logger.debug("Could not roll back because Session already closed", ex2); } catch (JMSException | RuntimeException | Error ex2) { logger.error("Application exception overridden by rollback error", ex); throw ex2; } } /** * Check whether the given Session is locally transacted, that is, whether * its transaction is managed by this listener container's Session handling * and not by an external transaction coordinator. * <p>Note: The Session's own transacted flag will already have been checked * before. This method is about finding out whether the Session's transaction * is local or externally coordinated. * @param session the Session to check * @return whether the given Session is locally transacted * @see #isSessionTransacted() * @see org.springframework.jms.connection.ConnectionFactoryUtils#isSessionTransactional */ protected boolean isSessionLocallyTransacted(Session session) { return isSessionTransacted(); } /** * Create a JMS MessageConsumer for the given Session and Destination. * <p>This implementation uses JMS 1.1 API. * @param session the JMS Session to create a MessageConsumer for * @param destination the JMS Destination to create a MessageConsumer for * @return the new JMS MessageConsumer * @throws jakarta.jms.JMSException if thrown by JMS API methods */ protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException { if (isPubSubDomain() && destination instanceof Topic topic) { if (isSubscriptionShared()) { return (isSubscriptionDurable() ? session.createSharedDurableConsumer(topic, getSubscriptionName(), getMessageSelector()) : session.createSharedConsumer(topic, getSubscriptionName(), getMessageSelector())); } else if (isSubscriptionDurable()) { return session.createDurableSubscriber( topic, getSubscriptionName(), getMessageSelector(), isPubSubNoLocal()); } else { // Only pass in the NoLocal flag in case of a Topic (pub-sub mode): // Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException // in case of the NoLocal flag being specified for a Queue. return session.createConsumer(destination, getMessageSelector(), isPubSubNoLocal()); } } else { return session.createConsumer(destination, getMessageSelector()); } } /** * Handle the given exception that arose during listener execution. * <p>The default implementation logs the exception at {@code WARN} level, * not propagating it to the JMS provider &mdash; assuming that all handling of * acknowledgement and/or transactions is done by this listener container. * This can be overridden in subclasses. * @param ex the exception to handle */ protected void handleListenerException(Throwable ex) { if (ex instanceof MessageRejectedWhileStoppingException) { // Internal exception - has been handled before. return; } if (ex instanceof JMSException jmsException) { invokeExceptionListener(jmsException); } if (isActive()) { // Regular case: failed while active. // Invoke ErrorHandler if available. invokeErrorHandler(ex); } else { // Rare case: listener thread failed after container shutdown. // Log at debug level, to avoid spamming the shutdown log. logger.debug("Listener exception after container shutdown", ex); } } /** * Invoke the registered JMS ExceptionListener, if any. * @param ex the exception that arose during JMS processing * @see #setExceptionListener */ protected void invokeExceptionListener(JMSException ex) { ExceptionListener exceptionListener = getExceptionListener(); if (exceptionListener != null) { exceptionListener.onException(ex); } } /** * Invoke the registered {@link #getErrorHandler() ErrorHandler} if any. * Log at {@code WARN} level otherwise. * @param ex the uncaught error that arose during JMS processing * @see #setErrorHandler */ protected void invokeErrorHandler(Throwable ex) { ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) { errorHandler.handleError(ex); } else { logger.warn("Execution of JMS message listener failed, and no ErrorHandler has been set.", ex); } } /** * Internal exception class that indicates a rejected message on shutdown. * <p>Used to trigger a rollback for an external transaction manager in that case. */ @SuppressWarnings("serial") private static class MessageRejectedWhileStoppingException extends RuntimeException { } private static abstract class ObservationFactory { private static final JmsProcessObservationConvention DEFAULT_CONVENTION = new DefaultJmsProcessObservationConvention(); static Observation create(@Nullable ObservationRegistry registry, Message message) { return JmsObservationDocumentation.JMS_MESSAGE_PROCESS .observation(null, DEFAULT_CONVENTION, () -> new JmsProcessObservationContext(message), registry); } } }
public class Transition { private Noeud depart; private Noeud arrive; private String etiquette; private Action action; public Transition(Noeud depart, Noeud arrive, String etiquette, Action action) { super(); this.depart = depart; this.arrive = arrive; this.etiquette = etiquette; this.action = action; } public Noeud doTransition( Noeud n, Mot mot ) { Noeud toReturn = this.arrive; toReturn.transfereMotsTraitesJusquAPresent( n ); if ( mot.type == RubriqueNom.type || mot.type == RubriqueValeur.type || mot.type == Verbe.type ) { toReturn.addMot(mot); } if ( action != null ) { action.doAction( toReturn.getMotsTraitesJusquAPresent() ); toReturn.clearMots(); } return toReturn; } public boolean accept(Noeud current, Mot mot) { // Si le noeud actuel est le noeud de départ et que la transition attend bien un mot du type etiquette if ( this.depart == current && mot.getType() == this.etiquette ) { return true; } return false; } public boolean isInitial() { return this.depart.isInitial(); } public Noeud getDepart() { return this.depart; } }
package com.DB.control; import java.io.IOException; import java.sql.Date; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.DB.dao.UserDao; import com.DB.dao.SQLServer.UserDaoImpl; import com.DB.model.User; /** * Servlet implementation class Inscription */ public class Inscription extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Inscription() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("Inscription..."); //get all the parameters String username = request.getParameter("Username"); String password = request.getParameter("Password"); String titre = request.getParameter("Titre"); String email = request.getParameter("Email"); System.out.println(request.getParameter("DOB")); Date DOB = Date.valueOf(request.getParameter("DOB")); System.out.println(DOB.toString()); User user = new User(); user.setUsername(username); user.setPassword(password); user.setTitre(titre); user.setEmail(email); user.setDOB(DOB); user.setDate_Inscription(Util.getCurDate()); user.setDate_Dernier_Acces(Util.getCurDate()); //System.out.println(user.toString()); //first enroll using admin acount. user.setLogin(Util.adminLogin); UserDao userDao = null; try { userDao = new UserDaoImpl(user.getLogin()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); Util.dispatcherToErrorPage("You haven't right to action.", request, response, this); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); Util.dispatcherToErrorPage("You haven't right to action.", request, response, this); } //check the possible duplication if(!userDao.checkDuplication(user.getUsername())) { //persist in database userDao.addUser(user); response.sendRedirect("jsp/SuccessInscription.jsp"); }else{ Util.dispatcherToErrorPage("Sorry, this username is used !", request, response, this); System.out.println("Test"); } } }
package main; import java.io.File; import java.util.ArrayList; import java.util.Collections; import com.beust.jcommander.JCommander; import struct.Node; import tools.Config; import tools.Generator; import tools.NodeCompartor; import tools.Parser; import tools.PrintUtils; import tools.Stat; import tools.ToolNode; public class Main { public static void main(String args[]) { JCommander cmd = new JCommander(new Config(), args); if(Config.help) cmd.usage(); else if (new File(Config.file).exists() && Config.file.contains(".spec")) { System.out.println("File := " + Config.file); Parser.readFile(Config.file); Generator.preperation(); Generator.generation(); Generator.termination(); PrintUtils.toFile(); Stat.writeStat(); } else { System.err.println("The File passed as parameter doesnt exisit"); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javafxtt.db; import java.io.File; import java.sql.*; import java.util.ArrayList; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.chart.PieChart; import javafx.scene.chart.PieChart.Data; import javafxtt.JavaFXTTControllerUtils; import javafxtt.model.Game; import javafxtt.model.Player; import javafxtt.service.GameService; /** * * @author LMI */ public class DatabaseUtils { //private static String dbURL = "jdbc:derby:C:/home/sh/JavaFXTT/database/javafxtt;create=true;user=javafxtt;password=javafxtt"; private static String dbURL = "jdbc:derby:" + new File(".").getAbsolutePath() + "/database/javafxttdb/javafxttdb;create=false;user=javafxtt;password=javafxtt"; // jdbc Connection private static Connection conn = null; private static Statement stmt = null; private static void createConnection() { try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //Get a connection conn = DriverManager.getConnection(dbURL); } catch (Exception except) { except.printStackTrace(); } } public void savePlayer(Player player) throws Exception { createConnection(); String query = "INSERT INTO PLAYER (PLAYER_ID, NAME, FIRSTNAME, TEAM, RANKING) VALUES (DEFAULT, ?, ?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, player.getName()); statement.setString(2, player.getFirstName()); statement.setString(3, player.getTeam()); statement.setString(4, player.getRanking()); System.out.println(statement.toString()); statement.executeUpdate(); statement.close(); shutdown(); } public void deletePlayer(Player player) throws Exception { createConnection(); String query = "DELETE FROM PLAYER WHERE NAME =? AND FIRSTNAME =? AND TEAM =? AND RANKING =?"; PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, player.getName()); statement.setString(2, player.getFirstName()); statement.setString(3, player.getTeam()); statement.setString(4, player.getRanking()); System.out.println(statement.toString()); statement.executeUpdate(); statement.close(); shutdown(); } public void updateRankingOfPlayer(Player player) throws Exception { createConnection(); String query = "UPDATE PLAYER SET RANKING=? WHERE NAME =? AND FIRSTNAME =? AND TEAM =?"; PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, player.getRanking()); statement.setString(2, player.getName()); statement.setString(3, player.getFirstName()); statement.setString(4, player.getTeam()); System.out.println(statement.toString()); statement.executeUpdate(); statement.close(); shutdown(); } public List<Player> getPlayerList() throws Exception { List<Player> playerList = new ArrayList<>(); createConnection(); Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery("Select * From JAVAFXTT.PLAYER"); while (resultSet.next()) { playerList.add(new Player(resultSet.getInt("PLAYER_ID"), resultSet.getString("NAME"), resultSet.getString("FIRSTNAME"), resultSet.getString("TEAM"), resultSet.getString("RANKING"))); } shutdown(); return playerList; } public Player getPlayer(String comboBoxValue) throws Exception { if (comboBoxValue != null && !JavaFXTTControllerUtils.SELECT_PLAYER_LABEL.equalsIgnoreCase(comboBoxValue)) { createConnection(); String[] nameFirstName = comboBoxValue.split("-"); String query = "SELECT * FROM PLAYER WHERE NAME = ? AND FIRSTNAME = ?"; PreparedStatement statement = conn.prepareStatement(query); System.out.println("nameFirstName[0].trim()" + nameFirstName[0].trim()); System.out.println("nameFirstName[1].trim()" + nameFirstName[1].trim()); statement.setString(1, nameFirstName[0].trim()); statement.setString(2, nameFirstName[1].trim()); ResultSet resultSet = statement.executeQuery(); resultSet.next(); Player player = new Player(resultSet.getInt("PLAYER_ID"), resultSet.getString("NAME"), resultSet.getString("FIRSTNAME"), resultSet.getString("TEAM"), resultSet.getString("RANKING")); statement.close(); shutdown(); return player; } return null; } public ObservableList<PieChart.Data> getStats(int gameId, int playerId) throws SQLException { ObservableList<Data> observableArrayList = null; createConnection(); String query = "Select * From GAME Where GAME_ID =?"; PreparedStatement statement = conn.prepareStatement(query); statement.setInt(1, gameId); ResultSet resultSet = statement.executeQuery(); if (resultSet != null) { resultSet.next(); int player1id = resultSet.getInt("PLAYER1_ID"); int player2id = resultSet.getInt("PLAYER2_ID"); observableArrayList = FXCollections.observableArrayList(); if (playerId == player1id || playerId == player2id) { int aInt = resultSet.getInt("HOME_NB_SERVICE_POINT"); if (aInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant sur service", aInt)); } int bInt = resultSet.getInt("HOME_NB_WINNING_POINT"); if (bInt > 0) { observableArrayList.add(new PieChart.Data("Pt sur service", bInt)); } int cInt = resultSet.getInt("VISITOR_NB_WINNING_POINT"); if (cInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant adv", cInt)); } int dInt = resultSet.getInt("HOME_DIRECT_FAULT_ON_SERVICE"); if (dInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe sur service", dInt)); } int eInt = resultSet.getInt("HOME_DIRECT_FAULT"); if (eInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe dans le jeu", eInt)); } int fInt = resultSet.getInt("RECEIVER_DIRECT_FAULT"); if (fInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe adv", fInt)); } int vaInt = resultSet.getInt("VIS_NB_SERVICE_POINT"); if (vaInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant de l'adv sur service", vaInt)); } int vbInt = resultSet.getInt("VIS_NB_WINNING_POINT"); if (vbInt > 0) { observableArrayList.add(new PieChart.Data("Pt de l'adv sur service", vbInt)); } /*int vcInt = resultSet.getInt("VIS_HOME_NB_WINNING_POINT"); if (vcInt > 0) { observableArrayList.add(new PieChart.Data("Point gagnant adv", vcInt)); }*/ int vdInt = resultSet.getInt("VIS_DIRECT_FAULT_ON_SERVICE"); if (vdInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe de l'adv sur service", vdInt)); } /*int veInt = resultSet.getInt("VIS_DIRECT_FAULT"); if (veInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe dans le jeu", veInt)); } int vfInt = resultSet.getInt("VIS_RECEIVER_DIRECT_FAULT"); if (vfInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe adv", vfInt)); }*/ } else { int aInt = resultSet.getInt("HOME_NB_SERVICE_POINT"); if (aInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant de l'adv sur service", aInt)); } int bInt = resultSet.getInt("HOME_NB_WINNING_POINT"); if (bInt > 0) { observableArrayList.add(new PieChart.Data("Pt de l'adv sur service", bInt)); } int cInt = resultSet.getInt("VISITOR_NB_WINNING_POINT"); if (cInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant dans le jeu", cInt)); } int dInt = resultSet.getInt("HOME_DIRECT_FAULT_ON_SERVICE"); if (dInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe de l'adv sur service", dInt)); } int eInt = resultSet.getInt("HOME_DIRECT_FAULT"); if (eInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe de l'adv. dans le jeu", eInt)); } int fInt = resultSet.getInt("RECEIVER_DIRECT_FAULT"); if (fInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe dans le jeu", fInt)); } int vaInt = resultSet.getInt("VIS_NB_SERVICE_POINT"); if (vaInt > 0) { observableArrayList.add(new PieChart.Data("Pt gagnant sur service", vaInt)); } int vbInt = resultSet.getInt("VIS_NB_WINNING_POINT"); if (vbInt > 0) { observableArrayList.add(new PieChart.Data("Pt sur service", vbInt)); } /*int vcInt = resultSet.getInt("VIS_HOME_NB_WINNING_POINT"); if (vcInt > 0) { observableArrayList.add(new PieChart.Data("Point gagnant adv", vcInt)); }*/ int vdInt = resultSet.getInt("VIS_DIRECT_FAULT_ON_SERVICE"); if (vdInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe sur service", vdInt)); } /*int veInt = resultSet.getInt("VIS_DIRECT_FAULT"); if (veInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe dans le jeu", veInt)); } int vfInt = resultSet.getInt("VIS_RECEIVER_DIRECT_FAULT"); if (vfInt > 0) { observableArrayList.add(new PieChart.Data("Faute directe adv", vfInt)); }*/ } } statement.close(); shutdown(); return observableArrayList; } public List<String> getListOfGames(Player player) throws SQLException { List<String> games = new ArrayList(); createConnection(); String query = "Select * From GAME Where PLAYER1_ID =? OR PLAYER2_ID =? OR PLAYER3_ID=? OR PLAYER4_ID=?"; PreparedStatement statement = conn.prepareStatement(query); statement.setInt(1, player.getId()); statement.setInt(2, player.getId()); statement.setInt(3, player.getId()); statement.setInt(4, player.getId()); ResultSet resultSet = statement.executeQuery(); if (resultSet != null) { while (resultSet.next()) { games.add(resultSet.getInt("GAME_ID") + " - " + resultSet.getDate("GAME_DATE").toString() + " - " + resultSet.getString("SCORE")); } } statement.close(); shutdown(); return games; } public void saveGame(Game game) throws SQLException { createConnection(); String query = "INSERT INTO GAME (GAME_ID, GAME_DATE, PLAYER1_ID, PLAYER2_ID, PLAYER3_ID, PLAYER4_ID, SCORE, HOME_WIN, HOME_NB_SERVICE_POINT, HOME_NB_WINNING_POINT, VISITOR_NB_WINNING_POINT, HOME_DIRECT_FAULT_ON_SERVICE, HOME_DIRECT_FAULT, RECEIVER_DIRECT_FAULT, VIS_NB_SERVICE_POINT, VIS_NB_WINNING_POINT, VIS_HOME_NB_WINNING_POINT, VIS_DIRECT_FAULT_ON_SERVICE, VIS_DIRECT_FAULT, VIS_RECEIVER_DIRECT_FAULT) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(query); statement.setDate(1, new Date(System.currentTimeMillis())); statement.setInt(2, game.getPlayer1().getId()); if (game.getPlayer2() != null) { statement.setInt(3, game.getPlayer2().getId()); } else { statement.setInt(3, 0); } statement.setInt(4, game.getPlayer3().getId()); if (game.getPlayer4() != null) { statement.setInt(5, game.getPlayer4().getId()); } else { statement.setInt(5, 0); } statement.setString(6, GameService.getPointsForEachSet(game)); statement.setBoolean(7, GameService.isGameFinished(game).getId() == game.getPlayer1().getId()); statement.setInt(8, GameService.getPointNumber(game, Game.PointType.POINT_ON_SERVICE, true)); statement.setInt(9, GameService.getPointNumber(game, Game.PointType.WINNING_POINT_FOR_SERVICE, true)); statement.setInt(10, GameService.getPointNumber(game, Game.PointType.WINNING_POINT_FOR_RECEIVER, true)); statement.setInt(11, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_SERVICE_ON_SERVICE, true)); statement.setInt(12, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_SERVICE, true)); statement.setInt(13, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_RECEIVER, true)); statement.setInt(14, GameService.getPointNumber(game, Game.PointType.POINT_ON_SERVICE, false)); statement.setInt(15, GameService.getPointNumber(game, Game.PointType.WINNING_POINT_FOR_SERVICE, false)); statement.setInt(16, GameService.getPointNumber(game, Game.PointType.WINNING_POINT_FOR_RECEIVER, false)); statement.setInt(17, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_SERVICE_ON_SERVICE, false)); statement.setInt(18, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_SERVICE, false)); statement.setInt(19, GameService.getPointNumber(game, Game.PointType.DIRECT_FAULT_FOR_RECEIVER, false)); System.out.println(statement.toString()); statement.executeUpdate(); statement.close(); shutdown(); } private static void shutdown() { try { if (stmt != null) { stmt.close(); } if (conn != null) { DriverManager.getConnection(dbURL + ";shutdown=true"); conn.close(); } } catch (SQLException sqlExcept) { } } public static void main(String args[]) throws Exception { createConnection(); } }
package com.trump.auction.reactor.api.model; import java.io.Serializable; import java.math.BigDecimal; import com.alibaba.fastjson.annotation.JSONField; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 出价请求 * * @author Owen * @since 2017/12/29 */ @ToString @EqualsAndHashCode(of = {"auctionNo", "bidder", "bizNo"}) public class BidRequest implements Serializable { /** * 竞拍编号 */ @Getter @Setter private String auctionNo; /** * 竞拍用户 */ @Getter @Setter private Bidder bidder; /** * 出价类型 */ @Getter @Setter private BidType bidType; /** * 业务流水 */ @Getter @Setter protected String bizNo; /** * 期望上一次出价价格 * <p> * 自动出价时使用 * </p> */ @Getter @Setter private BigDecimal expectLastPrice; /** * 出价周期信息 * <p> * 委托多次出价时使用,格式为:总次数-当前第几次 * 例:5-4,表示委托出价 5 次中的第 4 次出价信息 * </p> */ @Getter @Setter private String bidCycle; /** * 交易账户类型 */ @Getter @Setter private AccountCode accountCode; @Getter @Setter private Integer orderRondom; /** * 无效出价标识 */ @JSONField(serialize = false) public boolean isInvalidBid() { if (BidType.AUTO.equals(bidType)) { return true; } return this.accountCode.isInvalidBid(); } }
package dataservice; import dataservice.Shopping; import dataservice.HibernateUtility; import org.hibernate.Session; public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { try { Session session = null; session = HibernateUtility.getSessionFactory().openSession(); org.hibernate.Transaction hibTxn = null; hibTxn = session.getTransaction(); hibTxn.begin(); Shopping shop = new Shopping("Milk"); session.save(shop); hibTxn.commit(); session.close(); }catch(Exception e){ e.printStackTrace(); System.out.println("Adding Error Caught"); } } }
package Football; class Middle extends Player{ Middle(int force, String name, String nationality) { super(force, name, nationality); } }
package model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.apache.struts.action.ActionForm; @Entity public class Project extends ActionForm { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue private int projectId; private String projectTitle; private String startDate; private String endDate; private String status; public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public String getProjectTitle() { return projectTitle; } public void setProjectTitle(String projectTitle) { this.projectTitle = projectTitle; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "Project [projectId=" + projectId + ", projectTitle=" + projectTitle + ", startDate=" + startDate + ", endDate=" + endDate + ", status=" + status + "]"; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.client.match; import java.io.IOException; import java.net.URI; import java.util.List; import org.assertj.core.api.ThrowableTypeAssert; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.http.client.MockClientHttpRequest; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.anything; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; /** * Unit tests for {@link MockRestRequestMatchers}. * * @author Craig Walls * @author Rossen Stoyanchev * @author Sam Brannen * @author Simon Baslé */ class MockRestRequestMatchersTests { private final MockClientHttpRequest request = new MockClientHttpRequest(); @Test void requestTo() throws Exception { this.request.setURI(URI.create("http://www.foo.example/bar")); MockRestRequestMatchers.requestTo("http://www.foo.example/bar").match(this.request); } @Test // SPR-15819 void requestToUriTemplate() throws Exception { this.request.setURI(URI.create("http://www.foo.example/bar")); MockRestRequestMatchers.requestToUriTemplate("http://www.foo.example/{bar}", "bar").match(this.request); } @Test void requestToNoMatch() { this.request.setURI(URI.create("http://www.foo.example/bar")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.requestTo("http://www.foo.example/wrong").match(this.request)); } @Test void requestToContains() throws Exception { this.request.setURI(URI.create("http://www.foo.example/bar")); MockRestRequestMatchers.requestTo(containsString("bar")).match(this.request); } @Test void method() throws Exception { this.request.setMethod(HttpMethod.GET); MockRestRequestMatchers.method(HttpMethod.GET).match(this.request); } @Test void methodNoMatch() { this.request.setMethod(HttpMethod.POST); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.method(HttpMethod.GET).match(this.request)) .withMessageContaining("expected:<GET> but was:<POST>"); } @Test void header() throws Exception { this.request.getHeaders().put("foo", List.of("bar", "baz")); MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request); } @Test void headerDoesNotExist() throws Exception { MockRestRequestMatchers.headerDoesNotExist(null).match(this.request); MockRestRequestMatchers.headerDoesNotExist("").match(this.request); MockRestRequestMatchers.headerDoesNotExist("foo").match(this.request); List<String> values = List.of("bar", "baz"); this.request.getHeaders().put("foo", values); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerDoesNotExist("foo").match(this.request)) .withMessage("Expected header <foo> not to exist, but it exists with values: " + values); } @Test void headerMissing() { assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", "bar").match(this.request)) .withMessageContaining("was null"); } @Test void headerMissingValue() { this.request.getHeaders().put("foo", List.of("bar", "baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", "bad").match(this.request)) .withMessageContaining("expected:<bad> but was:<bar>"); } @Test void headerContains() throws Exception { this.request.getHeaders().put("foo", List.of("bar", "baz")); MockRestRequestMatchers.header("foo", containsString("ba")).match(this.request); } @Test void headerContainsWithMissingHeader() { assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", containsString("baz")).match(this.request)) .withMessage("Expected header <foo> to exist but was null"); } @Test void headerContainsWithMissingValue() { this.request.getHeaders().put("foo", List.of("bar", "baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", containsString("bx")).match(this.request)) .withMessageContaining("was \"bar\""); } @Test void headerListMissing() { assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerList("foo", hasSize(2)).match(this.request)) .withMessage("Expected header <foo> to exist but was null"); } @Test void headerListMatchers() throws IOException { this.request.getHeaders().put("foo", List.of("bar", "baz")); MockRestRequestMatchers.headerList("foo", containsInAnyOrder(endsWith("baz"), endsWith("bar"))).match(this.request); MockRestRequestMatchers.headerList("foo", contains(is("bar"), is("baz"))).match(this.request); MockRestRequestMatchers.headerList("foo", contains(is("bar"), anything())).match(this.request); MockRestRequestMatchers.headerList("foo", hasItem(endsWith("baz"))).match(this.request); MockRestRequestMatchers.headerList("foo", everyItem(startsWith("ba"))).match(this.request); MockRestRequestMatchers.headerList("foo", hasSize(2)).match(this.request); MockRestRequestMatchers.headerList("foo", notNullValue()).match(this.request); MockRestRequestMatchers.headerList("foo", is(anything())).match(this.request); MockRestRequestMatchers.headerList("foo", allOf(notNullValue(), notNullValue())).match(this.request); MockRestRequestMatchers.headerList("foo", allOf(notNullValue(), hasSize(2))).match(this.request); } @Test void headerListContainsMismatch() { this.request.getHeaders().put("foo", List.of("bar", "baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerList("foo", contains(containsString("ba"))).match(this.request)) .withMessageContainingAll( "Request header [foo] values", "Expected: iterable containing [a string containing \"ba\"]", "but: not matched: \"baz\""); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerList("foo", hasItem(endsWith("ba"))).match(this.request)) .withMessageContainingAll( "Request header [foo] values", "Expected: a collection containing a string ending with \"ba\"", "but: mismatches were: [was \"bar\", was \"baz\"]"); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerList("foo", everyItem(endsWith("ar"))).match(this.request)) .withMessageContainingAll( "Request header [foo] values", "Expected: every item is a string ending with \"ar\"", "but: an item was \"baz\""); } @Test void headerListDoesntHideHeaderWithSingleMatcher() throws IOException { this.request.getHeaders().put("foo", List.of("bar", "baz")); MockRestRequestMatchers.header("foo", equalTo("bar")).match(this.request); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.headerList("foo", equalTo("bar")).match(this.request)) .withMessageContainingAll( "Request header [foo] values", "Expected: \"bar\"", "but: was <[bar, baz]>"); } @Test void headers() throws Exception { this.request.getHeaders().put("foo", List.of("bar", "baz")); MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request); } @Test void headersWithMissingHeader() { assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", "bar").match(this.request)) .withMessage("Expected header <foo> to exist but was null"); } @Test void headersWithMissingValue() { this.request.getHeaders().put("foo", List.of("bar")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request)) .withMessageContaining("to have at least <2> values"); } @Test void queryParam() throws Exception { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); MockRestRequestMatchers.queryParam("foo", "bar", "baz").match(this.request); } @Test void queryParamMissing() { this.request.setURI(URI.create("http://www.foo.example/a")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParam("foo", "bar").match(this.request)) .withMessage("Expected query param <foo> to exist but was null"); } @Test void queryParamMissingValue() { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParam("foo", "bad").match(this.request)) .withMessageContaining("expected:<bad> but was:<bar>"); } @Test void queryParamContains() throws Exception { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); MockRestRequestMatchers.queryParam("foo", containsString("ba")).match(this.request); } @Test void queryParamContainsWithMissingValue() { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParam("foo", containsString("bx")).match(this.request)) .withMessageContaining("was \"bar\""); } @Test void queryParamListMissing() { assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParamList("foo", hasSize(2)).match(this.request)) .withMessage("Expected query param <foo> to exist but was null"); } @Test void queryParamListMatchers() throws IOException { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); MockRestRequestMatchers.queryParamList("foo", containsInAnyOrder(endsWith("baz"), endsWith("bar"))).match(this.request); MockRestRequestMatchers.queryParamList("foo", contains(is("bar"), is("baz"))).match(this.request); MockRestRequestMatchers.queryParamList("foo", contains(is("bar"), anything())).match(this.request); MockRestRequestMatchers.queryParamList("foo", hasItem(endsWith("baz"))).match(this.request); MockRestRequestMatchers.queryParamList("foo", everyItem(startsWith("ba"))).match(this.request); MockRestRequestMatchers.queryParamList("foo", hasSize(2)).match(this.request); MockRestRequestMatchers.queryParamList("foo", notNullValue()).match(this.request); MockRestRequestMatchers.queryParamList("foo", is(anything())).match(this.request); MockRestRequestMatchers.queryParamList("foo", allOf(notNullValue(), notNullValue())).match(this.request); MockRestRequestMatchers.queryParamList("foo", allOf(notNullValue(), hasSize(2))).match(this.request); } @Test void queryParamListContainsMismatch() { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParamList("foo", contains(containsString("ba"))).match(this.request)) .withMessageContainingAll( "Query param [foo] values", "Expected: iterable containing [a string containing \"ba\"]", "but: not matched: \"baz\""); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParamList("foo", hasItem(endsWith("ba"))).match(this.request)) .withMessageContainingAll( "Query param [foo] values", "Expected: a collection containing a string ending with \"ba\"", "but: mismatches were: [was \"bar\", was \"baz\"]"); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParamList("foo", everyItem(endsWith("ar"))).match(this.request)) .withMessageContainingAll( "Query param [foo] values", "Expected: every item is a string ending with \"ar\"", "but: an item was \"baz\""); } @Test void queryParamListDoesntHideQueryParamWithSingleMatcher() throws IOException { this.request.setURI(URI.create("http://www.foo.example/a?foo=bar&foo=baz")); MockRestRequestMatchers.queryParam("foo", equalTo("bar")).match(this.request); assertThatAssertionError() .isThrownBy(() -> MockRestRequestMatchers.queryParamList("foo", equalTo("bar")).match(this.request)) .withMessageContainingAll( "Query param [foo] values", "Expected: \"bar\"", "but: was <[bar, baz]>"); } private static ThrowableTypeAssert<AssertionError> assertThatAssertionError() { return assertThatExceptionOfType(AssertionError.class); } }
package com.sl.app.access.join.dao; import com.sl.app.access.join.vo.AppAccessJoinVO; import net.sf.json.JSONObject; public interface AppAccessJoinDAO { JSONObject getCheckEmail(AppAccessJoinVO vo); JSONObject setCompleteJoin(AppAccessJoinVO vo); }
package com.jeffdisher.thinktank.utilities; import org.junit.Assert; import org.junit.Test; public class MainHelpersTest { @Test public void testArgumentParsing() throws Throwable { String value = MainHelpers.getArgument(new String[] {"--adf", "--test", "value"}, "test"); Assert.assertEquals("value", value); value = MainHelpers.getArgument(new String[] {"--adf", "-t", "value"}, "test"); Assert.assertEquals("value", value); value = MainHelpers.getArgument(new String[] {"--adf", "--test", "value"}, "not"); Assert.assertEquals(null, value); value = MainHelpers.getArgument(new String[] {"--adf", "--test", "value", "--test", "value2"}, "test"); Assert.assertEquals("value", value); boolean flag = MainHelpers.getFlag(new String[] {"--adf", "--test", "value"}, "test"); Assert.assertTrue(flag); flag = MainHelpers.getFlag(new String[] {"--adf", "--test", "value"}, "not"); Assert.assertFalse(flag); } }