blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
4c4fd91209ebe631656c4a6f0c36e6bde79a8464
Java
aslivarov98/Market
/market_store/src/market_store/Silver_card.java
UTF-8
362
2.75
3
[]
no_license
package market_store; public class Silver_card extends Card { public Silver_card() { this.owner=null; this.turnover = 0; } public Silver_card(int turnover, String owner) { this.owner=owner; this.turnover = turnover; if (turnover>300) { this.discount_rate=3.5; } else { this.discount_rate=2.0; } } }
true
4157b6e67ed8ebad918c2d7327e5e00d790b8226
Java
wangxianglu/designPatterns
/src/proxy/Sourceable.java
UTF-8
186
1.96875
2
[ "Apache-2.0" ]
permissive
package proxy; /** * @ClassName Sourceable * @Description TODO * @Author Wangxianglu * @Date 2019/5/8 10:15 * @Version 1.0 **/ public interface Sourceable { void method(); }
true
0dd78722a03ae7b1afea8deb7d6cc8538e82585b
Java
aparnals1824/infotechApplication.github.io
/src/main/java/com/report/entities/OrderDetails.java
UTF-8
1,943
2.4375
2
[]
no_license
package com.report.entities; public class OrderDetails { private int odid; private int oid; private int pid; private double price; private int qty; private String tax; private String pdesc; private int hsn; private String cess; public OrderDetails() { } public OrderDetails( int odid, int oid, int pid, double price, int qty, String pdesc, int hsn, String tax, String cess) { this.odid = odid; this.oid = oid; this.pid = pid; this.price = price; this.qty = qty; this.pdesc = pdesc; this.hsn=hsn; this.tax= tax; this.cess= cess; } public int getOdid() { return odid; } public void setOdid(int odid) { this.odid = odid; } public int getOid() { return oid; } public void setOid(int oid) { this.oid = oid; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public String getTax() { return tax; } public void setTax(String tax) { this.tax = tax; } public String getPdesc() { return pdesc; } public void setPdesc(String pdesc) { this.pdesc = pdesc; } public int getHsn() { return hsn; } public void setHsn(int hsn) { this.hsn = hsn; } public String getCess() { return cess; } public void setCess(String cess) { this.cess = cess; } @Override public String toString() { return "OrderDetails{" + "odid=" + odid + ", oid=" + oid + ", pid=" + pid + ", price=" + price + ", qty=" + qty + ", pdesc=" + pdesc + ", hsn=" + hsn + ", tax=" + tax + ", cess=" + cess + '}'; } }
true
a3b12953a56fad8c0917f598f65212565b57b788
Java
dialoguetoolkit/chattool
/src/main/java/diet/server/conversation/ui/JParticipantsPanel.java
UTF-8
1,643
2.328125
2
[]
no_license
/* * 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 diet.server.conversation.ui; import diet.server.conversationhistory.ConversationHistory; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; /** * * @author gj */ public class JParticipantsPanel extends JPanel { ConversationHistory cH; JParticipantsTable jpt; JScrollPane jsp = new JScrollPane(); public JParticipantsPanelSouth jpps ;//= new JParticipantsPanelSouth(cH.getConversation()); public JParticipantsPanel(ConversationHistory cH, boolean telegram){ this.cH=cH; jpps = new JParticipantsPanelSouth(cH.getConversation(), this, telegram); //this.add(new JLabel("THIS")); //this.add(new JButton("THIS")); this.setLayout(new BorderLayout()); jpt = new JParticipantsTable (cH, telegram); jsp.getViewport().add(jpt); this.add(jsp, BorderLayout.CENTER); //this.add(new JLabel("SOUTH"), BorderLayout.SOUTH); //this.add(new JLabel("NORTH"), BorderLayout.SOUTH); this.add(jpps, BorderLayout.SOUTH); } public void updateData(){ final JParticipantsTableModel jptm = (JParticipantsTableModel)jpt.getModel(); SwingUtilities.invokeLater(new Runnable(){ public void run(){ jptm.updateData(); repaint(); } }); } }
true
f95bf7c2bc2012ad520eda8483eeabbb036071d6
Java
MaxBugay/AndroidMobileDevelopment
/Lab0Shapes/src/lab0shapes/EquilateralTriangle.java
UTF-8
833
3.421875
3
[]
no_license
/* * 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 lab0shapes; /** * * @author MaxBu */ public class EquilateralTriangle extends Shapes{ private double sides; public EquilateralTriangle(String name) { super(name); } public void setDimensions(double sides) { this.sides = sides; } @Override public void printDimensions() { System.out.println("Sides length: " + this.sides); } @Override public double getArea() { double halfper = (sides * 3) / 2; double area = Math.sqrt((halfper)*((halfper-sides)*(halfper-sides)*(halfper-sides))); return area; } }
true
a4872857db8aefbe1550307842f857f0720983eb
Java
SocketByte/minecraftparty
/src/main/java/pl/socketbyte/minecraftparty/basic/arena/ChickenGameArena.java
UTF-8
6,912
2.4375
2
[]
no_license
package pl.socketbyte.minecraftparty.basic.arena; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.ItemStack; import pl.socketbyte.minecraftparty.basic.Arena; import pl.socketbyte.minecraftparty.basic.Game; import pl.socketbyte.minecraftparty.basic.arena.helper.chickengame.Animal; import pl.socketbyte.minecraftparty.basic.arena.helper.chickengame.AnimalData; import pl.socketbyte.minecraftparty.basic.arena.helper.chickengame.AnimalPointData; import pl.socketbyte.minecraftparty.basic.arena.helper.chickengame.AnimalType; import pl.socketbyte.minecraftparty.basic.board.impl.ArenaBoardType; import pl.socketbyte.minecraftparty.commons.MessageHelper; import pl.socketbyte.minecraftparty.commons.RandomHelper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ChickenGameArena extends Arena { private int radius; private int amount; private final List<Animal> animals = new ArrayList<>(); private final Map<AnimalType, Double> chances = new HashMap<>(); private final Map<AnimalType, AnimalData> dataMap = new HashMap<>(); public ChickenGameArena(Game game) { super(game); } public int getSize() { return animals.size(); } public int getAnimalsToSpawn() { return amount - getSize(); } @Override public List<Location> getPlayerStartPositions() { return RandomHelper.createLocations(getArenaInfo().getDefaultLocation(), getGame().getPlaying().size()); } @Override public void onCountdown() { } @Override public void onTick(long timeLeft) { if (getAnimalsToSpawn() > 0) { spawn(getAnimalsToSpawn()); } } public void spawn(int amount) { for (int i = 0; i < amount; i++) { AnimalType animalType = RandomHelper.pick(chances); if (animalType == null) continue; boolean plus = RandomHelper.chance(85); AnimalData data = dataMap.get(animalType); Animal animal = new Animal(data); animal.setPlus(plus); animal.spawn(randomizeLocation()); animals.add(animal); } } public Location randomizeLocation() { Location location = getArenaInfo().getDefaultLocation().clone(); int randomX = RandomHelper.randomInteger(-radius, radius); int randomZ = RandomHelper.randomInteger(-radius, radius); location.add(randomX, 0, randomZ); return location; } @Override public void onFreeze() { for (Player player : getGame().getPlaying()) { player.getInventory().clear(); } for (Animal animal : animals) { animal.kill(); } } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (!getGame().isPlaying((Player) event.getWhoClicked())) return; if (!getGame().isArena(this)) return; event.setCancelled(true); } @EventHandler public void onInventoryDrop(PlayerDropItemEvent event) { if (!getGame().isPlaying(event.getPlayer())) return; if (!getGame().isArena(this)) return; event.setCancelled(true); } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { if (!getGame().isPlaying((Player) event.getPlayer())) return; if (!getGame().isArena(this)) return; event.setCancelled(true); } @Override public void onInit() { getBoard().setType(ArenaBoardType.SCORES); radius = getArenaInfo().getData().getInt("radius"); amount = getArenaInfo().getData().getInt("amount"); ConfigurationSection chickenData = getArenaInfo().getData().getConfigurationSection("chicken"); ConfigurationSection cowData = getArenaInfo().getData().getConfigurationSection("cow"); pushDataFor(AnimalType.CHICKEN, chickenData); pushDataFor(AnimalType.COW, cowData); } public void pushDataFor(AnimalType type, ConfigurationSection section) { AnimalData data = new AnimalData(type); AnimalPointData plus = new AnimalPointData(); plus.setPoints(section.getInt("plus.points")); plus.setTitle(MessageHelper.fixColor(section.getString("plus.title"))); data.setPlus(plus); AnimalPointData minus = new AnimalPointData(); minus.setPoints(section.getInt("minus.points")); minus.setTitle(MessageHelper.fixColor(section.getString("minus.title"))); data.setMinus(minus); data.setChance(section.getDouble("chance")); data.setHealth(section.getInt("health")); chances.put(type, data.getChance()); dataMap.put(type, data); } @Override public void onStart() { for (Player player : getGame().getPlaying()) { player.getInventory().setItem(0, new ItemStack(Material.DIAMOND_SWORD)); player.getInventory().setHeldItemSlot(0); } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (!getGame().isPlaying(event.getPlayer())) return; if (!getGame().isArena(this)) return; event.setCancelled(true); } @EventHandler public void onEntityKill(EntityDeathEvent event) { if (event.getEntity().getKiller() == null) return; if (!getGame().isPlaying(event.getEntity().getKiller())) return; if (!getGame().isArena(this)) return; LivingEntity entity = event.getEntity(); Animal animal = null; for (Animal a : animals) { if (a.getEntity().equals(entity)) { animal = a; break; } } if (animal == null) return; event.setDroppedExp(0); event.getDrops().clear(); Player player = entity.getKiller(); MessageHelper.send(player, animal.isPlus() ? animal.getData().getPlus().getTitle() : animal.getData().getMinus().getTitle()); if (animal.isPlus()) addInternalScore(player, animal.getData().getPlus().getPoints()); else addInternalScore(player, animal.getData().getMinus().getPoints()); animals.remove(animal); } @Override public void onEnd() { } }
true
2a1f1c2dbccc02b342cb5a24337eebe323b5f951
Java
skypep/WorkSpace
/SystemApp/通讯功能修改/Telephony/src/com/android/phone/ToroSimcardInfo.java
UTF-8
15,543
1.90625
2
[]
no_license
package com.android.phone; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PersistableBundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.SwitchPreference; import android.preference.TwoStatePreference; import android.telephony.CarrierConfigManager; import android.telephony.ServiceState; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.TextView; import com.android.internal.telephony.CommandException; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; /** * Create By liujia * on 2018/11/27. **/ public class ToroSimcardInfo extends Activity { private static int slotIndex; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.network_setting); ((TextView)findViewById(R.id.tv_title)).setText(getString(R.string.sim_card_info)); findViewById(R.id.ll_back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.network_setting_content); if (fragment == null) { fragmentManager.beginTransaction() .add(R.id.network_setting_content, new SimcardInfoFragment()) .commit(); } } public static class SimcardInfoFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener{ private SubscriptionManager mSubscriptionManager; private Phone mPhone; private ListPreference mButtonPreferredNetworkMode; private TwoStatePreference mAutoSelect; static final int preferredNetworkMode = Phone.PREFERRED_NT_MODE; private MyHandler mHandler; private ProgressDialog mProgressDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new MyHandler(); mSubscriptionManager = SubscriptionManager.from(getActivity()); updatePhone(slotIndex); mProgressDialog = new ProgressDialog(getContext()); addPreferencesFromResource(R.xml.sim_card_info); mButtonPreferredNetworkMode = (ListPreference) findPreference("preferred_network_mode_key"); mAutoSelect = (TwoStatePreference) findPreference("button_auto_select_key"); initNetworkType(); initAutoSelect(); } private void initAutoSelect() { mAutoSelect.setOnPreferenceChangeListener(this); getNetworkSelectionMode(); } private void initNetworkType() { int settingsNetworkMode = android.provider.Settings.Global.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE + mPhone.getSubId(), preferredNetworkMode); PersistableBundle carrierConfig = PhoneGlobals.getInstance().getCarrierConfigForSubId(mPhone.getSubId()); if (carrierConfig.getBoolean(CarrierConfigManager .KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL) && !mPhone.getServiceState().getRoaming() && mPhone.getServiceState().getDataRegState() == ServiceState.STATE_IN_SERVICE) { settingsNetworkMode = preferredNetworkMode; } mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode)); mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this); } private void updatePhone(int slotId) { final SubscriptionInfo sir = mSubscriptionManager .getActiveSubscriptionInfoForSimSlotIndex(slotId); if (sir != null) { mPhone = PhoneFactory.getPhone( SubscriptionManager.getPhoneId(sir.getSubscriptionId())); } if (mPhone == null) { // Do the best we can mPhone = PhoneGlobals.getPhone(); } } @Override public boolean onPreferenceChange(Preference preference, Object objValue) { final int phoneSubId = mPhone.getSubId(); if (preference == mButtonPreferredNetworkMode) { //NOTE onPreferenceChange seems to be called even if there is no change //Check if the button value is changed from the System.Setting mButtonPreferredNetworkMode.setValue((String) objValue); int buttonNetworkMode; buttonNetworkMode = Integer.parseInt((String) objValue); int settingsNetworkMode = android.provider.Settings.Global.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId, preferredNetworkMode); if (buttonNetworkMode != settingsNetworkMode) { int modemNetworkMode; // if new mode is invalid ignore it switch (buttonNetworkMode) { case Phone.NT_MODE_WCDMA_PREF: case Phone.NT_MODE_GSM_ONLY: case Phone.NT_MODE_WCDMA_ONLY: case Phone.NT_MODE_GSM_UMTS: case Phone.NT_MODE_CDMA: case Phone.NT_MODE_CDMA_NO_EVDO: case Phone.NT_MODE_EVDO_NO_CDMA: case Phone.NT_MODE_GLOBAL: case Phone.NT_MODE_LTE_CDMA_AND_EVDO: case Phone.NT_MODE_LTE_GSM_WCDMA: case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA: case Phone.NT_MODE_LTE_ONLY: case Phone.NT_MODE_LTE_WCDMA: case Phone.NT_MODE_TDSCDMA_ONLY: case Phone.NT_MODE_TDSCDMA_WCDMA: case Phone.NT_MODE_LTE_TDSCDMA: case Phone.NT_MODE_TDSCDMA_GSM: case Phone.NT_MODE_LTE_TDSCDMA_GSM: case Phone.NT_MODE_TDSCDMA_GSM_WCDMA: case Phone.NT_MODE_LTE_TDSCDMA_WCDMA: case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA: case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA: case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA: // This is one of the modes we recognize modemNetworkMode = buttonNetworkMode; break; default: return true; } android.provider.Settings.Global.putInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId, buttonNetworkMode ); //Set the modem network mode mPhone.setPreferredNetworkType(modemNetworkMode, mHandler .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE)); } return true; } else if(preference == mAutoSelect){ boolean autoSelect = (Boolean) objValue; selectNetworkAutomatic(autoSelect); return true; } return true; } protected void getNetworkSelectionMode() { final int phoneSubId = mPhone.getSubId(); int mPhoneId = SubscriptionManager.getPhoneId(phoneSubId); Message msg = mHandler.obtainMessage(MyHandler.EVENT_GET_NETWORK_SELECTION_MODE_DONE); Phone phone = PhoneFactory.getPhone(mPhoneId); if (phone != null) { phone.getNetworkSelectionMode(msg); } } private void selectNetworkAutomatic(boolean autoSelect) { final int phoneSubId = mPhone.getSubId(); int mPhoneId = SubscriptionManager.getPhoneId(phoneSubId); if (autoSelect) { showAutoSelectProgressBar(); mAutoSelect.setEnabled(false); Message msg = mHandler.obtainMessage(MyHandler.EVENT_AUTO_SELECT_DONE); Phone phone = PhoneFactory.getPhone(mPhoneId); if (phone != null) { phone.setNetworkSelectionModeAutomatic(msg); } } } private void showAutoSelectProgressBar() { mProgressDialog.setMessage( getContext().getResources().getString(R.string.register_automatically)); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setCancelable(false); mProgressDialog.setIndeterminate(true); mProgressDialog.show(); } private void dismissProgressBar() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } private class MyHandler extends Handler { static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 0; private static final int EVENT_AUTO_SELECT_DONE = 100; private static final int EVENT_GET_NETWORK_SELECTION_MODE_DONE = 200; @Override public void handleMessage(Message msg) { AsyncResult ar; switch (msg.what) { case MESSAGE_SET_PREFERRED_NETWORK_TYPE: handleSetPreferredNetworkTypeResponse(msg); break; case EVENT_AUTO_SELECT_DONE: mAutoSelect.setEnabled(true); dismissProgressBar(); ar = (AsyncResult) msg.obj; if (ar.exception != null) { displayNetworkSelectionFailed(ar.exception); } else { displayNetworkSelectionSucceeded(); } break; case EVENT_GET_NETWORK_SELECTION_MODE_DONE: ar = (AsyncResult) msg.obj; if (ar.exception != null) { } else if (ar.result != null) { try { int[] modes = (int[]) ar.result; boolean autoSelect = (modes[0] == 0); if (mAutoSelect != null) { mAutoSelect.setChecked(autoSelect); } } catch (Exception e) { } } break; } } private void handleSetPreferredNetworkTypeResponse(Message msg) { final Activity activity = getActivity(); if (activity == null || activity.isDestroyed()) { // Access preferences of activity only if it is not destroyed // or if fragment is not attached to an activity. return; } AsyncResult ar = (AsyncResult) msg.obj; final int phoneSubId = mPhone.getSubId(); if (ar.exception == null) { int networkMode; if (mButtonPreferredNetworkMode != null) { networkMode = Integer.parseInt(mButtonPreferredNetworkMode.getValue()); android.provider.Settings.Global.putInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId, networkMode ); } } else { updatePreferredNetworkUIFromDb(); } } } protected void displayNetworkSelectionFailed(Throwable ex) { String status; final int phoneSubId = mPhone.getSubId(); int mPhoneId = SubscriptionManager.getPhoneId(phoneSubId); if ((ex != null && ex instanceof CommandException) && ((CommandException) ex).getCommandError() == CommandException.Error.ILLEGAL_SIM_OR_ME) { status = getContext().getResources().getString(R.string.not_allowed); } else { status = getContext().getResources().getString(R.string.connect_later); } final PhoneGlobals app = PhoneGlobals.getInstance(); app.notificationMgr.postTransientNotification( NotificationMgr.NETWORK_SELECTION_NOTIFICATION, status); TelephonyManager tm = (TelephonyManager) app.getSystemService(Context.TELEPHONY_SERVICE); Phone phone = PhoneFactory.getPhone(mPhoneId); if (phone != null) { ServiceState ss = tm.getServiceStateForSubscriber(phone.getSubId()); if (ss != null) { app.notificationMgr.updateNetworkSelection(ss.getState(), phone.getSubId()); } } } // Used by both mAutoSelect and mNetworkSelect buttons. protected void displayNetworkSelectionSucceeded() { String status = getContext().getResources().getString(R.string.registration_done); final PhoneGlobals app = PhoneGlobals.getInstance(); app.notificationMgr.postTransientNotification( NotificationMgr.NETWORK_SELECTION_NOTIFICATION, status); } private void updatePreferredNetworkUIFromDb() { final int phoneSubId = mPhone.getSubId(); int settingsNetworkMode = android.provider.Settings.Global.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId, preferredNetworkMode); // changes the mButtonPreferredNetworkMode accordingly to settingsNetworkMode mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode)); } } public static Intent createIntent(Context context,int slotIndex) { Intent intent = new Intent(); intent.setClass(context,ToroSimcardInfo.class); ToroSimcardInfo.slotIndex = slotIndex; return intent; } }
true
5f8206a879aa3ff5201b6c85055f76330f3d1b01
Java
odl-lbk/opsManager
/src/main/java/cn/org/bnc/opsManager/entity/DeviceSubnetEntity.java
UTF-8
715
2.359375
2
[]
no_license
package cn.org.bnc.opsManager.entity; import java.util.List; public class DeviceSubnetEntity { private String subnet_name; private List<DeviceEntity> device; public String getSubnet_name() { return subnet_name; } public void setSubnet_name(String subnet_name) { this.subnet_name = subnet_name; } public List<DeviceEntity> getDevice() { return device; } public void setDevice(List<DeviceEntity> device) { this.device = device; } @Override public String toString() { return "DeviceSubnetEntity{" + "subnet_name='" + subnet_name + '\'' + ", device=" + device + '}'; } }
true
f2b220b6cc2279d9a65f390c399d064b99707f07
Java
Mozzarella123/grammatic
/src/main/java/curwa/LexemeFactory.java
UTF-8
288
2.71875
3
[]
no_license
package curwa; public class LexemeFactory { public static Lexeme createLexeme(String value) { try { Integer.parseInt(value); return new Operand(value); } catch (Exception e) { return new Operator(value); } } }
true
6a94c4378b55854184dd955ebc12d93defd72235
Java
charlotte-xiao/AppearanceAnalysis
/src/main/java/cn/xiaostudy/strategy/impl/OssUploadStrategy.java
UTF-8
1,272
2.4375
2
[]
no_license
package cn.xiaostudy.strategy.impl; import cn.xiaostudy.config.OssConfig; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.ByteArrayInputStream; import java.util.Base64; /** * OSS 上传策略 * @author charlotte xiao * @date 2021/10/2 * @description */ @Service("ossUploadStrategy") public class OssUploadStrategy extends AbstractUploadStrategyImpl { @Resource private OssConfig ossConfig; @Override public Boolean exists(String fileName) { return ossConfig.getOssClient().doesObjectExist(ossConfig.getBucketName(),ossConfig.getPath()+fileName); } @Override public void upload(String fileName, String image) { // 格式转换 Base64.Decoder decoder = Base64.getDecoder(); byte[] content = decoder.decode(image.getBytes()); for(int index = 0;index<content.length;index++){ if(content[index]<0){ content[index] += 1<<8; } } ossConfig.getOssClient().putObject(ossConfig.getBucketName(),ossConfig.getPath()+fileName,new ByteArrayInputStream(content)); } @Override public String getFileAccessUrl(String fileName) { return ossConfig.getUrl()+ossConfig.getPath()+fileName; } }
true
b4e2255dcae00a4a713a29241cf848570cd39026
Java
realpageQA/QA_Assessment
/src/test/java/starter/myaccount/MyAccountData.java
UTF-8
370
2.03125
2
[]
no_license
package starter.myaccount; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Question; import net.serenitybdd.screenplay.questions.TextContent; public class MyAccountData { public static Question<String> currentProfileName() { return actor -> TextContent.of(MyAccountOverview.USER_INFO).viewedBy(actor).asString().trim(); } }
true
f65619fc648e15b63762cde1c52c9a780d748874
Java
alavarello/SmartHome
/app/src/main/java/com/grupo1/hci/smarthome/Model/Door.java
UTF-8
1,578
2.84375
3
[]
no_license
package com.grupo1.hci.smarthome.Model; /** * Created by agust on 11/2/2017. */ public class Door implements Device { private String id; private String typeId = Constants.DOOR_ID; private String name; private boolean isClosed; private boolean isLocked; public Door(String id, String name) { this.id = id; this.name = name; this.isClosed = Constants.DOOR_CLOSED; this.isLocked = Constants.DOOR_UNLOCKED; } public Door(String id, String name, boolean isClosed, boolean isLocked) { this.id = id; this.name = name; this.isClosed = isClosed; this.isLocked = isLocked; } public Door(){} @Override public String getId() { return id; } @Override public String getTypeId() { return typeId; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isClosed() { return isClosed; } public void setClosed(boolean closed) { isClosed = closed; } public boolean isLocked() { return isLocked; } public void setLocked(boolean locked) { isLocked = locked; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Door door = (Door) o; return id.equals(door.id); } @Override public int hashCode() { return id.hashCode(); } }
true
4b6223abdf6f281390d4ebad8411c758caf41a72
Java
statops/MCrawlerT
/TOOLS/source/sgdAndroidKit/src/kit/Scenario/AbstractUserEnvironment.java
UTF-8
1,343
2.515625
3
[]
no_license
package kit.Scenario; import java.util.HashMap; abstract class AbstractUserEnvironment extends IScenarioElement implements Cloneable { public final static String NAME = "name"; public final static String STATUS = "status"; public AbstractUserEnvironment(String name, String id, HashMap<String, String> prop) { super(name, id); setProperties(prop); } public boolean isChanged() { return Boolean.parseBoolean(mProperties.get("status")); } abstract boolean isEqualTo(UserEnvironment ue2); @Override public String toString() { String value = ""; for (String prop : mProperties.keySet()) { value = value + prop + " : " + mProperties.get(prop) + " "; } return value; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((mProperties == null) ? 0 : mProperties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; UserEnvironment other = (UserEnvironment) obj; if (mName == null) if (other.mName != null) return false; if (isChanged() != other.isChanged()) return false; if (!mName.equalsIgnoreCase((other.mName))) return false; return true; } }
true
f8031ae921b9525030f855f4035a1172b8aa653b
Java
nadraliev/AndroidGamesProject
/app/src/main/java/com/soutvoid/gamesproject/app/App.java
UTF-8
2,177
1.828125
2
[ "Apache-2.0" ]
permissive
package com.soutvoid.gamesproject.app; import android.app.Application; import android.support.multidex.MultiDex; import android.support.v7.app.AppCompatDelegate; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.BuildConfig; import com.crashlytics.android.core.CrashlyticsCore; import com.github.anrwatchdog.ANRWatchDog; import com.soutvoid.gamesproject.app.dagger.AppComponent; import com.soutvoid.gamesproject.app.dagger.AppModule; import com.soutvoid.gamesproject.app.dagger.DaggerAppComponent; import com.soutvoid.gamesproject.app.log.Logger; import com.soutvoid.gamesproject.app.log.RemoteLogger; import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Kit; import soutvoid.com.gamesproject.R; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; /** * Created by andrew on 2/20/17. */ public class App extends Application { private AppComponent appComponent; @Override public void onCreate() { MultiDex.install(getApplicationContext()); super.onCreate(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); initFabric(); initAnrWatchDog(); initInjector(); initLog(); initCalligraphy(); } private void initAnrWatchDog() { new ANRWatchDog().setReportMainThreadOnly().setANRListener(RemoteLogger::logError).start(); } private void initFabric() { final Kit[] kits = { new Crashlytics.Builder().core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()).build() }; Fabric.with(this, kits); } private void initInjector() { appComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } private void initLog() { Logger.init(); } private void initCalligraphy() { CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Roboto-Regular.ttf") .setFontAttrId(R.attr.fontPath) .build()); } public AppComponent getAppComponent() { return this.appComponent; } }
true
a6a3b211e2b9b2242504bf091b750ba9f7653c03
Java
9526xu/sion
/sion-core/src/main/java/com/lol/sion/core/pojo/response/NasdaqEarningListResponse.java
UTF-8
2,253
1.609375
2
[]
no_license
package com.lol.sion.core.pojo.response; import lombok.Data; import java.util.Date; /** * @Author andyXu(xiaohei) xiaohei@maihaoche.com * @Date 2017/6/2 */ @Data public class NasdaqEarningListResponse { /** * This field corresponds to the database column nasdq_earning.earning_id */ private Long earningId; /** * This field corresponds to the database column nasdq_earning.gmt_create */ private Date gmtCreate; /** * This field corresponds to the database column nasdq_earning.gmt_modified */ private Date gmtModified; /** * This field corresponds to the database column nasdq_earning.is_deleted */ private Integer isDeleted; /** * This field corresponds to the database column nasdq_earning.company */ private String company; /** * This field corresponds to the database column nasdq_earning.code */ private String code; /** * This field corresponds to the database column nasdq_earning.capital_amount */ private String capitalAmount; /** * This field corresponds to the database column nasdq_earning.expect_date */ private String expectDate; /** * This field corresponds to the database column nasdq_earning.deadline_date */ private String deadlineDate; /** * This field corresponds to the database column nasdq_earning.per_share_earnings_expect */ private String perShareEarningsExpect; /** * This field corresponds to the database column nasdq_earning.expect_num */ private String expectNum; /** * This field corresponds to the database column nasdq_earning.last_year_report_date */ private String lastYearReportDate; /** * This field corresponds to the database column nasdq_earning.last_year_per_share_earnings */ private String lastYearPerShareEarnings; /** * This field corresponds to the database column nasdq_earning.publish_time */ private String publishTime; /** * This field corresponds to the database column nasdq_earning.title */ private String title; private Integer publishTimeType; private String reportStr; private String tickerSymbolCn; }
true
76fd1b025f18ac59532e8b2cb911f485ef1bfba1
Java
kykkyn2/java
/sample_code/src/Entry/Entry_exam.java
UTF-8
489
3.28125
3
[]
no_license
package Entry; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class Entry_exam { public static void main(String[] args) { Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("1_key", "1_value"); dataMap.put("2_key", "2_value"); dataMap.put("3_key", "3_value"); for(Entry<String,Object> entry : dataMap.entrySet()){ System.out.println( entry.getKey() + "=======" + entry.getValue() ); } } }
true
d27c823c2b092d402373a15e594752301e2165b5
Java
sganapavarapu1sfdc/interviews-dump
/apple-range-checker/src/IRangeTracker.java
UTF-8
198
2.140625
2
[]
no_license
public interface IRangeTracker { void addRange(int min, int max); boolean queryRange(int min, int max); boolean deleteRange(int min, int max); void listRanges(); // in-order print }
true
dbf7e1bebd567aaaedb5677d925e67f623528070
Java
jjy2301/scouter
/scouter.client/src/scouter/client/constants/MenuStr.java
UTF-8
13,567
1.523438
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.client.constants; public class MenuStr { // @ObjectNavigationView.java - ServerObject public static final String TIME_ALL = "Time All"; public static final String TIME_ALL_ID = "scouter.client.contextmenu.serverobject.timeallcounter"; public static final String DAILY_ALL = "Daily All"; public static final String DAILY_ALL_ID = "scouter.client.contextmenu.serverobject.dailyallcounter"; public static final String TIME_TOTAL = "Time Total"; public static final String TIME_TOTAL_ID = "scouter.client.contextmenu.serverobject.timetotalcounter"; public static final String DAILY_TOTAL = "Daily Total"; public static final String DAILY_TOTAL_ID = "scouter.client.contextmenu.serverobject.dailytotalcounter"; public static final String STATUS_DASHBOARD_REAL = "Status Dashboard"; public static final String ALERT_REAL = "Alert"; public static final String ACTIVE_SPEED_REAL = "Active Speed"; public static final String ACTIVE_SPEED_REAL_ID = "scouter.client.actions.counter.activespeed"; public static final String SERVICE_COUNT = "24H Service Count"; public static final String SERVICE_COUNT_ID = "scouter.client.actions.counter.servicecount"; public static final String HOURLY_CHART = "Hourly Chart"; public static final String HOURLY_CHART_ID = "scouter.client.actions.counter.hourlychart"; public static final String TODAY_SERVICE_COUNT = "Today Service Count"; public static final String TODAY_SERVICE_COUNT_ID = "scouter.client.actions.counter.todayservicecount"; public static final String XLOG = "XLog"; public static final String XLOG_ID = "scouter.client.actions.counter.XLog"; public static final String REALTIME_XLOG = "Realtime XLog"; public static final String REALTIME_XLOG_ID = "scouter.client.actions.counter.realTimeXLog"; public static final String PASTTIME_XLOG = "Pasttime XLog"; public static final String PASTTIME_XLOG_ID = "scouter.client.actions.counter.loadTimeXLog"; public static final String DIGITAL_COUNT = "Digital Count"; public static final String DIGITAL_COUNT_ID = "scouter.client.menu.performance.real.digitalcount"; public static final String LOAD_SERVICE_COUNT = "Load Service Count "; public static final String LOAD_SERVICE_COUNT_ID = "scouter.client.actions.counter.loadservicecount"; public static final String OTHER_REAL_PERFORMANCE_VIEWS = "other Real Performance views..."; public static final String OTHER_REAL_PERFORMANCE_VIEWS_ID = "scouter.client.menu.performance.real.other"; public static final String OTHER_PAST_PERFORMANCE_VIEWS = "other Past Performance views..."; public static final String OTHER_PAST_PERFORMANCE_VIEWS_ID = "scouter.client.menu.performance.past.other"; public static final String OBJECT_MANAGER = "Object Manager"; public static final String ALERT_HISTORY = "Alert History"; public static final String ALERT_HISTORY_ID = "scouter.client.menu.statistics.alert"; public static final String BY_LEVEL = "By Level"; public static final String BY_TITLE = "By Title"; public static final String ALERT_DETAIL_LIST = "Alert Detail List"; public static final String SERVER_THREAD_LIST = "Server Thread List"; public static final String CURRENT_LOGIN_LIST = "Current Login List"; public static final String FILE_MANAGEMENT = "File Management"; public static final String STATISTICS = "Statistics"; public static final String STATISTICS_ID = "scouter.client.statistics"; public static final String REPORT = "Report"; public static final String REPORT_ID = "scouter.client.report"; public static final String DAILY_STATISTICS = "Daily Statistics"; public static final String DAILY_STATISTICS_ID = "scouter.client.statistics.daily"; public static final String SERVICE_SUMMARY = "Summary"; public static final String SERVICE_SUMMARY_ID = "scouter.client.summary.service"; public static final String HOURLY_SERVICE = "Hourly Service"; public static final String SHORT_TIME_SERVICE = "Short Time Service"; public static final String SQL_SUMMARY = "SQL Summary"; public static final String SQL_SUMMARY_ID = "scouter.client.summary.sql"; public static final String HOURLY_SQL = "Hourly SQL"; public static final String HOURLY_APP_SQL = "Hourly Service/SQL"; public static final String HOURLY_APICALL = "Hourly API Call"; public static final String HOURLY_APP_APICALL = "Hourly Service/API Call"; public static final String HOURLY_IP = "Hourly IP"; public static final String COMPARE_OBJECT = "Compare Object"; public static final String EXPORT_TO_WORKSPACE_S = "Export to Workspace"; public static final String EXPORT_TO_WORKSPACE_S_ID = "scouter.client.statistics.export"; public static final String EXPORT_DAILY_APP_SUMMARY = "Export Daily App Summary"; public static final String EXPORT_ALERT_HISTORY = "Export Alert History (Max:1000)"; public static final String EXPORT_ALL = "Export all..."; public static final String EXPORT_ALL_ID = "scouter.client.export.all"; public static final String CONFIGURATIONS = "Configurations"; public static final String CONFIGURATIONS_ID = "scouter.client.configure"; public static final String MANAGEMENT = "Management"; public static final String MANAGEMENT_ID = "scouter.client.management"; public static final String SERVER = "Server"; public static final String ALERT_RULE = "Alert Rule"; public static final String COUNTER = "Counter"; public static final String COUNTER_DESIGNER = "Counter Designer"; public static final String ACCOUNT = "Account"; public static final String ACCOUNT_ID = "scouter.client.account"; public static final String LIVE_CHART = "Live"; public static final String LOAD_CHART = "Load"; public static final String PERFORMANCE_COUNTER = "Performance Counter"; public static final String PERFORMANCE_COUNTER_ID = "scouter.client.contextmenu.agentobject.performanceCounter"; public static final String PERFORMANCE_REQUEST = "Object Request"; public static final String PERFORMANCE_REQUEST_ID = "scouter.client.contextmenu.agentobject.request"; public static final String TIME_COUNTER = "Time"; public static final String TIME_COUNTER_ID = "scouter.client.contextmenu.agentobject.timecounter"; public static final String DAILY_COUNTER = "Daily"; public static final String DAILY_COUNTER_ID = "scouter.client.contextmenu.agentobject.dailycounter"; public static final String THREAD_LIST = "Thread List"; public static final String THREAD_LIST_ID = "scouter.client.contextmenu.agentobject.threadlist"; public static final String ACTIVE_SERVICE_LIST = "Active Service List"; public static final String ACTIVE_SERVICE_LIST_ID = "scouter.client.contextmenu.agentobject.activeservicelist"; public static final String LOADED_CLASS_LIST = "Loaded Class List"; public static final String LOADED_CLASS_LIST_ID = "scouter.client.contextmenu.agentobject.loadedclasslist"; public static final String HEAP_HISTOGRAM = "Heap Histogram"; public static final String HEAP_HISTOGRAM_ID = "scouter.client.contextmenu.agentobject.heaphistogram"; public static final String HEAP_DUMP = "Heap Dump"; public static final String HEAP_DUMP_ID = "scouter.client.contextmenu.agentobject.heapdump"; public static final String HEAP_DUMP_RUN = "Run Heap Dump"; public static final String HEAP_DUMP_LIST = "List Heap Dump"; public static final String THREAD_DUMP = "Thread Dump"; public static final String THREAD_DUMP_ID = "scouter.client.contextmenu.agentobject.threaddump"; public static final String ENV = "Env"; public static final String ENV_ID = "scouter.client.contextmenu.agentobject.env"; public static final String FILE_SOCKET = "File Socket"; public static final String FILE_SOCKET_ID = "scouter.client.contextmenu.agentobject.filesocket"; public static final String RESET_CACHE = "Reset Cache"; public static final String RESET_CACHE_ID = "scouter.client.contextmenu.agentobject.resetcache"; public static final String CONFIGURE = "Configure"; public static final String CONFIGURE_ID = "scouter.client.contextmenu.agentobject.configure"; public static final String SERVER_CONFIGURES = "Configures"; public static final String SERVER_CONFIGURES_ID = "scouter.client.contextmenu.server.configures"; public static final String TELEGRAF_CONFIGURE = "Telegraf Configure"; public static final String TELEGRAF_FILE_CONFIGURE = "Edit telegraf file directly"; public static final String COUNTERS_SITE_FILE_CONFIGURE = "Edit counters.site.xml file"; public static final String ALERT_SCRIPTING = "Customizable Alert"; public static final String ALERT_SCRIPTING_ID = "scouter.client.alertScripting"; public static final String PROPERTIES = "Properties"; public static final String PROPERTIES_ID = "scouter.client.contextmenu.agentobject.properties"; public static final String EXPORT_TO_WORKSPACE = "Export to Workspace"; public static final String EXPORT_TO_WORKSPACE_ID = "scouter.client.contextmenu.agentobject.exporttoworkspace"; public static final String EXPORT_TIME_COUNTER = "Export Time Counter"; public static final String EXPORT_DAILY_COUNTER = "Export Daily Counter"; public static final String EXPORT_LOADTIME_COUNTER = "Export LoadTime Counter"; public static final String EXPORT_LOADDATE_COUNTER = "Export LoadDate Counter"; public static final String FILEDUMP = "File Dump"; public static final String FILEDUMP_ID = "scouter.client.contextmenu.agentobject.filedump"; public static final String STACK_ANALYZER = "Stack Frequency Analyzer"; public static final String STACK_ANALYZER_ID = "scouter.client.contextmenu.agentobject.stack"; public static final String DUMP_ACTIVE_SERVICE_LIST = "Dump Active Service List"; public static final String DUMP_THREAD_DUMP = "Dump Thread Dump"; public static final String DUMP_THREAD_LIST = "Dump Thread List"; public static final String DUMP_HEAPHISTO = "Dump Heaphisto"; public static final String LIST_DUMP_FILES = "List Dump Files"; public static final String SYSTEM_GC = "System.GC"; public static final String TOP = "Top"; public static final String DISK_USAGE = "Disk Usage"; public static final String NET_STAT = "Net Stat"; public static final String WHO = "Who"; public static final String MEM_INFO = "Mem Info"; public static final String BATCH_HISTORY = "Batch History"; public static final String BATCH_ACTIVE_LIST = "Batch Active List"; }
true
6114b784243ab7059cb8ef2e4fc7643e8fb82aae
Java
enaawy/gproject
/gp_JADX/org/keyczar/C8004j.java
UTF-8
1,087
1.71875
2
[]
no_license
package org.keyczar; import java.nio.ByteBuffer; import javax.crypto.Mac; import org.keyczar.exceptions.KeyczarException; import org.keyczar.p571c.C7986f; import org.keyczar.p571c.C7993g; import org.keyczar.p572d.C7996b; final class C8004j implements C7986f, C7993g { public final Mac f41026a; public final /* synthetic */ C8003i f41027b; public C8004j(C8003i c8003i) { this.f41027b = c8003i; try { this.f41026a = Mac.getInstance("HMACSHA1"); } catch (Throwable e) { throw new KeyczarException(e); } } public final void mo6656a() { try { this.f41026a.init(this.f41027b.f41024b); } catch (Throwable e) { throw new KeyczarException(e); } } public final void mo6657a(ByteBuffer byteBuffer) { this.f41026a.update(byteBuffer); } public final boolean mo6658b(ByteBuffer byteBuffer) { byte[] bArr = new byte[byteBuffer.remaining()]; byteBuffer.get(bArr); return C7996b.m38192a(this.f41026a.doFinal(), bArr); } }
true
75552d3a783be97c88023b674c9da1bbf7b59041
Java
isyzes/brewery
/src/main/java/com/example/demo/mapper/BeerRequestMapper.java
UTF-8
264
1.578125
2
[]
no_license
package com.example.demo.mapper; import com.example.demo.dto.beer.Beer; import com.example.demo.entity.BeerEntity; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface BeerRequestMapper extends DestinationMapper<Beer, BeerEntity> { }
true
305d12ebca9ebba7bdd3e12ddb92327ad2561905
Java
wellengineered-us/archive-uprising-java
/src/pln-abstractions/src/main/java/com/syncprem/uprising/pipeline/abstractions/middleware/MiddlewareBuilderImpl.java
UTF-8
4,621
2.09375
2
[ "MIT" ]
permissive
/* Copyright ©2017-2019 SyncPrem, all rights reserved. Distributed under the MIT license: https://opensource.org/licenses/MIT */ package com.syncprem.uprising.pipeline.abstractions.middleware; import com.syncprem.uprising.infrastructure.configuration.ConfigurationObject; import com.syncprem.uprising.infrastructure.polyfills.*; import com.syncprem.uprising.streamingio.primitives.SyncPremException; import java.util.ArrayList; import java.util.List; public final class MiddlewareBuilderImpl<TData, TComponent extends Creatable & Disposable, TConfiguration extends ConfigurationObject> implements MiddlewareBuilder<TData, TComponent>, MiddlewareBuilderExtensions<TData, TComponent, TConfiguration> { public MiddlewareBuilderImpl() { this(new ArrayList<>()); } public MiddlewareBuilderImpl(List<MiddlewareChainDelegate<MiddlewareDelegate<TData, TComponent>, MiddlewareDelegate<TData, TComponent>>> components) { if (components == null) throw new ArgumentNullException("components"); this.components = components; } private final List<MiddlewareChainDelegate<MiddlewareDelegate<TData, TComponent>, MiddlewareDelegate<TData, TComponent>>> components; private List<MiddlewareChainDelegate<MiddlewareDelegate<TData, TComponent>, MiddlewareDelegate<TData, TComponent>>> getComponents() { return this.components; } @Override public MiddlewareDelegate<TData, TComponent> build() throws SyncPremException { MiddlewareDelegate<TData, TComponent> transform = (data, target) -> target; // simply return original target unmodified // REVERSE LIST - LIFO order for (int i = this.getComponents().size() - 1; i >= 0; i--) { final MiddlewareChainDelegate<MiddlewareDelegate<TData, TComponent>, MiddlewareDelegate<TData, TComponent>> component = this.getComponents().get(i); final MiddlewareDelegate<TData, TComponent> _transform = transform; if (component == null) continue; transform = component.invoke(_transform); } return transform; } @Override public MiddlewareBuilder<TData, TComponent> from(Class<? extends Middleware<TData, TComponent, TConfiguration>> middlewareClass, TConfiguration middlewareConfiguration) throws SyncPremException { if (middlewareClass == null) throw new ArgumentNullException("middlewareClass"); if (middlewareConfiguration == null) throw new ArgumentNullException("middlewareConfiguration"); return this.use(next -> { return (data, target) -> { TComponent newTarget; if (data == null) throw new InvalidOperationException("data"); if (target == null) throw new InvalidOperationException("target"); if (middlewareClass == null) throw new InvalidOperationException("middlewareClass"); if (middlewareConfiguration == null) throw new InvalidOperationException("middlewareConfiguration"); try (Middleware<TData, TComponent, TConfiguration> middleware = Utils.newObjectFromClass(middlewareClass)) { if (middleware == null) throw new InvalidOperationException("middleware"); middleware.setConfiguration(middlewareConfiguration); middleware.create(); newTarget = middleware.process(data, target, next); return newTarget; } catch (Exception ex) { throw new SyncPremException(ex); } }; }); } @Override public MiddlewareBuilderImpl<TData, TComponent, TConfiguration> use(MiddlewareChainDelegate<MiddlewareDelegate<TData, TComponent>, MiddlewareDelegate<TData, TComponent>> middleware) { if (middleware == null) throw new ArgumentNullException("middleware"); this.getComponents().add(middleware); return this; } @Override public MiddlewareBuilderImpl<TData, TComponent, TConfiguration> with(Middleware<TData, TComponent, TConfiguration> middleware) throws SyncPremException { if (middleware == null) throw new ArgumentNullException("middleware"); return this.use(next -> { return (data, target) -> { TComponent newTarget; if (data == null) throw new InvalidOperationException("data"); if (target == null) throw new InvalidOperationException("target"); if (middleware == null) throw new InvalidOperationException("middleware"); try { if (!middleware.isCreated() || middleware.isDisposed()) ; newTarget = middleware.process(data, target, next); return newTarget; } catch (Exception ex) { throw new SyncPremException(ex); } }; }); } }
true
0bea3ccc792c5a78560da59654e7af7c0fb6ca97
Java
regolakit/regola-kit
/regola-kit/regola-web/src/main/java/org/regola/validation/QueryFilterBuilder.java
UTF-8
181
1.757813
2
[]
no_license
package org.regola.validation; import org.regola.model.ModelPattern; public interface QueryFilterBuilder { public void decorate(Object ormQueryBuilder, ModelPattern filter); }
true
ea1e1cfdd593ba7f567c5e55a19a2fbee8ad90ca
Java
dasarisaichandana/java-hcl
/Assignment5/src/com/rel/Relational.java
UTF-8
466
2.65625
3
[]
no_license
package com.rel; public class Relational { public int greater (int a,int b) { if(a>b) { return a; } else { return b; } } public int less(int a,int b) { if(a<b) { return a; } else { return b; } } public int greaterThan(int a,int b) { if(a>=b) { return a; } else { return b; } } public double lessthan(int a,int b) { if(a>b) { return a; } else { return b; } } }
true
e75649dfae2fbd9ab7907f36a8e64008cdfc2815
Java
hongyuan-wang/mage
/mage-server/src/main/java/com/yuanwhy/mage/demo/server/MageServer.java
UTF-8
1,977
2.34375
2
[ "Apache-2.0" ]
permissive
package com.yuanwhy.mage.demo.server; import com.yuanwhy.mage.registry.api.MageRegistry; import com.yuanwhy.mage.rpc.protocol.Protocol; import com.yuanwhy.mage.rpc.rmi.RmiInvocationHandler; import com.yuanwhy.mage.rpc.rmi.RmiInvocationHandlerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.HashSet; import java.util.Set; /** * Created by hongyuan.wang on 31/10/2017. */ public class MageServer { private static Logger logger = LoggerFactory.getLogger(MageServer.class); private MageRegistry registry; private int port; private Set<Class> ifaces = new HashSet<>(); private Registry rmiRegistry; private Protocol protocol; public MageServer(MageRegistry registry, int port) { this.registry = registry; this.port = port; } public MageRegistry getRegistry() { return registry; } public int getPort() { return port; } public <T> void exportService(Class<T> iface, Object impl){ ifaces.add(iface); try { RmiInvocationHandler rmiInvocationHandler = new RmiInvocationHandlerImpl(impl); UnicastRemoteObject.exportObject(rmiInvocationHandler, 0); if (rmiRegistry == null) { init(); } rmiRegistry.rebind(iface.getName(), rmiInvocationHandler); } catch (RemoteException e) { logger.error("add one service error"); throw new RuntimeException(e); } } private void init() { try { rmiRegistry = LocateRegistry.createRegistry(port); logger.info("mage server is running"); } catch (RemoteException e) { logger.error("init mage server error"); throw new RuntimeException(e); } } }
true
9340f411ff910e1a00b2879dd435f0a656b026d6
Java
majagulan/Seat-reservation
/isa2017/src/main/java/ftn/isa/entity/users/Friend.java
UTF-8
1,431
2.140625
2
[]
no_license
package ftn.isa.entity.users; import java.beans.Transient; import java.io.Serializable; import javax.persistence.AssociationOverride; import javax.persistence.AssociationOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Table; @Entity @Table(name = "friend") @AssociationOverrides({ @AssociationOverride(name = "pk.sender", joinColumns = @JoinColumn(name = "SENDER_ID")), @AssociationOverride(name = "pk.reciever", joinColumns = @JoinColumn(name = "RECIEVER_ID")) }) public class Friend implements Serializable { /** * */ private static final long serialVersionUID = 8073014162857692185L; @EmbeddedId FriendId pk = new FriendId(); @Column(name = "STATUS", nullable = false) private boolean status; @Transient private Guest getSender(){ return pk.getSender(); } @Transient public Guest getReciever(){ return pk.getReciever(); } public void setSender(Guest sender){ pk.setSender(sender); } public void setReciever(Guest reciever){ pk.setReciever(reciever); } public FriendId getPk() { return pk; } public void setPk(FriendId pk) { this.pk = pk; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
true
d06e6921198c884efa7e528b17b067a38dbd50b2
Java
anirudhy88/DS-Project-Three
/SimpleDht/app/src/main/java/edu/buffalo/cse/cse486586/simpledht/SimpleDhtActivity.java
UTF-8
4,693
2.390625
2
[]
no_license
package edu.buffalo.cse.cse486586.simpledht; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.telephony.TelephonyManager; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.TextView; public class SimpleDhtActivity extends Activity { static final String TAG = SimpleDhtActivity.class.getSimpleName(); private static final String KEY_FIELD = "key"; private static final String VALUE_FIELD = "value"; private static int sequenceNum = 0; private static final Uri uri = Uri.parse("content://edu.buffalo.cse.cse486586.simpledht.provider"); public static String nodeId = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_dht_main); TextView tv = (TextView) findViewById(R.id.textView1); tv.setMovementMethod(new ScrollingMovementMethod()); findViewById(R.id.button3).setOnClickListener( new OnTestClickListener(tv, getContentResolver())); // Button 1 is LDump, so get local DHT key,value pairs by querying the CP with @ // as selection parameter findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = getContentResolver().query(uri, null, "@", null, null); Log.i(TAG, "After getting cursor object"); if (cursor == null) { Log.e(TAG, "Result null"); try { throw new Exception(); } catch (Exception e) { Log.e(TAG, "cursor object is null"); } } if(cursor.moveToFirst()) { do { String cursorData = cursor.getString(cursor.getColumnIndex("key")); TextView localTextView = (TextView) findViewById(R.id.textView1); localTextView.append("\t" + cursorData); // This is one way to display a string. TextView remoteTextView = (TextView) findViewById(R.id.textView1); remoteTextView.append("\n"); } while(cursor.moveToNext()); } // Play with cursor to display the results onto the textView1 and // then close the cursor } }); // Button 2 is DDump, so get entire DHT key,value pairs by querying the CP with * // as selection parameter findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = getContentResolver().query(uri, null, "*", null, null); if (cursor == null) { Log.e(TAG, "Result null"); try { throw new Exception(); } catch (Exception e) { Log.e(TAG, "cursor object is null"); } } if(cursor.moveToFirst()) { do { String cursorData = cursor.getString(cursor.getColumnIndex("key")); cursorData += " " + cursor.getString(cursor.getColumnIndex("value")); TextView localTextView = (TextView) findViewById(R.id.textView1); localTextView.append("\t" + cursorData); // This is one way to display a string. TextView remoteTextView = (TextView) findViewById(R.id.textView1); remoteTextView.append("\n"); } while(cursor.moveToNext()); } } }); /* Uri uri = Uri.parse("content://edu.buffalo.cse.cse486586.groupmessenger1.provider"); // Building ContentValues Object ContentValues contVal = new ContentValues(); contVal.put(KEY_FIELD, Integer.toString(sequenceNum)); contVal.put(VALUE_FIELD,strReceived); // Inserting getContentResolver().insert(uri, contVal);*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_simple_dht_main, menu); return true; } }
true
19e43c686653bac1ea213fbf01168c73fb5880b0
Java
shahbazmansahia/CS-151-Object-Oriented-Programming
/Mancala/src/src/BoardFrame.java
UTF-8
8,181
3.234375
3
[]
no_license
//comment import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.*; public class BoardFrame extends JFrame { public Board board; //constructor public BoardFrame() { JFrame setupFrame = new JFrame(); setupFrame(setupFrame); } //frame for setting up the mancala game, how many stones? public void setupFrame(JFrame sFrame) { //set size of the setup frame with a title sFrame.setSize(400, 285); sFrame.setTitle("Mancala Setup"); sFrame.setLayout(new BorderLayout()); //create title label and set font and size JLabel setupTitle = new JLabel("Mancala Setup Settings", JLabel.CENTER); setupTitle.setFont(new Font("Times New Roman", Font.BOLD, 30)); //create panel that will display all prompts for game info JPanel gameInfoPanel = new JPanel(); gameInfoPanel.setLayout(new BorderLayout()); //create prompt for how many stones to begin with, and radio buttons and set action commands to identify which radio was chosen JLabel stonePrompt = new JLabel("How many stones would you like to start with?"); JRadioButton threeStone = new JRadioButton("3"); threeStone.setActionCommand("3"); threeStone.setSelected(true); JRadioButton fourStone = new JRadioButton("4"); fourStone.setActionCommand("4"); fourStone.setSelected(false); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(threeStone); buttonGroup.add(fourStone); //create a stone panel, add prompt and stone radio buttons to stone panel JPanel stonePanel = new JPanel(); stonePanel.setLayout(new FlowLayout()); stonePanel.add(stonePrompt); stonePanel.add(threeStone); stonePanel.add(fourStone); //add the stone panel to the main gameInfoPanel gameInfoPanel.add(stonePanel, BorderLayout.NORTH); //create panel for holding name prompts and text boxes JPanel namePanel = new JPanel(); namePanel.setLayout(new FlowLayout()); //create prompt and textbox for getting name of player A JLabel firstPlayerPrompt = new JLabel("Enter the name of Player A"); JTextField firstPlayerName = new JTextField("Player A", 20); //add first player prompt and textbox to the namePanel namePanel.add(firstPlayerPrompt); namePanel.add(firstPlayerName); //create prompt and text box for getting name of player b JLabel secondPlayerPrompt = new JLabel("Enter the name of Player B"); JTextField secondPlayerName = new JTextField("Player B", 20); //add second player prompt and text box to the namePanel namePanel.add(secondPlayerPrompt); namePanel.add(secondPlayerName); //add namePanel to the main gameInfoPanel gameInfoPanel.add(namePanel, BorderLayout.CENTER); //create a panel to hold radio buttons for the different themes JPanel themePanel = new JPanel(); themePanel.setLayout(new FlowLayout()); //create label for prompt and radio buttons for each theme and set action commands to identify which radio was chosen JLabel themePrompt = new JLabel("Select a theme: "); JRadioButton rainbowTheme = new JRadioButton("Rainbow theme"); rainbowTheme.setActionCommand("Rainbow"); rainbowTheme.setSelected(true); JRadioButton christmasTheme = new JRadioButton("Christmas theme"); christmasTheme.setActionCommand("Christmas"); christmasTheme.setSelected(false); ButtonGroup themeGroup = new ButtonGroup(); themeGroup.add(rainbowTheme); themeGroup.add(christmasTheme); //add prompt and buttons to the themePanel themePanel.add(themePrompt); themePanel.add(rainbowTheme); themePanel.add(christmasTheme); //add the themePanel to the main gameInfoPanel gameInfoPanel.add(themePanel, BorderLayout.SOUTH); //create a panel to hold the start button and the quit button JPanel startPanel = new JPanel(); //create a start button with action to get information, dispose of this setup screen, and call the gameFrame JButton startButton = new JButton("Start"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //get number of stones input from setup menu int stones = Integer.parseInt(buttonGroup.getSelection().getActionCommand()); board = new Board(stones); //get names of players from JTextFields and set them in the model board.setPlayerAsName(firstPlayerName.getText()); board.setPlayerBsName(secondPlayerName.getText()); //get the theme input from setup menu String theme = themeGroup.getSelection().getActionCommand(); sFrame.dispose(); //if theme selected is rainbow, send rainbow theme if(theme.equals("Rainbow")) { //get rainbow image BufferedImage img = null; try{ img = ImageIO.read(new File("rainbow.jpg")); } catch (IOException e1) { e1.printStackTrace(); } //create a theme strategy, given rainbow theme and image associated BoardStrategy strategy = new RainbowTheme(img); //call game frame method to create frame using this theme gameFrame(strategy); } else //else send christmas theme { //gameFrame(); } } }); startButton.setBackground(Color.WHITE); //create a quit button with action to exit when pressed JButton quitButton = new JButton("Quit"); quitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); quitButton.setBackground(Color.RED); //add these buttons to the startPanel startPanel.add(startButton); startPanel.add(quitButton); //add title to the NORTH, gameInfo to the CENTER, and startPanel to the SOUTH sFrame.add(setupTitle, BorderLayout.NORTH); sFrame.add(gameInfoPanel, BorderLayout.CENTER); sFrame.add(startPanel, BorderLayout.SOUTH); sFrame.setVisible(true); sFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //function for drawing out the game frame, automatically called by setupFrame public void gameFrame(BoardStrategy strategy) { setSize(1000,700); setTitle("Mancala"); setLayout(new BorderLayout()); //load background image from files and set to this frame Image img = strategy.getBackgroundImage(); getContentPane().add(new BackgroundPanel(img)); //create undoPanel to hold the undo button JPanel undoPanel = new JPanel(); undoPanel.setLayout(new FlowLayout()); //create undo button and set its preferred size and add it to the undoPanel JButton undoButton = new JButton("Undo"); undoButton.setPreferredSize(new Dimension(80,20)); undoPanel.add(undoButton, BorderLayout.NORTH); //add undoPanel to NORTH side of the backgroundImg label add(undoPanel, BorderLayout.NORTH); //create panel to hold all pits, 12 in total JPanel pitsPanel = new JPanel(); pitsPanel.setLayout(new GridLayout(2, 6)); //iterate 12 times to create all pits as JButtons, adding all pits to pitsPanel for(int i = 0; i < 12; i++) { JButton pit = new JButton(); pit.setPreferredSize(new Dimension(50,50)); strategy.setBackgroundColor(pit); strategy.addStone(pit, board.getNumOfStones()); pitsPanel.add(pit); } //add pitsPanel to CENTER of background JLabel add(pitsPanel, BorderLayout.CENTER); //create east side mancala pit JPanel eastMancala = new BackgroundPanel(img); JButton mancalaA = new JButton(); mancalaA.setEnabled(false); mancalaA.setPreferredSize(new Dimension(200, 300)); mancalaA.setBackground(Color.LIGHT_GRAY); eastMancala.add(mancalaA); //create west side mancala pit JPanel westMancala = new BackgroundPanel(img); JButton mancalaB = new JButton(); mancalaB.setEnabled(false); mancalaB.setPreferredSize(new Dimension(200, 300)); mancalaB.setBackground(Color.LIGHT_GRAY); westMancala.add(mancalaB); add(westMancala, BorderLayout.WEST); add(eastMancala, BorderLayout.EAST); //--------------------------------------------------------------------------- setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
true
1c308701d89ad77d6d2e4563c3c21d88a8a1007e
Java
itakigawa/itakigawa.github.io
/old/csit_java/2017/Judge2.java
UTF-8
2,749
3.09375
3
[]
no_license
import java.util.Scanner; import java.util.HashMap; public class Judge2 { private String name; private JankenPlayer[] players; private Hand[] hands; public Judge2(String name){ this.name = name; } public String getName(){ return this.name; } public void setPlayers(JankenPlayer[] players){ this.players = players; } private void notifyAll(Hand handWin, Hand handLose){ for(int i=0; i<players.length; i++){ if(hands[i]==handWin){ players[i].notify(Result.WIN); }else if(hands[i]==handLose){ players[i].notify(Result.LOSE); } } } public void play(){ hands = new Hand[players.length]; int countRock=0, countScissors=0, countPaper=0; for(int i=0; i<players.length; i++){ hands[i] = players[i].showHand(); if(hands[i]==Hand.ROCK){ countRock += 1; }else if(hands[i]==Hand.SCISSORS){ countScissors += 1; }else if(hands[i]==Hand.PAPER){ countPaper += 1; } System.out.println(players[i].getName()+" "+hands[i]); } if(countRock==players.length || countScissors==players.length || countPaper==players.length || countRock*countScissors*countPaper!=0){ // Draw for(int i=0; i<players.length; i++){ players[i].notify(Result.DRAW); } }else if (countRock==0){ // Scissors Win notifyAll(Hand.SCISSORS,Hand.PAPER); }else if(countScissors==0){ // Paper Win notifyAll(Hand.PAPER,Hand.ROCK); }else if(countPaper==0){ // Rock Win notifyAll(Hand.ROCK,Hand.SCISSORS); }else{ System.err.println("Please email to takigawa if you see this message."); } System.out.println("R:"+countRock+" S:"+countScissors+" P:"+countPaper); System.out.println(); } public static void main(String[] args) { try{ int num = Integer.parseInt(args[0]); JankenPlayer[] players = new JankenPlayer[3]; players[0] = new RandomJankenPlayer("Yamada"); players[1] = new JankenPlayerTypeA("Suzuki"); players[2] = new JankenPlayerTypeB("Tanaka"); Judge2 judge = new Judge2("Sato"); judge.setPlayers(players); for(int i=0; i<num; i++){ judge.play(); } for(int j=0; j<players.length; j++){ players[j].report(); } }catch(Exception e){ System.out.println("this requires an integer argument."); e.printStackTrace(); } } }
true
33ca757ef021583b8aead99977d82d7b4aae74b3
Java
Tronic44/How-about-Pokemon
/src/draftpanels/PanelMenu.java
UTF-8
2,080
2.421875
2
[]
no_license
package draftpanels; import java.awt.Font; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import client.MainMenu; import client.Manage; import javax.swing.JLayeredPane; @SuppressWarnings("serial") public class PanelMenu extends JPanel { private JLayeredPane panel; private static final Font FONT = new Font(Manage.FONT, Font.BOLD, 23); private JButton btnStartButton; public PanelMenu() { panel = new JLayeredPane(); panel.setBounds(0, 0, 409, 640); panel.setLayout(null); ImageIcon background = new ImageIcon(getClass().getResource("background.jpg")); Image img = background.getImage(); Image temp = img.getScaledInstance(409, 640, Image.SCALE_SMOOTH); background = new ImageIcon(temp); JLabel back = new JLabel(background); back.setLayout(null); back.setBounds(0, 0, 409, 640); panel.add(back); JLabel lblPokemonRandomDraft = new JLabel("Pokemon Random Draft"); panel.setLayer(lblPokemonRandomDraft, 1); lblPokemonRandomDraft.setBounds(17, 11, 374, 38); panel.add(lblPokemonRandomDraft); lblPokemonRandomDraft.setFont(new Font(Manage.FONT, Font.BOLD, 31)); btnStartButton = new JButton("Start Draft"); panel.setLayer(btnStartButton, 1); btnStartButton.addActionListener(e -> DraftGui.getwindow().visStartDraft()); btnStartButton.setFont(FONT); btnStartButton.setBounds(86, 109, 236, 68); panel.add(btnStartButton); JButton btnLoadDraft = new JButton("Load Draft"); panel.setLayer(btnLoadDraft, 1); btnLoadDraft.addActionListener(e -> DraftGui.getwindow().visLoadDraft()); btnLoadDraft.setFont(FONT); btnLoadDraft.setEnabled(false); btnLoadDraft.setBounds(86, 286, 236, 68); panel.add(btnLoadDraft); JButton btnExit = new JButton("Exit"); panel.setLayer(btnExit, 1); btnExit.addActionListener(e -> MainMenu.getwindow().visMainMenu()); btnExit.setFont(FONT); btnExit.setBounds(85, 463, 239, 68); panel.add(btnExit); add(panel); } public void renamebtn(String s) { btnStartButton.setText(s); } }
true
2d35f7132079374d77345569a2cb107cb4cf9c2a
Java
SebastianMonteroC/File-Compressor
/EscritorDeBytes.java
UTF-8
1,020
3.703125
4
[]
no_license
import java.io.*; public class EscritorDeBytes{ private BufferedOutputStream salida; private String path; public EscritorDeBytes( String nombre){ try { FileOutputStream file = new FileOutputStream(nombre); salida = new BufferedOutputStream( file ); this.path = nombre; } catch(IOException e){ System.err.println("Error al crear archivo "+nombre); } } /* Funcion: Escribe un byte en un archivo. *Param: int elByte que sera escrito *Return: void */ public void guardar(int elByte){ try { salida.write(elByte); } catch(IOException e){ System.err.println("Error al escribir en archivo "); } } /* Funcion: Cierra el archivo. *Param: --- *Return: void */ public void close(){ try { salida.close(); } catch(IOException e){ System.err.println("Error al cerrar archivo "); } } }
true
cd10d45ebb477ecf8ea14b3be42ca196bc6fdcd9
Java
modianor/webmagic-58house
/src/main/java/cn/edu/usts/cs/webmagic/service/serviceImp/HouseInfoServiceImp.java
UTF-8
1,088
2.265625
2
[]
no_license
package cn.edu.usts.cs.webmagic.service.serviceImp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.edu.usts.cs.webmagic.dao.HouseInfoDao; import cn.edu.usts.cs.webmagic.pojo.HouseInfo; import cn.edu.usts.cs.webmagic.service.HouseInfoService; @Service public class HouseInfoServiceImp implements HouseInfoService { @Autowired private HouseInfoDao houseInfoDao; @Override @Transactional public void save(HouseInfo info) { HouseInfo param = HouseInfo.builder().build(); param.setHouse_title(info.getHouse_title()); List<HouseInfo> all = findHouseInfo(param); if (all.size() == 0) { this.houseInfoDao.saveAndFlush(info); } } @Override public List<HouseInfo> findHouseInfo(HouseInfo info) { Example<HouseInfo> example = Example.of(info); List<HouseInfo> all = this.houseInfoDao.findAll(example); return all; } }
true
cb0c725aff0c20f467bb2582e231301d8d4a0ff8
Java
apache/commons-math
/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/analysis/solvers/BracketingNthOrderBrentSolverTest.java
UTF-8
8,477
2.4375
2
[ "BSD-3-Clause", "Minpack", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * 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.commons.math4.legacy.analysis.solvers; import org.apache.commons.math4.legacy.analysis.QuinticFunction; import org.apache.commons.math4.legacy.analysis.UnivariateFunction; import org.apache.commons.math4.legacy.analysis.differentiation.DerivativeStructure; import org.apache.commons.math4.legacy.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException; import org.apache.commons.math4.legacy.exception.TooManyEvaluationsException; import org.junit.Assert; import org.junit.Test; /** * Test case for {@link BracketingNthOrderBrentSolver bracketing n<sup>th</sup> order Brent} solver. * */ public final class BracketingNthOrderBrentSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ @Override protected UnivariateSolver getSolver() { return new BracketingNthOrderBrentSolver(); } /** {@inheritDoc} */ @Override protected int[] getQuinticEvalCounts() { return new int[] {1, 3, 8, 1, 9, 4, 8, 1, 12, 1, 16}; } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder1() { new BracketingNthOrderBrentSolver(1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder2() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder3() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 1); } @Test public void testConstructorsOK() { Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 2).getMaximalOrder()); } @Test public void testConvergenceOnFunctionAccuracy() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 0.001, 3); QuinticFunction f = new QuinticFunction(); double result = solver.solve(20, f, 0.2, 0.9, 0.4, AllowedSolution.BELOW_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) <= 0); Assert.assertTrue(result - 0.5 > solver.getAbsoluteAccuracy()); result = solver.solve(20, f, -0.9, -0.2, -0.4, AllowedSolution.ABOVE_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) >= 0); Assert.assertTrue(result + 0.5 < -solver.getAbsoluteAccuracy()); } @Test public void testIssue716() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 1.0e-22, 5); UnivariateFunction sharpTurn = new UnivariateFunction() { @Override public double value(double x) { return (2 * x + 1) / (1.0e9 * (x + 1)); } }; double result = solver.solve(100, sharpTurn, -0.9999999, 30, 15, AllowedSolution.RIGHT_SIDE); Assert.assertEquals(0, sharpTurn.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(sharpTurn.value(result) >= 0); Assert.assertEquals(-0.5, result, 1.0e-10); } @Test public void testFasterThanNewton() { // the following test functions come from Beny Neta's paper: // "Several New Methods for solving Equations" // intern J. Computer Math Vol 23 pp 265-282 // available here: http://www.math.nps.navy.mil/~bneta/SeveralNewMethods.PDF // the reference roots have been computed by the Dfp solver to more than // 80 digits and checked with emacs (only the first 20 digits are reproduced here) compare(new TestFunction(0.0, -2, 2) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.sin().subtract(x.multiply(0.5)); } }); compare(new TestFunction(6.3087771299726890947, -5, 10) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.pow(5).add(x).subtract(10000); } }); compare(new TestFunction(9.6335955628326951924, 0.001, 10) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.sqrt().subtract(x.reciprocal()).subtract(3); } }); compare(new TestFunction(2.8424389537844470678, -5, 5) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.exp().add(x).subtract(20); } }); compare(new TestFunction(8.3094326942315717953, 0.001, 10) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.log().add(x.sqrt()).subtract(5); } }); compare(new TestFunction(1.4655712318767680266, -0.5, 1.5) { @Override public DerivativeStructure value(DerivativeStructure x) { return x.subtract(1).multiply(x).multiply(x).subtract(1); } }); } private void compare(TestFunction f) { compare(f, f.getRoot(), f.getMin(), f.getMax()); } private void compare(final UnivariateDifferentiableFunction f, double root, double min, double max) { NewtonRaphsonSolver newton = new NewtonRaphsonSolver(1.0e-12); BracketingNthOrderBrentSolver bracketing = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-12, 1.0e-18, 5); double resultN; try { resultN = newton.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultN = Double.NaN; } double resultB; try { resultB = bracketing.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultB = Double.NaN; } Assert.assertEquals(root, resultN, newton.getAbsoluteAccuracy()); Assert.assertEquals(root, resultB, bracketing.getAbsoluteAccuracy()); // bracketing solver evaluates only function value, we set the weight to 1 final int weightedBracketingEvaluations = bracketing.getEvaluations(); // Newton-Raphson solver evaluates both function value and derivative, we set the weight to 2 final int weightedNewtonEvaluations = 2 * newton.getEvaluations(); Assert.assertTrue(weightedBracketingEvaluations < weightedNewtonEvaluations); } private abstract static class TestFunction implements UnivariateDifferentiableFunction { private final double root; private final double min; private final double max; protected TestFunction(final double root, final double min, final double max) { this.root = root; this.min = min; this.max = max; } public double getRoot() { return root; } public double getMin() { return min; } public double getMax() { return max; } @Override public double value(final double x) { return value(new DerivativeStructure(0, 0, x)).getValue(); } @Override public abstract DerivativeStructure value(DerivativeStructure t); } }
true
afebd492d80bf599d3d7c8c042206e1c94a38d34
Java
li5220008/free3
/f10Common/app/dto/financeana/EarnPowerItem.java
UTF-8
753
1.953125
2
[]
no_license
package dto.financeana; /** * User: wenzhihong * Date: 12-12-21 * Time: 下午2:29 */ public class EarnPowerItem { public String enddateStr; public double operatingProfiToRevenue;/*营业利润率*/ public double operatingMarginRatio;/*营业毛利率*/ public double rOA1B;/*资产报酬率*/ public double rOA2B;/*总资产净利润率(ROA)*/ public double netProfitToCurrentAssetB;/*流动资产净利润率*/ public double rOEB;/*净资产收益率(ROE)*/ public double returnOnInvestedCapital;/*投入资本回报率*/ public double returnOnLongTermInvested;/*长期资本收益率*/ public double operatingCostRatio;/*营业成本率*/ public double salesExpenseRate;/*销售费用率*/ }
true
2cbaa372490d15d46757b1c5950a84156f8e3b20
Java
songpq/PMD
/app/src/main/java/app/android/pmdlocker/com/pmd_locker/networks/BaseEndpoint.java
UTF-8
13,748
1.867188
2
[]
no_license
package app.android.pmdlocker.com.pmd_locker.networks; import app.android.pmdlocker.com.pmd_locker.BuildConfig; import app.android.pmdlocker.com.pmd_locker.models.responses.HLockerLocationResponse; import app.android.pmdlocker.com.pmd_locker.models.responses.UserOTPResponse; import app.android.pmdlocker.com.pmd_locker.models.responses.UserRegisterResponse; import app.android.pmdlocker.com.pmd_locker.models.responses.UserResponse; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; /** * Created by tuanhoang on 3/23/17. */ public interface BaseEndpoint { public static final String HOST = String.format("%s", BuildConfig.HOST); public static final String REGISTER_URL = "customers/register"; public static final String VERIFY_OTP_URL = "customers/verify_otp"; public static final String LOGIN_URL = "customers/login"; public static final String LOGOUT_URL = "customers/logout"; public static final String LOGIN_FACEBOOK_URL = "customers/login_via_fb"; public static final String FORGOT_PASS_URL = "customers/sent_otp_lost_password"; public static final String VERIFY_OTP_LOST_PASS_URL = "customers/verify_otp_otp_lost_password"; public static final String RESET_PASS_BY_PHONE_URL = "customers/reset_password_by_phone"; public static final String PROFILE_URL = "customers/profile"; public static final String UPDATE_CUSTOM_PROFILE_URL = "customers/update_customer_profile"; public static final String UPDATE_CUSTOM_PASSWORD_URL = "customers/update_customer_password"; public static final String LIST_KIOSK_URL = "kiosks/list_kiosk"; @GET(value = LIST_KIOSK_URL) Call<HLockerLocationResponse> getListKiosk(); @POST(value = REGISTER_URL) @FormUrlEncoded Call<UserRegisterResponse> registerUser( @Field("username") String username, @Field("email") String email, @Field("password") String password, @Field("phone") String phone, @Field("first_name") String firstName, @Field("last_name") String lastName, @Field("device_token") String deviceToken ); @POST(value = VERIFY_OTP_URL) @FormUrlEncoded Call<UserOTPResponse> verifyOTP( @Field("phone") String phone, @Field("otp_code") String otpCode ); @POST(value = FORGOT_PASS_URL) @FormUrlEncoded Call<UserOTPResponse> sentOTPLostPass( @Field("phone") String phone ); @POST(value = VERIFY_OTP_LOST_PASS_URL) @FormUrlEncoded Call<UserOTPResponse> verifyOTPLostPass( @Field("phone") String phone, @Field("reset_password_token") String OTPCode ); @POST(value = RESET_PASS_BY_PHONE_URL) @FormUrlEncoded Call<UserResponse> resetPassByPhone( @Field("phone") String phone, @Field("password") String password, @Field("confirmation_password") String confirmPass ); @POST(value = LOGIN_URL) @FormUrlEncoded Call<UserResponse> loginUserName( @Field("username") String userName, @Field("password") String password, @Field("device_token") String deviceToken ); @POST(value = LOGOUT_URL) @FormUrlEncoded Call<UserResponse> logoutUser( @Field("username") String userName ); @POST(value = LOGIN_FACEBOOK_URL) @FormUrlEncoded Call<UserResponse> loginViaFacebook( @Field("fb_id") String fb_id, @Field("fb_email") String fb_email ); @PUT(value = UPDATE_CUSTOM_PROFILE_URL) @FormUrlEncoded // @Headers("Content-Type: application/json") Call<UserResponse> updateCustomUpdateProfile( @Field("access_token") String accessToken, @Field("preferred_locker_location") String location, @Field("preferred_locker_location_name") String locationName, @Field("usage_duration") Integer duration, @Field("usage_locker") String locker ); @PUT(value = UPDATE_CUSTOM_PASSWORD_URL) @FormUrlEncoded Call<UserResponse> updateCustomPassword( @Field("access_token") String accessToken, @Field("current_password") String currentPassword, @Field("password") String password, @Field("password_confirmation") String confirm_password ); @PUT(value = UPDATE_CUSTOM_PROFILE_URL) @FormUrlEncoded Call<UserResponse> updateCustomProfile( @Field("access_token") String accessToken, @Field("first_name") String firstName, @Field("last_name") String lastName ); // public static final String HOME_URL = "load-home-screen"; // public static final String CATEGORY_URL = "category"; // public static final String COLLECTION_URL = "collection"; // public static final String APP_DETAIL_URL = "app/detail"; // public static final String REGISTER_ACCOUNT_URL = "account/register"; // public static final String LOGIN_ACCOUNT_URL = "account/login-account"; // public static final String LOGIN_FACEBOOK = "account/login-facebook"; // public static final String MENU_CATEGORIES_URL = "categories"; // public static final String MOVIES_BY_CATEGORY_URL = "movie/category"; // public static final String MOVIE_BY_ID_URL = "movie"; // public static final String LOAD_MOVIES_SCREEN_URL = "load-movie-screen"; // public static final String COMIC_DETAIL_URL = "comic"; // public static final String COMIC_BY_CATEGORY_URL = "comic/category"; // public static final String COMIC_CATEGORIES_URL = "comic/categories"; // public static final String COMMENTS_BY_APP_URL = "comments"; // public static final String GET_MENU_BY_CATEGORY_URL = "get-menu-category"; // public static final String SEARCH_URL = "search"; // public static final String GET_MENU_BY_SEARCH_URL = "get-menu-search"; // public static final String SUGGEST_SEARCH_URL = "suggest-search"; // public static final String REQUEST_APP_CONTENT_URL = "request-app/content"; // public static final String REQUEST_APP_IMAGES_URL = "request-app/image"; // public static final String REQUEST_APP_LINK_URL = "request-app/link"; // public static final String LOGOUT_ACCOUNT_URL = "account/logout"; // public static final String EVENTS_URL = "events"; // public static final String GIFTS_BY_APP_URL = "gifts"; // public static final String GIFTS_BY_USER_URL = "account/gifts"; // public static final String STORE_CHECK_UPDATE_APP_URL = "store/check-update-app"; // public static final String STORE_CHECK_UPDATE_LANG_URL = "store/check-update-language"; // public static final String STORE_CHECK_UPDATE_APP_URL = "store/check-update"; // public static final String GET_FAVORITE_APP_URL = "favourite"; // public static final String GET_FAVORITE_MENU_URL = "get-menu-favourite"; // public static final String APP_CHECK_UPDATE_URL = "app/check-update"; // public static final String RECEIVED_GIFT_CODE_URL = "receive-gift-code"; // @GET(value = HOME_URL) // Call<HomeResponse> getHome(); // // @GET(value = CATEGORY_URL) // Call<CategoryResponse> getCategoryById( // @Query("id") Integer categoryId, // @Query("p") Integer pageIndex, // @Query("sort") String sortType // ); // // @GET // Call<CategoryResponse> getCategoryByURL( // @Url String url // ); // // @GET(value = APP_DETAIL_URL) // Call<AppResponse> getAppById( // @Query("id") Integer appId // ); // // @GET(value = COLLECTION_URL) // Call<CollectionResponse> getCollectionById( // @Query("id") Integer collectionId, // @Query("page") Integer page // ); // // @POST(value = REGISTER_ACCOUNT_URL) // @FormUrlEncoded // Call<UserRegisterResponse> registerUser( // @Field("email") String email, // @Field("username") String username, // @Field("password") String password, // @Field("full_name") String fullName // ); // // @POST(value = LOGIN_ACCOUNT_URL) // @FormUrlEncoded // Call<UserRegisterResponse> loginUser( // @Field("username") String username, // @Field("password") String password // // ); // @POST(value = LOGIN_FACEBOOK) // @FormUrlEncoded // Call<UserRegisterResponse> loginFacebook( // @Field("fb_token") String accessToken // // ); // // @GET(value = MOVIES_BY_CATEGORY_URL) // Call<MCategoryResponse> getMoviesByCategory( // @Query("id") Integer categoryId // ); // // @GET(value = MOVIE_BY_ID_URL) // Call<MovieResponse> getMovieById( // @Query("id") Integer movieId // ); // // @GET(value = LOAD_MOVIES_SCREEN_URL) // Call<MCategoriesResponse> getMovieCategories(); // // // @GET(value = MENU_CATEGORIES_URL) // Call<HCategoriesResponse> getCategories( // @Query("parent") Integer parentId, // @Query("id") Integer id // ); // // @GET // Call<HCategoriesResponse> getCategoriesByURL( // @Url String url // ); // // @GET(value = COMIC_DETAIL_URL) // Call<ComicResponse> getComicById( // @Query("id") Integer id // ); // // @GET(value = COMIC_BY_CATEGORY_URL) // Call<CCategoryResponse> getComicsByCategory( // @Query("id") Integer categoryId // ); // // @GET(value = COMIC_CATEGORIES_URL) // Call<CCategoriesResponse> getComicCategories(); // // @GET(value = COMMENTS_BY_APP_URL) // Call<CommentsResponse> getCommentsByAppId( // @Query("app_id") Integer appId, // @Query("p") Integer page // ); // // @POST(value = COMMENTS_BY_APP_URL) // @FormUrlEncoded // Call<DefaultResponse> postCommentByUser( // @Field("app_id") Integer appId, // @Field("rate") Integer rate, // @Field("content") String content, // @Field("user_id") Integer userId // ); // // @GET(value = GET_MENU_BY_CATEGORY_URL) // Call<MenusResponse> getMenusByCategory( // @Query("type") Integer type, // @Query("parent_id") Integer parentId // ); // // @GET(value = SEARCH_URL) // Call<CategoriesResponse> searchByKeywords( // @Query("q") String keyword, // @Query("p") Integer page, // @Query("c") String categories // ); // // @GET(value = GET_MENU_BY_SEARCH_URL) // Call<MenusResponse> getMenusBySearchingKeywords( // @Query("q") String keyword // ); // // @GET(value = SUGGEST_SEARCH_URL) // Call<ResultsResponse> suggestSearchByKeywords( // @Query("q") String keyword, // @Query("limit") Integer limit // ); // // @GET // Call<CategoriesResponse> searchByURL( // @Url String url, // @Query("type") Integer type // ); // // @GET // Call<CategoriesResponse> favoriteByURL( // @Url String url // // ); // // // // @POST(value = REQUEST_APP_CONTENT_URL) // @FormUrlEncoded // Call<DefaultResponse> requestAppByContent( // @Field("content") String content, // @Field("device_id") String deviceId // ); // // @POST(value = REQUEST_APP_IMAGES_URL) // @Multipart // Call<DefaultResponse> requestAppByImage( // @Part("device_id") String deviceId, // @Part MultipartBody.Part image // ); // // @POST(value = REQUEST_APP_LINK_URL) // @FormUrlEncoded // Call<DefaultResponse> requestAppByLinks( // @Field("link") String link, // @Field("device_id") String deviceId // ); // // @GET(value = LOGOUT_ACCOUNT_URL) // Call<DefaultResponse> logout(); // // @GET(value = EVENTS_URL) // Call<EventsResponse> eventsByAppId( // @Query("app_id") Integer appId // ); // // @GET(value = GIFTS_BY_APP_URL) // Call<GiftsResponse> giftsByAppId( // @Query("app_id") Integer appId // ); // // @GET(value = GIFTS_BY_USER_URL) // Call<GiftsResponse> giftsByUser( // @Query("p") Integer page // ); // // @POST(value = STORE_CHECK_UPDATE_APP_URL) // @FormUrlEncoded // Call<HUpdateStoreResponse> storeCheckUpdateApp( // @Field("version_store") Integer versionStore, // @Field("version_language") Integer versionLanguage // ); // //// @GET(value = STORE_CHECK_UPDATE_LANG_URL) //// Call<StoreResponse> storeCheckUpdateLanguage( //// @Query("v") Integer version //// ); // // @GET(value = GET_FAVORITE_MENU_URL) // Call<MenusResponse> getMenuFavorite( // // ); // // @GET(value = GET_FAVORITE_APP_URL) // Call<CategoriesResponse> getFavoriteApps( // @Query("c") String category, // @Query("p") Integer page, // @Query("limit") Integer limit // ); // // @POST(value = GET_FAVORITE_APP_URL) // @FormUrlEncoded // Call<CategoriesResponse> addFavoriteApps( // @Field("app_id") Integer appId // // ); // // // @FormUrlEncoded // @HTTP(method = "DELETE",path = BaseEndpoint.GET_FAVORITE_APP_URL ,hasBody = true) // Call<CategoriesResponse> deleteFavoriteApps( // @Field("app_id") Integer appId // ); // // @POST(value = APP_CHECK_UPDATE_URL) // @FormUrlEncoded // Call<StoresResponse> checkAppUpdate( // @Field("payload") String payload // ); // // @POST(value = RECEIVED_GIFT_CODE_URL) // @FormUrlEncoded // Call<DefaultResponse> receivedGiftCode( // @Field("id") Integer id // ); }
true
a6b38e97fa43cc8ac30c5784e4d41b719b9bfe34
Java
zhongxingyu/Seer
/Diff-Raw-Data/15/15_a04331cf6416e68e5e04f7d4eb760daab2eeedd7/Parser/15_a04331cf6416e68e5e04f7d4eb760daab2eeedd7_Parser_t.java
UTF-8
4,779
2.5625
3
[]
no_license
package edu.umich.insoar.language; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.*; import org.xml.sax.SAXException; import sml.Agent; import sml.Identifier; import sml.Kernel; public class Parser { private String languageSentence; private BOLTDictionary dictionary; private Map<String,Object> tagsToWords; private String tagString; private List<EntityPattern> entityPatterns; public Parser(BOLTDictionary dictionary) { this.dictionary = dictionary; parseXMLGrammar(); } private void parseXMLGrammar(){ entityPatterns = new ArrayList<EntityPattern>(); //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file Document dom = db.parse("src/edu/umich/insoar/language/grammar.xml"); //Document dom = db.parse("./java/src/edu/umich/insoar/language/grammar.xml"); //get the root element Element docEle = dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("Pattern"); if(nl == null){ return; } //Go through each pattern in the xml document and create an EntityPattern for(int i = 0; i < nl.getLength(); i++){ EntityPattern pattern = new EntityPattern(); Element patternElement = (Element)nl.item(i); NodeList children = patternElement.getChildNodes(); for(int j = 0; j < children.getLength(); j++){ Node childNode = children.item(j); if(childNode.getNodeName().equals("Regex")){ pattern.regex = Pattern.compile(childNode.getTextContent()); } else if(childNode.getNodeName().equals("Tag")){ pattern.tag = childNode.getTextContent(); } else if(childNode.getNodeName().equals("EntityType")){ pattern.entityType = childNode.getTextContent(); } } //System.out.println(pattern.entityType + "; " + pattern.tag + "; " + pattern.regex); entityPatterns.add(pattern); } }catch(ParserConfigurationException pce) { pce.printStackTrace(); }catch(SAXException se) { se.printStackTrace(); }catch(IOException ioe) { ioe.printStackTrace(); } } public boolean getSoarSpeak(String latestMessage, Identifier messageId) { this.languageSentence = latestMessage; tagsToWords = new LinkedHashMap(); mapTagToWord(); this.tagString = getPOSTagString(); return traslateToSoarSpeak(messageId, getParse()); } // create tags to words mappings private void mapTagToWord(){ String[] wordSet = languageSentence.split(" "); String tag; for (int i = 0; i < wordSet.length; i++){ tag = dictionary.getTag(wordSet[i]); tagsToWords.put(tag.concat(Integer.toString(i)),wordSet[i]); } } //create a sentence of POS tags. private String getPOSTagString(){ String tagString = ""; Iterator itr = tagsToWords.entrySet().iterator(); while(itr.hasNext()){ Map.Entry pair = (Map.Entry)itr.next(); tagString = tagString+pair.getKey().toString()+" "; } return tagString.trim(); } //parse linguistic elements from the POS tagString. public String getParse() { ParserUtil util = new ParserUtil(); for(EntityPattern pattern : entityPatterns){ tagString = util.extractPattern(pattern, tagString, tagsToWords); } return tagString; } //Get Soar structure public boolean traslateToSoarSpeak(Identifier messageId, String tagString){ // System.out.println("tagString: " + tagString); Object obj = tagsToWords.get(tagString); if(obj == null){ return false; } try{ LinguisticEntity entity = (LinguisticEntity)obj; entity.translateToSoarSpeak(messageId, null); } catch (ClassCastException e){ return false; } return true; } }
true
7010deb331467e5db18dd03ca4051343c251b12b
Java
dkf68657/aws-iot-device-bulb
/src/main/java/com/aws/iot/training/device/DeviceSimulatorController.java
UTF-8
1,940
2.109375
2
[]
no_license
package com.aws.iot.training.device; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.amazonaws.services.iot.client.AWSIotException; import com.amazonaws.services.iot.client.AWSIotTimeoutException; import com.aws.iot.training.device.ShadowThing.Document; import com.aws.iot.training.sampleUtil.Message; @Controller @RequestMapping("/device") public class DeviceSimulatorController { @Autowired private DeviceService deviceService; @GetMapping("") public String index(@RequestParam(name = "name", required = false, defaultValue = "World") String name, HttpServletRequest request, Model model) { return "device"; } @RequestMapping(value = "/getLastStatus", produces=MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) @ResponseBody public Document getLastStatus(HttpServletRequest request) { Document document = null; try { document = deviceService.getDeviceLastStatus(); } catch (InterruptedException | AWSIotException | IOException | AWSIotTimeoutException e) { System.out.println("Not able to capture device last status."); e.printStackTrace(); } return document; } @RequestMapping(value = "/sessionid", produces=MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) @ResponseBody public Message sessionid(HttpServletRequest request) { return new Message(request.getSession().getId()); } }
true
b8dd2607d64226d9da591566668801258dfa8c55
Java
moutainhigh/bi_application
/yiyun_carservice/pcBackend/src/main/java/com/carservice/project/shop/service/ICShopGoodsService.java
UTF-8
1,472
1.984375
2
[]
no_license
package com.carservice.project.shop.service; import java.util.List; import com.carservice.project.shop.domain.CShop; import com.carservice.project.shop.domain.CShopGoods; /** * 店铺产品Service接口 * * @author carservice * @date 2020-12-12 */ public interface ICShopGoodsService { /** * 查询店铺产品 * * @param id 店铺产品ID * @return 店铺产品 */ public CShopGoods selectCShopGoodsById(Long id); /** * 查询店铺产品列表 * * @param cShopGoods 店铺产品 * @return 店铺产品集合 */ public List<CShopGoods> selectCShopGoodsList(CShopGoods cShopGoods); /** * 新增店铺产品 * * @param cShopGoods 店铺产品 * @return 结果 */ public int insertCShopGoods(CShopGoods cShopGoods); /** * 修改店铺产品 * * @param cShopGoods 店铺产品 * @return 结果 */ public int updateCShopGoods(CShopGoods cShopGoods); /** * 批量删除店铺产品 * * @param ids 需要删除的店铺产品ID * @return 结果 */ public int deleteCShopGoodsByIds(Long[] ids); /** * 删除店铺产品信息 * * @param id 店铺产品ID * @return 结果 */ public int deleteCShopGoodsById(Long id); List<CShopGoods> selectCShopGoodsByShopId(Long id); List<CShopGoods> selectCShopGoodsByShopIds(List<CShop> list,String serviceType); }
true
6b832262230431169ec1ea75c6df7f744002ee72
Java
changsongyang/boot-cloud
/springboot-sharding-jdbc/sharding-springboot-mybatisplus/src/main/java/com/hjc/sharding/demo/service/MemberService.java
UTF-8
605
1.96875
2
[]
no_license
package com.hjc.sharding.demo.service; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.hjc.sharding.demo.entity.Member; import com.hjc.sharding.demo.mapper.MemberMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Created with Intellij IDEA. * @author hjc * @version 2018/5/31 */ @Service public class MemberService extends ServiceImpl<MemberMapper, Member> { @Transactional(rollbackFor = Exception.class) public boolean save(Member member) { return super.insertOrUpdate(member); } }
true
e5af3eca97b3366676f9f1c55a49a8d43dc0c1f3
Java
zhangxw92/hello
/src/main/java/com/athome/Hello.java
UTF-8
954
2.65625
3
[]
no_license
package com.athome; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @Author zhangxw03 * @Dat 2020-11-09 11:45 * @Describe */ public class Hello { private String name; public void hello() { System.out.println("this is my first Spring!"); //System.out.println("测试获取属性值" + name); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Hello hello = (Hello) context.getBean("hello"); // hello.hello(); A a = context.getBean("a", A.class); B b = context.getBean("b", B.class); } public Hello() { System.out.println("hello create success!"); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
97359780871e3ce4936e005b47f7a5e4d29b1f0e
Java
Barrelwolf38087/jubilant-meme
/libgrapher/src/grapher/LinearFunction.java
UTF-8
608
3.84375
4
[]
no_license
package grapher; /** * Represents a linear function. * @author William Leverone * @version 1.0 * @see Function */ public class LinearFunction implements Function { /** * Represents the {@link Function Function}'s slope. */ private double m; /** * Represents the {@link Function Function}'s y-intercept. */ private double b; public LinearFunction(double slope, double yIntercept) { this.m = slope; this.b = yIntercept; } /** * @return the result of {@link #m m} * x + {@link #b b} */ public double func(double x) { return (this.m * x) + this.b; } }
true
8324532ce813ebffd4c7a4ae0efc8f0c9a737367
Java
SiroWirdo/zpi_main
/ZPI/src/main/java/main/controller/MainMenuController.java
UTF-8
327
1.921875
2
[]
no_license
package main.controller; import main.model.MapModel; import main.view.MainMenuView; public class MainMenuController { MapModel menuModel; MainMenuView menuView; public MainMenuController(MapModel menuModel) { this.menuModel = menuModel; menuView = new MainMenuView(this, menuModel); // menuView.initialize(); } }
true
002d88bfc28591379f1774dfe9e7b2225408602a
Java
aheadlcx/analyzeApk
/budejie/sources/com/sprite/ads/media/NativeMediaAdView.java
UTF-8
5,587
2.109375
2
[]
no_license
package com.sprite.ads.media; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import com.sprite.ads.DataSourceType; import com.sprite.ads.internal.bean.data.ADConfig; import com.sprite.ads.internal.bean.data.AdItem; import com.sprite.ads.internal.bean.data.MediaAdItem; import com.sprite.ads.nati.reporter.Reporter; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class NativeMediaAdView extends RelativeLayout implements MediaPlayerControl, Reporter { private ADStatusChangeListner mADStatusChangeListner; private LinkedList<MediaAdItem> mMediaAdItems; private MediaAdapter mMediaAdapter; private MediaListener mMediaListener; private MediaPlayerControler mMediaPlayerControl; private NativeMediaADListener mNativeMediaADListener; public NativeMediaAdView(Context context) { this(context, null); } public NativeMediaAdView(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public NativeMediaAdView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); this.mMediaAdItems = new LinkedList<MediaAdItem>() { private final int capacity = 10; public boolean addAll(Collection<? extends MediaAdItem> collection) { while (size() > 10 - collection.size()) { if (pollLast() == null) { break; } } return super.addAll(0, collection); } public boolean offer(MediaAdItem mediaAdItem) { return super.offerFirst(mediaAdItem); } }; } private void bindAD(MediaAdItem mediaAdItem, MediaListener mediaListener) { MediaPlayerControler createMediaPlayerControler = MediaFactory.createMediaPlayerControler(mediaAdItem.getDataSourceType()); if (createMediaPlayerControler != null) { bindAD(mediaAdItem, createMediaPlayerControler, mediaListener); } } private void bindAD(MediaAdItem mediaAdItem, MediaPlayerControler mediaPlayerControler, MediaListener mediaListener) { this.mMediaPlayerControl = mediaPlayerControler; mediaPlayerControler.bindView(this); mediaPlayerControler.setDataResoure(mediaAdItem); mediaPlayerControler.setMediaListener(mediaListener); } private boolean isBind() { return this.mMediaPlayerControl != null; } public int getCurrentPosition() { return this.mMediaPlayerControl.getCurrentPosition(); } public long getDuration() { return this.mMediaPlayerControl.getDuration(); } public int getProgress() { return this.mMediaPlayerControl.getProgress(); } public boolean isPlaying() { return this.mMediaPlayerControl.isPlaying(); } public boolean isVideoAD() { return this.mMediaPlayerControl.isVideoAD(); } void loadAd(DataSourceType dataSourceType, AdItem adItem, ADConfig aDConfig) { this.mMediaAdapter = MediaFactory.createMediaAdapter(dataSourceType, adItem, aDConfig); if (this.mMediaAdapter != null) { this.mNativeMediaADListener = new NativeMediaADListener<MediaAdItem<?>>() { public void onADLoaded(List<MediaAdItem> list) { if (list.size() > 0) { NativeMediaAdView.this.mMediaAdItems.addAll(list); } } public void onADStatusChanged(MediaAdItem<?> mediaAdItem) { if (NativeMediaAdView.this.mADStatusChangeListner != null) { NativeMediaAdView.this.mADStatusChangeListner.onADStatusChanged(mediaAdItem); } } public void onNoAD(int i) { } }; this.mMediaAdapter.loadAd(getContext(), this.mNativeMediaADListener); } } public void onClicked(View view) { this.mMediaPlayerControl.onClicked(view); } public void onExposured(View view) { this.mMediaPlayerControl.onExposured(view); } public void onPlay(View view) { this.mMediaPlayerControl.onPlay(view); } public void play() { this.mMediaPlayerControl.play(); } public MediaAdItem refreshAd() { MediaAdItem mediaAdItem = (MediaAdItem) this.mMediaAdItems.poll(); if (mediaAdItem != null) { if (isBind()) { this.mMediaPlayerControl.setDataResoure(mediaAdItem); this.mMediaPlayerControl.setMediaListener(this.mMediaListener); } else { bindAD(mediaAdItem, this.mMediaListener); } } if ((mediaAdItem == null || this.mMediaAdItems.size() <= 4) && this.mMediaAdapter != null) { this.mMediaAdapter.loadAd(getContext(), this.mNativeMediaADListener); } return mediaAdItem; } public void release() { this.mMediaPlayerControl.release(); } public void replay() { this.mMediaPlayerControl.replay(); } public void setADStatusChangeListner(ADStatusChangeListner aDStatusChangeListner) { this.mADStatusChangeListner = aDStatusChangeListner; } public void setMediaListener(MediaListener mediaListener) { this.mMediaListener = mediaListener; } public void stop() { this.mMediaPlayerControl.stop(); } }
true
ac6a4c06cb8d5a9198ff2e54424bd9b86358cbb4
Java
won21kr/Malware_Project_Skycloset
/skycloset_malware/src/android/support/v4/b/a/b.java
UTF-8
1,236
1.578125
2
[]
no_license
package android.support.v4.b.a; import android.content.res.ColorStateList; import android.graphics.PorterDuff; import android.support.v4.f.c; import android.view.MenuItem; import android.view.View; public interface b extends MenuItem { b a(c paramc); b a(CharSequence paramCharSequence); c a(); b b(CharSequence paramCharSequence); boolean collapseActionView(); boolean expandActionView(); View getActionView(); int getAlphabeticModifiers(); CharSequence getContentDescription(); ColorStateList getIconTintList(); PorterDuff.Mode getIconTintMode(); int getNumericModifiers(); CharSequence getTooltipText(); boolean isActionViewExpanded(); MenuItem setActionView(int paramInt); MenuItem setActionView(View paramView); MenuItem setAlphabeticShortcut(char paramChar, int paramInt); MenuItem setIconTintList(ColorStateList paramColorStateList); MenuItem setIconTintMode(PorterDuff.Mode paramMode); MenuItem setNumericShortcut(char paramChar, int paramInt); MenuItem setShortcut(char paramChar1, char paramChar2, int paramInt1, int paramInt2); void setShowAsAction(int paramInt); MenuItem setShowAsActionFlags(int paramInt); }
true
c0b080a3a608c797998712ed29f7e404cde7a398
Java
softwareyhl/SpringBootRESTful
/src/main/java/com/mobin/entity/Subway.java
UTF-8
1,407
2.640625
3
[]
no_license
package com.mobin.entity; /** * Created by Mobin on 2017/11/14. * @author MOBIN */ public class Subway { private int id; private String name; private String address; private String lat; private String lng; private String district; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "Subway{" + "id=" + id + ", name='" + name + '\'' + ", address='" + address + '\'' + ", lat='" + lat + '\'' + ", lng='" + lng + '\'' + ", district='" + district + '\'' + '}'; } }
true
d14d32242701c0c7106bf213c045d8d05ee6db5e
Java
ShaluDhochak/LMSAutovista2
/app/src/main/java/com/excell/lms/lmsautovista/View/Adapter/DsewiseCountAdapter.java
UTF-8
3,060
2.171875
2
[]
no_license
package com.excell.lms.lmsautovista.View.Adapter; /* Created by Shalu Dhochak on 5/4/2018. */ import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.excell.lms.lmsautovista.Model.DSEReportBean; import com.excell.lms.lmsautovista.R; import com.excell.lms.lmsautovista.View.Activity.DseWiseReportDetailActivity; import java.util.ArrayList; public class DsewiseCountAdapter extends BaseAdapter { Context context; DSEReportBean.Dsewise_Count bean; ArrayList<DSEReportBean.Dsewise_Count> allLeadsBeanList = new ArrayList<>(); LayoutInflater inflater; public DsewiseCountAdapter(Context context, ArrayList<DSEReportBean.Dsewise_Count> allLeadsBeanList) { this.context = context; this.allLeadsBeanList.clear(); this.allLeadsBeanList.addAll(allLeadsBeanList); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public Object getItem(int position) { return allLeadsBeanList.get(position); } @Override public int getCount() { return allLeadsBeanList.size(); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { bean = allLeadsBeanList.get(position); ViewHolder viewHolder; if(convertView == null) { convertView = inflater.inflate(R.layout.dse_report_list,null); viewHolder = new ViewHolder(); viewHolder.dseNameListReport_TextView = (TextView) convertView.findViewById(R.id.dseNameListReport_TextView); viewHolder.dseLnameListReport_TextView = (TextView) convertView.findViewById(R.id.dseLnameListReport_TextView); viewHolder.viewDetailsDseList_TextView = (TextView) convertView.findViewById(R.id.viewDetailsDseList_TextView); convertView.setTag(viewHolder); } else viewHolder = (ViewHolder) convertView.getTag(); viewHolder.dseNameListReport_TextView.setText(bean.getFname()); viewHolder.dseLnameListReport_TextView.setText(bean.getLname()); viewHolder.viewDetailsDseList_TextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DseWiseReportDetailActivity.class); intent.putExtra("position",position); intent.putExtra("bean", allLeadsBeanList.get(position)); intent.putParcelableArrayListExtra("arrayList",allLeadsBeanList); context.startActivity(intent); } }); return convertView; } public class ViewHolder { TextView dseNameListReport_TextView, dseLnameListReport_TextView, viewDetailsDseList_TextView; } }
true
c86961e221907bdf4d142d42b8db95a5ae7a52ac
Java
kaleido-io/tessera
/tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/node/VersionInfo.java
UTF-8
221
1.679688
2
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
package com.quorum.tessera.partyinfo.node; import java.util.Set; public interface VersionInfo { Set<String> supportedApiVersions(); static VersionInfo from(Set<String> versions) { return () -> versions; } }
true
c95b54b1a4bff4e3eecedae0e185ef53e5e8ec3e
Java
saroj-kumar-barik/hiring-events
/src/main/java/com/candidate/interview/hiringevent/runtime/service/JobDetailsModelService.java
UTF-8
1,366
2.078125
2
[]
no_license
package com.candidate.interview.hiringevent.runtime.service; import com.candidate.interview.hiringevent.runtime.dao.impl.JobDetailsDaoImpl; import com.candidate.interview.hiringevent.runtime.mock.IUserInfoService; import com.candidate.interview.hiringevent.runtime.model.JobDetails; import com.candidate.interview.hiringevent.runtime.model.SkillSet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.UUID; @Service public class JobDetailsModelService { @Autowired private JobDetailsDaoImpl jobDetailsDao; @Autowired IUserInfoService userInfoService; public JobDetails save(JobDetails jobDetails) { jobDetails.setCreatedBy(userInfoService.getCurrentLoggedInUserInfo().getUserId()); jobDetails.setResourceId("skill-"+ UUID.randomUUID().toString()); return jobDetailsDao.insert(jobDetails); } public boolean delete(Integer id) { return jobDetailsDao.delete(id)!=0; } public JobDetails findById(Integer id) { return jobDetailsDao.select(id); } public List<JobDetails> findAll() { return jobDetailsDao.selectAll(); } public JobDetails updateById(Integer id, JobDetails jobDetails) { return jobDetailsDao.update(id,jobDetails); } }
true
08521c903af5689bcdae3d43ad01c60f06bc11a7
Java
stevelinz/mapstruct-auth0
/src/main/java/com/mapstruct/demo/mapstruct/mappers/MapStructMapper.java
UTF-8
875
2.09375
2
[]
no_license
package com.mapstruct.demo.mapstruct.mappers; import com.mapstruct.demo.entities.Author; import com.mapstruct.demo.entities.Book; import com.mapstruct.demo.entities.User; import com.mapstruct.demo.mapstruct.dtos.*; import org.mapstruct.Mapper; import org.mapstruct.ReportingPolicy; import java.util.List; @Mapper( componentModel = "spring" ) public interface MapStructMapper { BookSlimDto bookToBookSlimDto( Book book ); BookDto bookToBookDto( Book book ); AuthorDto authorToAuthorDto( Author author ); AuthorAllDto authorToAuthorAllDto( Author author ); List<AuthorAllDto> authorsToAuthorAllDtos( List<Author> authors ); UserGetDto userToUserGetDto( User user ); User userPostDtoToUser( UserPostDto userPostDto ); }
true
a5209f30098b72317e30616f54f66bd3a83df509
Java
cerner/ccl-testing
/cdoc/cdoc-maven-plugin/src/test/java/com/cerner/ccl/cdoc/velocity/AbstractSourceDocumentationGeneratorTest.java
UTF-8
9,276
1.9375
2
[ "Apache-2.0" ]
permissive
package com.cerner.ccl.cdoc.velocity; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.whenNew; import java.io.File; import java.io.Writer; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.cerner.ccl.cdoc.script.ScriptExecutionDetails; import com.cerner.ccl.cdoc.velocity.navigation.Navigation; import com.cerner.ccl.cdoc.velocity.structure.RecordStructureFormatter; import com.cerner.ccl.parser.data.record.InterfaceStructureType; import com.cerner.ccl.parser.data.record.RecordStructure; /** * Unit tests for {@link AbstractSourceDocumentationGenerator}. * * @author Joshua Hyde * */ @SuppressWarnings("unused") @RunWith(PowerMockRunner.class) @PrepareForTest(value = { AbstractSourceDocumentationGenerator.class, RecordStructureFormatter.class, URL.class, VelocityContext.class }) public class AbstractSourceDocumentationGeneratorTest { @Mock private Writer writer; @Mock private File cssDirectory; @Mock private VelocityEngine engine; @Mock private ScriptExecutionDetails executionDetails; @Mock private Navigation backNav; private ConcreteGenerator generator; /** * Set up the generator for each test. */ @Before public void setUp() { generator = new ConcreteGenerator(writer, cssDirectory, executionDetails, engine, backNav); } /** * Construction with a {@code null} {@link Navigation} object for the back navigation should fail. */ @Test public void testConstructNullBackNavigation() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new ConcreteGenerator(writer, cssDirectory, executionDetails, engine, null); }); assertThat(e.getMessage()).isEqualTo("Back navigation cannot be null."); } /** * Construction with a {@code null} CSS directory should fail. */ @Test public void testConstructNullCssDirectory() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new ConcreteGenerator(writer, null, executionDetails, engine, backNav); }); assertThat(e.getMessage()).isEqualTo("CSS directory cannot be null."); } /** * Construction with a {@code null} {@link ScriptExecutionDetails} should fail. */ @Test public void testConstructNullScriptExecutionDetails() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new ConcreteGenerator(writer, cssDirectory, null, engine, backNav); }); assertThat(e.getMessage()).isEqualTo("Script execution details cannot be null."); } /** * Construction with a {@code null} {@link Writer} should fail. */ @Test public void testConstructNullWriter() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new ConcreteGenerator(null, cssDirectory, executionDetails, engine, backNav); }); assertThat(e.getMessage()).isEqualTo("Writer cannot be null."); } /** * Test the generation of documentation. * * @throws Exception * If any errors occur during the test run. */ @Test public void testGenerate() throws Exception { final VelocityContext context = mock(VelocityContext.class); whenNew(VelocityContext.class).withNoArguments().thenReturn(context); final RecordStructure request = mock(RecordStructure.class); when(request.getStructureType()).thenReturn(InterfaceStructureType.REQUEST); final RecordStructure reply = mock(RecordStructure.class); when(reply.getStructureType()).thenReturn(InterfaceStructureType.REPLY); final RecordStructure neither = mock(RecordStructure.class); generator.setRecordStructure(Arrays.asList(request, reply, neither)); final String formattedRequest = "formatted request"; final String formattedReply = "formatted reply"; final RecordStructureFormatter structureFormatter = mock(RecordStructureFormatter.class); when(structureFormatter.format(request)).thenReturn(formattedRequest); when(structureFormatter.format(reply)).thenReturn(formattedReply); whenNew(RecordStructureFormatter.class).withArguments(engine).thenReturn(structureFormatter); final Template template = mock(Template.class); when(engine.getTemplate("/velocity/source-doc.vm", "utf-8")).thenReturn(template); final Object object = new Object(); generator.setObject(object); generator.setObjectFilename("object-filename"); generator.setObjectName("object-name"); final String cssUrlExternalForm = "i/am/the/external/form/of/the/CSS/directory/URL"; URI uri = new URI("file:///" + cssUrlExternalForm); when(cssDirectory.toURI()).thenReturn(uri); generator.generate(); verify(context).put("object", object); verify(context).put("objectName", "object-name"); verify(context).put("objectFilename", "object-filename"); verify(context).put("cssDirectory", "file:/" + cssUrlExternalForm); verify(context).put("executionDetails", executionDetails); verify(context).put("backNavigation", backNav); verify(context).put("requestDefinition", formattedRequest); verify(context).put("requestRecordStructure", request); verify(context).put("replyDefinition", formattedReply); verify(context).put("replyRecordStructure", reply); template.merge(context, writer); verify(structureFormatter, never()).format(neither); } /** * Concrete generator for testing. * * @author Joshua Hyde * */ private static class ConcreteGenerator extends AbstractSourceDocumentationGenerator<Object> { private final VelocityEngine engine; private Object object; private String objectFilename; private String objectName; private List<RecordStructure> recordStructures; /** * Create a generator. * * @param writer * A {@link Writer}. * @param cssDirectory * A {@link File}. * @param details * A {@link ScriptExecutionDetails}. * @param engine * A {@link VelocityEngine}. * @param backNavigation * A {@link Navigation}. */ public ConcreteGenerator(final Writer writer, final File cssDirectory, final ScriptExecutionDetails details, final VelocityEngine engine, final Navigation backNavigation) { super(writer, cssDirectory, details, backNavigation); this.engine = engine; } /** * Set the object for which documentation is to be generated. * * @param object * The object for which documentation is to be generated. */ public void setObject(final Object object) { this.object = object; } /** * Set the filename of the object. * * @param objectFilename * The filename of the object. */ public void setObjectFilename(final String objectFilename) { this.objectFilename = objectFilename; } /** * Set the object name. * * @param objectName * The object name. */ public void setObjectName(final String objectName) { this.objectName = objectName; } /** * Set the record structures to be returned by this generator. * * @param recordStructures * A {@link List} of {@link RecordStructure} objects to be returned by this generator. */ public void setRecordStructure(final List<RecordStructure> recordStructures) { this.recordStructures = recordStructures; } @Override protected VelocityEngine getEngine() { return engine; } @Override protected Object getObject() { return object; } @Override protected String getObjectFilename() { return objectFilename; } @Override protected String getObjectName() { return objectName; } @Override protected List<RecordStructure> getRecordStructures() { return recordStructures; } } }
true
eb22d9e751b2e4b1d4a7593e82c09defaf84987d
Java
P79N6A/icse_20_user_study
/methods/Method_12191.java
UTF-8
103
2.1875
2
[]
no_license
public AbstractResultOrder withError(ResultStatusOrder status){ this.status=status; return this; }
true
8838c3b68406c677b2eae1552a7dc8d3c64e4729
Java
dreadnaught05/software-tester
/src/main/java/org/ssdt/ohio/interview/softwaretester/constants/JobStatus.java
UTF-8
141
1.539063
2
[]
no_license
package org.ssdt.ohio.interview.softwaretester.constants; public enum JobStatus { Active, Inactive, Terminated, Deceased }
true
7e5815aa8ba54c8a7b5c97089a841527c9e3ca82
Java
Ayush0410-a11y/Swiggyassigment
/Swiggy/src/test/java/com/swiggy/stepdefination/Hooks.java
UTF-8
2,990
2.15625
2
[]
no_license
package com.swiggy.stepdefination; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.Logger; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import com.swiggy.reports.ExtentTestImp; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.Scenario; public class Hooks { public static WebDriver driver; public static ExtentTest extenObj; @Before public void intilazeVarExtent(Scenario secnario) { String secnarioName= secnario.getName(); extenObj = ExtentTestImp.getReporter().startTest(secnarioName); } @Before public WebDriver intilaizeDriver() throws IOException { Properties properties = new Properties(); FileInputStream fis = new FileInputStream("C:\\Users\\HELLO\\eclipse-workspace\\Swiggy\\src\\main\\resources\\Config.properties"); properties.load(fis); String browserName =properties.getProperty("browser"); System.out.println("test case is running on "+browserName+ "browser"); if(browserName.equals("chrome")) { System.setProperty("webdriver.chrome.driver","C:\\Users\\HELLO\\eclipse-workspace\\Swiggy\\Driver\\chromedriver.exe" ); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); } else if(browserName.equals("internetexplore")) { System.setProperty("webdriver.ie.driver", "C:\\Users\\HELLO\\eclipse-workspace\\Swiggy\\Driver\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); } else if(browserName.equals("firefox")){ System.setProperty("webdriver.gecko.driver", "C:\\Users\\HELLO\\eclipse-workspace\\Swiggy\\Driver\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); } else if (browserName.equals("RcBrowser")) { DesiredCapabilities dc = new DesiredCapabilities(); dc.setBrowserName("chrome"); dc.setPlatform(Platform.WINDOWS); driver = new RemoteWebDriver(new URL("http://192.168.0.115:4444/wd/hub"),dc); } driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); return driver; } @After public WebDriver quitDriver() { driver.quit(); return driver; } @After public void endExtentRep(Scenario secnario) { if(secnario.isFailed()) { Hooks.extenObj.log(LogStatus.FAIL, "Test Case Failed"); } ExtentTestImp.getReporter().endTest(extenObj); } }
true
84ca02646a10799d844a184da27e0b3c4541a73a
Java
dazzleman/Android
/Android - 3/Lesson - 2/app/src/test/java/com/geekbrains/lesson2/RxJavaTest0.java
UTF-8
2,621
3.265625
3
[]
no_license
package com.geekbrains.lesson2; import io.reactivex.annotations.NonNull; public class RxJavaTest0 { public interface Observer<T> { void onSubscribe(@NonNull Disposable d); void onNext(@NonNull T t); void onError(@NonNull Throwable e); void onComplete(); } public interface Disposable { void dispose(); boolean isDisposed(); } public interface Subscriber<T> { void onSubscribe(@NonNull Disposable d); void onNext(@NonNull T t); void onError(@NonNull Throwable e); void onComplete(); } public interface Subscription { public void request(long n); public void cancel(); } // Observable vs Flowable // // Используйте Observable, если // 1. У вас не очень много данных и, накапливаясь, они не смогут привести к OutOfMemoryError. // 2. Вы работаете с данными, которые не поддерживают backpressure, например: touch-события. // Вы не можете попросить пользователя не нажимать на экран. // // Используйте Flowable, если // Данные поддерживают backpressure, например: чтение с диска. Вы всегда можете приостановить его, // чтобы обработать то, что уже пришло, а затем возобновить чтение. // Single // Этот источник предоставит вам либо один элемент в onNext, либо ошибку в onError, // после чего передача данных будет считаться завершенной. onComplete вы от него не дождетесь. // Completable // Этот источник предоставит вам либо onComplete, либо ошибку в onError. Никаких данных в onNext он не передаст. // Этот тип удобно использовать, когда вам нужно выполнить какую-то операцию, // которая не имеет результата, и получить уведомление, что она завершена. // Maybe // Его можно описать как Single OR Completable. Т.е. вам придет либо одно значение в onNext, либо onCompleted, но не оба. // Также может прийти onError. }
true
b44c25d50d2c9d3a93c4e1093f08f684ec978f6d
Java
iQuest-Group/students-contest-2018-PL
/src/main/java/com/iquestgroup/iqrailway/apiserver/dto/SeatDTO.java
UTF-8
428
1.8125
2
[]
no_license
package com.iquestgroup.iqrailway.apiserver.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class SeatDTO { @ApiModelProperty(value = "${swagger.properties.seatdto.id}") private Integer id; @ApiModelProperty(value = "${swagger.properties.seatdto.name}") private String name; @ApiModelProperty(value = "${swagger.properties.seatdto.available}") private boolean available; }
true
084e751d499be7ac4b174f2f2cf71c7da82a4bb0
Java
AziCat/leetcode-java
/src/test/java/code/code1850/question1813/SolutionTest.java
UTF-8
1,148
2.6875
3
[]
no_license
package code.code1850.question1813; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; public class SolutionTest extends TestCase { @Test public void test1() { Solution solution = new Solution(); Assert.assertFalse(solution.areSentencesSimilar("of", "A lot of words")); } @Test public void test2() { Solution solution = new Solution(); Assert.assertTrue(solution.areSentencesSimilar("My name is Haley", "My Haley")); } @Test public void test3() { Solution solution = new Solution(); Assert.assertTrue(solution.areSentencesSimilar("a b", "a d b")); } @Test public void test4() { Solution solution = new Solution(); Assert.assertFalse(solution.areSentencesSimilar("a", "b")); } @Test public void test5() { Solution solution = new Solution(); Assert.assertTrue(solution.areSentencesSimilar("A", "a A d A")); } @Test public void test6() { Solution solution = new Solution(); Assert.assertTrue(solution.areSentencesSimilar("A b c d e", "A b c")); } }
true
1d32f42d2758034a3693e08d38966fb8a363cb1a
Java
sebcsaba/GeoResults
/src/main/java/scs/georesults/om/szlalom/SzlalomFutamImpl.java
UTF-8
1,782
1.835938
2
[]
no_license
package scs.georesults.om.szlalom; import scs.javax.collections.List; import scs.javax.dii.DIIException; import scs.javax.rdb.RdbException; import scs.javax.rdb.RdbSession; import scs.javax.rdb.helper.RdbEntityHelper; import scs.javax.rdb.mapping.ClassMapping; import scs.javax.rdb.mapping.MappingPool; import scs.javax.rdb.mapping.PrimitiveRdbCondition; import scs.javax.rdb.mapping.fields.RdbMetaStringField; import scs.georesults.GeoDbSession; import scs.georesults.common.Futam; import scs.georesults.om.nevezes.Nevezes; import scs.georesults.om.verseny.Szlalom; public class SzlalomFutamImpl extends SzlalomFutam implements Futam { public SzlalomFutamImpl () { super(); } public SzlalomFutamImpl ( long szlid, int rajtszam ) { super( szlid, rajtszam ); } public SzlalomFutamImpl ( long szlid, int rajtszam, long vid ) { super( szlid, rajtszam, vid ); } public static List loadAllForNevezes ( RdbSession session, Nevezes nevezes ) throws RdbException { return loadAll( session, SzlalomFutam.class, "rajtszam", nevezes, "vid", nevezes ); } public static int countAllForSzlalom ( GeoDbSession db, Szlalom szlalom ) throws DIIException, RdbException { ClassMapping cm = MappingPool.getClassMapping( SzlalomFutam.class ); RdbEntityHelper helper = db.getEntityHelper( cm ); PrimitiveRdbCondition cond = new PrimitiveRdbCondition( cm.getField( "szlid" ), new Long( szlalom.getSzlid() ) ); List src = db.queryAll( helper.createCountAllFilteredStatement( cond ), RdbMetaStringField.getMetaCm() ); if ( src.size() != 1 )return 0; RdbMetaStringField.MetaData md = ( RdbMetaStringField.MetaData ) src.get( 0 ); return Integer.parseInt( md.getData() ); } }
true
66b832b0454b8d99b870673cb4287e7933c4b920
Java
Pocheng-Ko/taxi_go
/app/src/main/java/com/dk/main/MapsActivity.java
UTF-8
4,947
2.28125
2
[]
no_license
package com.dk.main; import android.location.Location; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationServices; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener { class Coordinate { protected Double dLatitude; protected Double dLongitude; public void setCoordinate(Double x, Double y) { dLatitude = x; dLongitude = y; } public Double getLatitude() { return dLatitude; } public Double getLongitude() { return dLongitude; } } protected static final String TAG = "MapActivity"; protected GoogleApiClient mGoogleApiClient; protected Location mLastLocation; private GoogleMap mMap; Coordinate Coordinate = new Coordinate(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. buildGoogleApiClient(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.getUiSettings().setZoomControlsEnabled(true); // 右下角的放大縮小功能 mMap.getUiSettings().setCompassEnabled(true); // 左上角的指南針,要兩指旋轉才會出現 mMap.getUiSettings().setMapToolbarEnabled(true); // 右下角的導覽及開啟 Google Map功能 } @Override public void onConnected(@Nullable Bundle bundle) { // 這行指令在 IDE 會出現紅線,不過仍可正常執行,可不予理會 mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { Log.i(TAG, mLastLocation.getLatitude() + ""); Log.i(TAG, mLastLocation.getLongitude() + ""); Coordinate.setCoordinate(mLastLocation.getLatitude(), mLastLocation.getLongitude()); // LatLng nowLocation = new LatLng(Coordinate.dLatitude, Coordinate.dLongitude); mMap.addMarker(new MarkerOptions().position(nowLocation).title("You are here!")); mMap.moveCamera(CameraUpdateFactory.newLatLng(nowLocation)); // } else { Toast.makeText(this, "偵測不到定位,請確認定位功能已開啟。", Toast.LENGTH_LONG).show(); } } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } }
true
633689dc7ea87b8d4773d73afe4751367f42187a
Java
setsumi/ver40-7ke6780
/ver40.ver40-maven/src/main/java/ru/ver40/system/UserGameState.java
UTF-8
3,389
2.734375
3
[]
no_license
package ru.ver40.system; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.state.StateBasedGame; import ru.ver40.TheGame; /** * Базовый класс изолированного от системы игрового стейта. Обязательно * выполнять attachToSystemState() и все суперы. */ public abstract class UserGameState { /** * ID системного стейта-владельца. Обязательно присвоить в конструкторах * наследников вызовом attachToSystemState(). */ private int m_id = -1; private final StateManager m_manager; // Менеджер стейтов приложения. private boolean m_isInitialized = false; // Флаг для инициализации через // onUpdate() и onRender() /** * Конструктор. */ public UserGameState() { m_manager = TheGame.getStateManager(); } /** * Присоединиться к родному системному стейту. Обязательно выполнить в * конструкторах наследников. */ protected void attachToSystemState(int id) { m_id = id; m_manager.getSystemState(m_id).setClient(this); } /** * Активировать себя. */ public void show() { m_manager.enter(m_id); } /** * Активировать себя модально (повесить поверх предыдущих стейтов). */ public void showModal() { m_manager.enterModal(m_id); } /** * Выйти из себя в предыдущий стейт. */ public void exitModal() { m_manager.exitModal(); } /** * Событие входа в стейт. Обязательно вызывать этот супер в наследниках. */ public void onEnter(GameContainer gc, StateBasedGame game) { gc.getInput().clearKeyPressedRecord(); } /** * Событие выхода из стейта. Обязательно вызывать этот супер в наследниках. */ public void onLeave(GameContainer gc, StateBasedGame game) { gc.getInput().clearKeyPressedRecord(); } /** * Инициализация стейта. Обязательно вызывать этот супер в наследниках. */ public void onInit(GameContainer gc, StateBasedGame game) { m_isInitialized = true; } /** * Обновление стейта. Крутится в цикле. Обязательно вызывать этот супер в наследниках. */ public void onUpdate(GameContainer gc, StateBasedGame game, int delta) { if (!m_isInitialized) { onInit(gc, game); } } /** * Рендер стейта. Крутится в цикле. Обязательно вызывать этот супер в наследниках. */ public void onRender(GameContainer gc, StateBasedGame game, Graphics g) { if (!m_isInitialized) { onInit(gc, game); } } /** * Прием нажатия клавиш. */ public abstract void onKeyPressed(int key, char c); /** * Прием отпускания клавиш. */ public abstract void onKeyReleased(int key, char c); }
true
023f1497dcc333064827e3847dc7ba986c497955
Java
infinispan/infinispan
/core/src/main/java/org/infinispan/util/logging/annotation/impl/Logged.java
UTF-8
1,057
2.328125
2
[ "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
permissive
package org.infinispan.util.logging.annotation.impl; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * <b>This annotation is for internal use only!</b> * <p/> * This annotation should be used on methods that need to be notified when information is logged by the * {@link org.infinispan.util.logging.events.EventLogger}. There is no distinction between the log level or category. * <p/> * Methods annotated with this annotation should accept a single parameter, an {@link * org.infinispan.util.logging.events.EventLog}, otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called. * * @see org.infinispan.notifications.Listener * @since 14.0 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Logged { }
true
ce8c4e121458b0ce3babe060c6c28a9752ff9886
Java
redtreelchao/spkid-scm
/spkid-scm-web/src/main/java/com/fclub/tpd/controller/ProductController.java
UTF-8
25,648
1.9375
2
[]
no_license
package com.fclub.tpd.controller; import static com.fclub.web.util.UploadUtil.deleteFile; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.fclub.common.dal.Page; import com.fclub.common.lang.BizException; import com.fclub.common.lang.utils.StringUtil; import com.fclub.common.log.LogUtil; import com.fclub.tpd.batch.importing.dto.GoodsDescDTO; import com.fclub.tpd.biz.ProductService; import com.fclub.tpd.dataobject.Brand; import com.fclub.tpd.dataobject.Category; import com.fclub.tpd.dataobject.Product; import com.fclub.tpd.dataobject.Product.GoodsColorVo; import com.fclub.tpd.dataobject.Product.GoodsSizeVo; import com.fclub.tpd.dataobject.ProductGallery; import com.fclub.tpd.dataobject.ProductSub; import com.fclub.tpd.helper.ConstantsHelper; import com.fclub.tpd.helper.SessionHelper; import com.fclub.tpd.mapper.BrandMapper; import com.fclub.tpd.mapper.CategoryMapper; import com.fclub.tpd.mapper.ProductGalleryMapper; import com.fclub.tpd.mapper.ProductSubMapper; import com.fclub.tpd.mapper.ProductTypeLinkMapper; @Controller @RequestMapping("/goods") public class ProductController extends BaseController { private LogUtil logger = LogUtil.getLogger(ProductController.class); @Autowired private ProductService productService; @Autowired private BrandMapper brandMapper; @Autowired private CategoryMapper categoryMapper; @Autowired private ProductTypeLinkMapper goodsTypeLinkMapper; @Autowired private ProductSubMapper productLaborMapper; @Autowired private ProductGalleryMapper productGalleryMapper; public static final Map<String, String> SEX_MAP = new LinkedHashMap<String, String>(); static { SEX_MAP.put("m", "男"); SEX_MAP.put("w", "女"); SEX_MAP.put("a", "全部"); } @RequestMapping("/list/main.htm") public String main(ModelMap modelMap) { List<Brand> brandList = brandMapper.findBrandsByProviderId(SessionHelper.getProvider().getProviderId()); modelMap.put("brandList", brandList); return "tpd/goods"; } @RequestMapping("/list/query.htm") public String query(ModelMap modelMap, Page<Product> page, Product goods) { List<Product> list = queryGoods(page, goods); modelMap.put("list", list); return "tpd/goodsList"; } /** * 通过分页方式查询列表信息 * @param page * @param goodsSeach * @return */ private List<Product> queryGoods(Page<Product> page, Product goods) { if (goods.getProviderGoods() != null) { goods.setProviderGoods(goods.getProviderGoods().trim()); } if (goods.getProviderCode() != null) { goods.setProviderCode(goods.getProviderCode().trim()); } if (goods.getGoodsSn() != null) { goods.setGoodsSn(goods.getGoodsSn().trim()); } if (!isAdmin()) { goods.setProviderId(getProviderId()); } page = productService.queryGoodsByPage(page, goods); //处理重复Color数据 List<Product> goodsList = page.getResult(); List<Product> list = new ArrayList<>(); for (Product good : goodsList) { list.add(handleGoodsColorData(good)); } return list; } @RequestMapping("/addTo.htm") public String addTo() { return "tpd/goodsAdd"; } @RequestMapping("/add.htm") public String add(ModelMap modelMap, Product goods) throws Exception { productService.save(goods); modelMap.addAttribute("currentUrl", "/goods/addTo.htm"); modelMap.addAttribute("backUrl", "/goods/list/main.htm"); return "commons/success2"; } @RequestMapping("/list/show.htm") public String show(ModelMap modelMap, @RequestParam("goodsId") String id) { modelMap.put("readOnly", 1); getGoodsInfo(modelMap, id); return "tpd/goodsEdit"; } /** * 编辑商品名称。 */ @ResponseBody @RequestMapping("/editGoodsName.htm") public String editGoodsName(@RequestParam("upKey") Integer productId, @RequestParam("upVal") String goodsName) { Product product = new Product(); product.setGoodsId(productId); product.setGoodsName(goodsName); productService.updateByScmProductId(product); return "success"; } /** * 编辑妈咪价。 */ @ResponseBody @RequestMapping("/editShopPrice.htm") public String editShopPrice(@RequestParam("upKey") Integer productId, @RequestParam("upVal") BigDecimal shopPrice) { Product product = new Product(); product.setGoodsId(productId); product.setShopPrice(shopPrice); productService.updateByScmProductId(product); return "success"; } @RequestMapping("/editTo.htm") public String editTo(ModelMap modelMap, @RequestParam("goodsId") String id) { getGoodsInfo(modelMap, id); return "tpd/goodsEdit"; } /** * 查询商品基本信息 */ private void getGoodsInfo(ModelMap modelMap, String id) { List<Brand> brandList = brandMapper.findBrandsByProviderId(SessionHelper.getProvider().getProviderId()); List<Category> categoryList = categoryMapper.querySubCategory(); Map<String, String> sexMap = SEX_MAP; Product goods = productService.getExtGoodsById(Integer.valueOf(id)); //商品描述(新) String content = goods.getGoodsDescAdditional(); ObjectMapper mapper = new ObjectMapper(); GoodsDescDTO goodsDescVo = null; try { if (StringUtil.isNotBlank(content)) { goodsDescVo = mapper.readValue(content, GoodsDescDTO.class); } else { goodsDescVo = new GoodsDescDTO(); } } catch (IOException e) { logger.error("商品描述(新),json数据解析错误,原始数据:{0}", e, content); throw new BizException("编辑商品,数据错误,请联系管理员!"); } // 前台分类关联信息 List<String> goodsTypeNames = goodsTypeLinkMapper.selectGoodsTypeNamesByGoodsId(Integer.valueOf(id)); modelMap.put("brandList", brandList); modelMap.put("categoryList", categoryList); modelMap.put("sexMap", sexMap); modelMap.put("goods", handleGoodsColorData(goods)); modelMap.put("goodsDescVo", goodsDescVo); modelMap.put("goodsTypeNames", goodsTypeNames); } @RequestMapping("/edit.htm") public String edit(ModelMap modelMap, Product goods, GoodsDescDTO goodsDescVo, @RequestParam("isSubmit") int isSubmit) throws Exception { Product goodsTmp = new Product(); //过滤filter字段 String[] ignoreProperties = filerDisabled(goods); BeanUtils.copyProperties(goods, goodsTmp, ignoreProperties); if (isSubmit == 1) { goodsTmp.setTpdGoodsStatus("1"); checkGoodsImportStatus(goodsTmp.getGoodsId()); } goodsTmp.setUpdateTime(new Date()); //商品描述(新) StringWriter goodsDescStrW = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(goodsDescStrW, goodsDescVo); goodsTmp.setGoodsDescAdditional(goodsDescStrW.toString()); productService.updateByScmProductId(goodsTmp); modelMap.addAttribute("backUrl", "/goods/list/main.htm"); return "commons/success2"; } @RequestMapping(value = "/batchSubmit.json") @ResponseBody public String batchSubmit(String ids) { String result = ""; try { String[] optStatusArr = {"0"}; for (String id : ids.split(",")) { checkGoodsStatus(Integer.valueOf(id), optStatusArr, "提交审核"); checkGoodsImportStatus(Integer.valueOf(id)); } productService.batchSubmit(ids); } catch (BizException e) { logger.error("批量提交审核商品失败,goodsId:{0}", e, ids); result = "批量提交审核商品失败:" + e.getMessage(); } catch (Exception e) { logger.error("批量提交审核商品失败,goodsId:{0}", e, ids); result = "批量提交审核商品失败:" + e.getMessage(); } return result; } @ResponseBody @RequestMapping(value = {"/online.json"}) public String online(@RequestParam("ids[]") Integer[] ids) { String result = ""; try { productService.online(getOperaterId(), ids); } catch (Exception e) { logger.error("上架商品失败,goodsId:{0}", e, Arrays.toString(ids)); result = "上架商品失败:" + e.getMessage(); } return result; } @ResponseBody @RequestMapping(value = {"/offline.json"}) public String offline(@RequestParam("ids[]") Integer[] ids) { String result = ""; try { productService.offline(getOperaterId(), ids); } catch (Exception e) { logger.error("下架商品失败,goodsId:{0}", e, Arrays.toString(ids)); result = "下架商品失败:" + e.getMessage(); } return result; } // ---- admin ------------------------------------------------------------- @ResponseBody @RequestMapping(value = {"/check.json"}) public String batchCheck(@RequestParam("ids[]") Integer[] ids) { String result = ""; try { productService.check(getOperaterId(), ids); } catch (Exception e) { logger.error("审核商品失败,goodsId:{0}", e, Arrays.toString(ids)); result = "审核商品失败:" + e.getMessage(); } return result; } @ResponseBody @RequestMapping(value = {"/reject.json"}) public String batchReject(@RequestParam("ids[]") Integer[] ids) { String result = ""; try { productService.reject(ids); } catch (Exception e) { logger.error("驳回商品失败,goodsId:{0}", e, Arrays.toString(ids)); result = "驳回商品失败:" + e.getMessage(); } return result; } @RequestMapping("/limit/show.htm") public String shouLimit(Integer goodsId, ModelMap modelMap) { Product product = productService.get(goodsId); modelMap.put("product", product); return "tpd/goodsLimit"; } @ResponseBody @RequestMapping("/limit/update.htm") public String updateLimit(Product product) { Integer limitNum = product.getLimitNum(); if (limitNum == null || limitNum.intValue() < 0) { product.setLimitNum(Integer.valueOf(0)); product.setLimitDay(Integer.valueOf(0)); } else { product.setLimitNum(limitNum); product.setLimitDay(Integer.valueOf(1)); //XXX:默认1天 } try { productService.updateByScmProductId(product); } catch (Exception e) { logger.error(e.getMessage(), e); return "限购设置失败!"; } return "success"; } // 检查商品信息状态 private void checkGoodsStatus(Integer id, String[] statusArr, String optMsg) { Product product = productService.get(id); boolean correctStatus = false; for (String status : statusArr) { if (StringUtil.equals(product.getTpdGoodsStatus(), status)) { correctStatus = true; break; } } if (!correctStatus) { throw new BizException(product.getGoodsSn() + " 为" + product.getTpdGoodsStatusName() + "状态,不能" + optMsg); } } // 检查商品信息导入状态 private void checkGoodsImportStatus(Integer id) { String goodsSn = productService.get(id).getGoodsSn(); List<ProductSub> goodsLaborList = productLaborMapper.selectByGoodsIdGroupByColorId(id); if (goodsLaborList == null || goodsLaborList.size() == 0) throw new BizException(goodsSn + " 还没有导入颜色尺寸.不能提交审核"); Boolean[] validateGalleryResult = new Boolean[2]; for (ProductSub goodsLabor : goodsLaborList) { validateGalleryResult = validateGoodsGallery(goodsLabor); if (!validateGalleryResult[0]) { throw new BizException(goodsSn + " 还没有导入商品默认图.不能提交审核"); } if (!validateGalleryResult[1]) { throw new BizException(goodsSn + " 还没有导入商品局部图.不能提交审核"); } } } /** * 过滤disabled字段 * @param goods */ private String[] filerDisabled(Product goods) { List<String> arrsList = new ArrayList<>(); if (StringUtil.isBlank(goods.getGoodsSn())) { arrsList.add("goodsSn"); } if (goods.getCatId() == null) { arrsList.add("catId"); } if (goods.getBrandId() == null) { arrsList.add("brandId"); } if (goods.getStyleId() == null) { arrsList.add("styleId"); } if (goods.getCoopId() == null) { arrsList.add("coopId"); } if (goods.getUnitId() == null) { arrsList.add("unitId"); } if (goods.getProviderId() == null) { arrsList.add("providerId"); } if (goods.getGoodsYear() == null) { arrsList.add("goodsYear"); } if (goods.getGoodsMonth() == null) { arrsList.add("goodsMonth"); } String[] ignoreProperties = new String[arrsList.size()]; for (int i = 0; i < ignoreProperties.length; i++) { ignoreProperties[i] = arrsList.get(i); } return ignoreProperties; } @RequestMapping(value = "/delete.json") @ResponseBody public String delete(@RequestParam("goodsId") String id) { String result = ""; try { String[] optStatusArr = {"0", "1"}; checkGoodsStatus(Integer.valueOf(id), optStatusArr, "删除"); List<ProductGallery> goodsGallerys = getGallerysByGoodsId(id); productService.deleteGoods(Integer.valueOf(id)); deleteGalleryFileByGoodsId(goodsGallerys); } catch (BizException e) { logger.error("删除商品失败,goodsId:{0}", e, id); result = "删除商品失败"; } catch (Exception e) { logger.error("删除商品失败,goodsId:{0}", e, id); result = "删除商品失败"; } return result; } @RequestMapping(value = "/batchDelete.json") @ResponseBody public String batchDelete(String ids) { String result = ""; try { String[] optStatusArr = {"0", "1"}; List<List<ProductGallery>> goodsGalleryLists = new ArrayList<List<ProductGallery>>(); for (String id : ids.split(",")) { checkGoodsStatus(Integer.valueOf(id), optStatusArr, "删除"); goodsGalleryLists.add(getGallerysByGoodsId(id)); } productService.batchDelete(ids); for (List<ProductGallery> goodsGallerys : goodsGalleryLists) { deleteGalleryFileByGoodsId(goodsGallerys); } } catch (BizException e) { logger.error("批量删除商品失败,goodsId:{0}", e, ids); result = "批量删除商品失败:" + e.getMessage(); } catch (Exception e) { logger.error("批量删除商品失败,goodsId:{0}", e, ids); result = "批量删除商品失败:" + e.getMessage(); } return result; } @RequestMapping("/validation.json") @ResponseBody public String validation(@RequestParam("key") String key, @RequestParam("value") String value, Product goods) { String result = ""; try { if (StringUtil.equals(key, "goodsSn")) { goods.setGoodsSn(value); } productService.validation(goods); } catch (BizException e) { logger.warn("Goods验证,验证失败", e); result = "商品款号已经存在"; } catch (IllegalArgumentException e) { logger.warn("Goods验证,验证失败", e); result = "商品款号已经存在"; } catch (Exception e) { logger.error("Goods验证,验证失败", e); result = "商品款号已经存在"; } return result; } @RequestMapping("/deleteGallery.json") @ResponseBody public String deleteGallery(@RequestParam("imgId") String imgId) { String result = ""; try { ProductGallery goodsGallery = productGalleryMapper.get(Integer.valueOf(imgId)); productGalleryMapper.delete(Integer.valueOf(imgId)); doDeleteGalleryFile(goodsGallery); } catch (BizException e) { logger.error("删除商品图失败,imgId:{0}", e, imgId); result = "删除商品图失败"; } catch (Exception e) { logger.error("删除商品图失败,imgId:{0}", e, imgId); result = "删除商品图失败"; } return result; } @RequestMapping("/deleteBcs.json") @ResponseBody public String deleteBcs(@RequestParam("goodsId") String goodsId) { String result = ""; try { Product goods = productService.get(Integer.valueOf(goodsId)); if (goods != null) { Product goodsTmp = new Product(); goodsTmp.setGoodsId(goods.getGoodsId()); goodsTmp.setScDesc(""); productService.update(goodsTmp); } } catch (BizException e) { logger.error("删除尺寸对照图失败,imgId:{0}", e, goodsId); result = "删除尺寸对照图失败"; } catch (Exception e) { logger.error("删除尺寸对照图失败,imgId:{0}", e, goodsId); result = "删除尺寸对照图失败"; } return result; } /** * 处理重复Color数据 * @param goods * @return */ private Product handleGoodsColorData(Product good) { List<ProductSub> goodsLabors = good.getGoodsLabors(); Product goodsVo = new Product(); BeanUtils.copyProperties(good, goodsVo); // List<GoodsColorVo> colorVos = new ArrayList<>(); if (goodsLabors != null && goodsLabors.size() > 0) for (ProductSub goodsLabor : goodsLabors) { GoodsColorVo vo = genColorVo(colorVos, goodsLabor); // GoodsSizeVo sizeVo = new GoodsSizeVo(); sizeVo.setConsignNum(goodsLabor.getConsignNum()); sizeVo.setGlId(goodsLabor.getGlId()); sizeVo.setSizeCode(goodsLabor.getSizeCode()); sizeVo.setSizeName(goodsLabor.getSizeName()); sizeVo.setProviderBarcode(goodsLabor.getTpdProviderBarcode()); sizeVo.setPic(Boolean.parseBoolean(goodsLabor.getIsPic().toString())); // List<GoodsSizeVo> sizeList = vo.getSizeList(); if (sizeList == null) { sizeList = new ArrayList<>(); } sizeList.add(sizeVo); vo.setSizeList(sizeList); vo.setGalleryList(goodsLabor.getGoodsGallerys()); } goodsVo.setColorVos(colorVos); // 检查商品信息导入状态 goodsVo.setImportStatus("Red"); List<ProductSub> goodsLaborList = productLaborMapper.selectByGoodsIdGroupByColorId(good.getGoodsId()); if (goodsLaborList != null && goodsLaborList.size() > 0) { goodsVo.setImportStatus("Yellow"); Boolean galleryCheck = true; Boolean[] validateGalleryResult = new Boolean[2]; for (ProductSub goodsLabor : goodsLaborList) { validateGalleryResult = validateGoodsGallery(goodsLabor); if (!validateGalleryResult[0] || !validateGalleryResult[1]) { galleryCheck = false; break; } } if (galleryCheck) { goodsVo.setImportStatus("Blue"); if (goodsVo.getScDesc() !=null && !"".equals(goodsVo.getScDesc())) goodsVo.setImportStatus("Green"); } } return goodsVo; } private Boolean[] validateGoodsGallery(ProductSub goodsLabor) { Boolean[] result = new Boolean[2]; HashMap<String, Object> param = new HashMap<String, Object>(); param.put("goodsId", goodsLabor.getGoodsId()); param.put("colorId", goodsLabor.getColorId()); List<ProductGallery> goodsGalleryList = productGalleryMapper.selectByGoodsId(param); boolean defaultExist = false, partExist = false; for (ProductGallery goodsGallery : goodsGalleryList) { if ("default".equals(goodsGallery.getImgDefault())) defaultExist = true; if ("part".equals(goodsGallery.getImgDefault())) partExist = true; } result[0] = defaultExist; result[1] = partExist; return result; } /** * 根据GoodsLabor判断,如果在List中存在,则直接返回,如果不存在则构建此对象设在在List中,返回此对象 * @param list * @param goodsLabor * @return */ public static GoodsColorVo genColorVo(List<GoodsColorVo> list, ProductSub goodsLabor) { for (GoodsColorVo vo : list) { if (vo.getColorId() == goodsLabor.getColorId()) { return vo; } } GoodsColorVo colorVo = new GoodsColorVo(); colorVo.setColorId(goodsLabor.getColorId()); colorVo.setColorName(goodsLabor.getColorName()); colorVo.setIsPic(goodsLabor.getIsPic()); list.add(colorVo); return colorVo; } @RequestMapping("/list/export.htm") public void export(Product goods, HttpServletResponse response) { goods.setProviderId(SessionHelper.getProvider().getProviderId()); productService.exportGoodsData(response, goods); } @RequestMapping("/consign/toUpdate.htm") public String toUpdateConsignNum(Integer glId, ModelMap modelMap) { modelMap.put("glId", glId); return "tpd/goodsConsignNum"; } @ResponseBody @RequestMapping("/consign/update.htm") public String updateConsignNum(@RequestParam("upKey") Integer glId, @RequestParam("upVal") String consignNum) { Integer consign = null; try { consign = Integer.valueOf(consignNum); } catch (Exception e) { logger.error("修改商品虚库库存失败:不是有效的数字!", e); return "商品库存必须为0或正整数!"; } ProductSub sub = productLaborMapper.get(glId); if (sub == null) { return "指定的商品SKU不存在!"; } sub.setConsignNum(consign); productService.updateConsignNum(sub); return "success"; } private List<ProductGallery> getGallerysByGoodsId(String id) { List<ProductGallery> goodsGallerys = new ArrayList<ProductGallery>(); List<ProductSub> goodsLabors = productLaborMapper.selectByGoodsId(Integer.valueOf(id)); if (goodsLabors != null && goodsLabors.size() > 0) { for (ProductSub goodsLabor : goodsLabors) { HashMap<String, Object> param = new HashMap<String, Object>(); param.put("goodsId", goodsLabor.getGoodsId()); param.put("colorId", goodsLabor.getColorId()); List<ProductGallery> goodsGalleryList = productGalleryMapper.selectByGoodsId(param); if (goodsGalleryList != null && goodsGalleryList.size() > 0) { for (ProductGallery goodsGallery : goodsGalleryList) { goodsGallerys.add(goodsGallery); } } } } return goodsGallerys; } private void deleteGalleryFileByGoodsId(List<ProductGallery> goodsGalleryList) { for (ProductGallery goodsGallery : goodsGalleryList) { doDeleteGalleryFile(goodsGallery); } } private void doDeleteGalleryFile(ProductGallery goodsGallery) { doDeleteFile(goodsGallery.getImgUrl()); doDeleteFile(goodsGallery.getThumbUrl()); doDeleteFile(goodsGallery.getMiddleUrl()); doDeleteFile(goodsGallery.getBigUrl()); doDeleteFile(goodsGallery.getTeenyUrl()); doDeleteFile(goodsGallery.getSmallUrl()); doDeleteFile(goodsGallery.getImgOriginal()); doDeleteFile(goodsGallery.getUrl120160()); doDeleteFile(goodsGallery.getUrl99132()); doDeleteFile(goodsGallery.getUrl480640()); doDeleteFile(goodsGallery.getUrl5684()); doDeleteFile(goodsGallery.getUrl222296()); doDeleteFile(goodsGallery.getUrl342455()); doDeleteFile(goodsGallery.getUrl170227()); doDeleteFile(goodsGallery.getUrl135180()); doDeleteFile(goodsGallery.getUrl251323()); doDeleteFile(goodsGallery.getUrl502646()); doDeleteFile(goodsGallery.getUrl12001600()); } private void doDeleteFile(String fileName) { if (fileName == null || fileName.isEmpty()) { return; } deleteFile(ConstantsHelper.getPicRootPath() + "/" + fileName); } }
true
98f0082757141a7dd9af80075bc406c12640f14e
Java
tinam8/Introduction-to-Java-Programming-Language
/hw12-1191226486/src/main/java/hr/fer/zemris/java/custom/scripting/elems/ElementConstantInteger.java
UTF-8
760
3.296875
3
[]
no_license
package hr.fer.zemris.java.custom.scripting.elems; /** * Class representing Element of type Integer. * * @author tina * */ public class ElementConstantInteger extends Element { /** * Read-only double property - value of expression; int */ private int value; /** * Constructor * * @param value * value of expression. */ public ElementConstantInteger(int value) { this.value = value; } /** * Gets value of read-only propertu <code>value</code> * * @return value of expression. */ public double getValue() { return value; } @Override public String asText() { return String.valueOf(value); } @Override public void accept(IElementVisitor visitor) { visitor.visitElementConstantInteger(this); } }
true
48a64da83c18119b75dcc7ce2101983d3876e6bd
Java
VitalyGryaznov/web_exercise
/src/test/java/pageObjects/travelexPages/TravelexHomePage.java
UTF-8
1,927
2.421875
2
[]
no_license
package pageObjects.travelexPages; import hooks.SetupDriverHook; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import pageObjects.BasePage; public class TravelexHomePage extends BasePage { private static final String DIRECT_LINK = "https://www.travelex.co.uk/"; @FindBy(css = ".simple__animation") private WebElement homeCards; @FindBy(css = ".hiw__header") private WebElement howItWorksHeader; private WebElement getCurentlyVisibleCartDotNumber(int number) { return setupDriverHook.getDriver().findElement(By.xpath(String.format("//ul[@class='slick-dots']/li[%d]", number))); } public TravelexHomePage(SetupDriverHook setupDriverHook) { super(setupDriverHook); } @Override public TravelexHomePage assertPageLoaded() { this.scenario.write("Making that wikipedia article page loaded"); waitForVisibilityOf(homeCards); waitForVisibilityOf(howItWorksHeader); return this; } public void swipeLeftCardsSlider(int numberOfSwipes) { WebDriver driver = setupDriverHook.getDriver(); Dimension size = driver.manage().window().getSize(); Actions builder = new Actions(driver); builder.clickAndHold(homeCards).moveByOffset(-homeCards.getSize().getWidth() / 2, 0).release().perform(); } public TravelexHomePage openItWithDirectLink() { this.scenario.write("Opening Travelex Home Page with direct link" + DIRECT_LINK); setupDriverHook.getDriver().get(DIRECT_LINK); return this.assertPageLoaded(); } public boolean currentDisplayedCardNumberIs(int number) { return getCurentlyVisibleCartDotNumber(number).getAttribute("class").equals("slick-active"); } }
true
b75e3b8b3bcd71651ae70998444fff0abe7c308f
Java
wang-shun/ecom-maindir
/ecom-cms/src/main/java/com/cn/thinkx/ecom/eshop/service/impl/EshopInfServiceImpl.java
UTF-8
1,401
1.960938
2
[]
no_license
package com.cn.thinkx.ecom.eshop.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cn.thinkx.ecom.common.service.impl.BaseServiceImpl; import com.cn.thinkx.ecom.eshop.domain.EshopInf; import com.cn.thinkx.ecom.eshop.mapper.EshopInfMapper; import com.cn.thinkx.ecom.eshop.service.EshopInfService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; @Service("eshopInfService") public class EshopInfServiceImpl extends BaseServiceImpl<EshopInf> implements EshopInfService { @Autowired private EshopInfMapper eshopInfMapper; @Override public PageInfo<EshopInf> getEshopInfPage(int startNum, int pageSize, EshopInf entity) { PageHelper.startPage(startNum, pageSize); List<EshopInf> list = eshopInfMapper.getList(entity); PageInfo<EshopInf> page = new PageInfo<EshopInf>(list); return page; } @Override public List<EshopInf> getList() { return this.eshopInfMapper.getList(); } @Override public List<EshopInf> selectByComboBox() { return this.eshopInfMapper.selectByComboBox(); } @Override public EshopInf selectByEshopName(EshopInf eshopInf) { return this.eshopInfMapper.selectByEshopName(eshopInf); } @Override public EshopInf selectByEshopInf(EshopInf eshopInf) { return this.eshopInfMapper.selectByEshopInf(eshopInf); } }
true
637e55cc8aba045b581bf165642007f63ca850f3
Java
zhaoxiansheng/MyAnimation
/DevCommon/src/main/java/com/autopai/common/utils/reflect/HardwareRenderBarrier.java
UTF-8
6,044
1.851563
2
[]
no_license
package com.autopai.common.utils.reflect; import android.graphics.Rect; import android.os.Build; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import com.autopai.common.utils.common.Utilities; import java.lang.reflect.Field; import java.lang.reflect.Method; public class HardwareRenderBarrier implements ViewRootProxySurface.ProxyCallBack { private static final String TAG = "HardwareRenderBarrier"; private PreDrawListener mPredrawListener = new PreDrawListener(); private View mBaseView; private Object mBaseHwRender; private ViewRootProxySurface mProxySurface; private boolean mHadBarrier = false; private boolean baseIsAvailable = true; private static Field mRenderField; private static Field sIsAvailableField; private static Method isAvailableMethod; private static final String HARDWARERENDER_NAME = Utilities.ATLEAST_O ? "mThreadedRenderer":"mHardwareRenderer"; private static final String HARDWARERENDER_CLASS = Utilities.ATLEAST_N ? "android.view.ThreadedRenderer":"android.view.HardwareRenderer"; static{ Class<?> attachInfoCls = ReflectUtil.getClazz("android.view.View$AttachInfo"); if(attachInfoCls != null) { mRenderField = ReflectUtil.getClassFiled(attachInfoCls, HARDWARERENDER_NAME); } Class<?> renderCls = ReflectUtil.getClazz(HARDWARERENDER_CLASS); if(attachInfoCls != null) { isAvailableMethod = ReflectUtil.getMethod(renderCls, "isAvailable", null); } if(Utilities.ATLEAST_O) { Class<?> canvasCls = ReflectUtil.getClazz("android.view.ThreadedRenderer"); if(canvasCls != null) { sIsAvailableField = ReflectUtil.getClassFiled(canvasCls, "sSupportsOpenGL"); } }else{ Class<?> canvasCls = ReflectUtil.getClazz("android.view.GLES20Canvas"); if(canvasCls != null) { sIsAvailableField = ReflectUtil.getClassFiled(canvasCls, "sIsAvailable"); } } } @Override public void onGetGenerationId() { if(mHadBarrier) { removeHwRenderBarrier(); } } @Override public boolean onRelease() { //Log.e(TAG, "root surface release at: " + Log.getStackTraceString(new Throwable())); return true; } private class PreDrawListener implements ViewTreeObserver.OnPreDrawListener { @Override public boolean onPreDraw() { if(mHadBarrier) { removeHwRenderBarrier(); } return true; //return true;//if true candraw } } public HardwareRenderBarrier(View attatchView, boolean proxySurface) { mBaseView = attatchView; init(proxySurface); } private void init(boolean proxySurface) { if(proxySurface) { /** * final int surfaceGenerationId = mSurface.getGenerationId(); * */ mProxySurface = new ViewRootProxySurface(); mProxySurface.setProxyCallBack(this); } baseIsAvailable = isHwAvaliable(); } private boolean isHwAvaliable() { Object[] ret = new Object[1]; if( ReflectUtil.callMethod(isAvailableMethod, null, null, ret) ) { return (boolean)ret[0]; } return false; } private boolean setHwIsAvaliable(boolean bAvaliable) { boolean ret = ReflectUtil.setObjectByFiled(null, bAvaliable, sIsAvailableField); return ret; } private boolean setHwRenderBarrier() { Log.e(TAG, "setHwRenderBarrier"); Object baseRootImpl = ViewRootImplUtil.getRootImpl(mBaseView); Object attachInfo = ViewRootImplUtil.getBaseAttachInfo(baseRootImpl); if(attachInfo != null) { mBaseHwRender = ReflectUtil.getObjectByFiled(attachInfo, mRenderField); mHadBarrier = ReflectUtil.setObjectByFiled(attachInfo, null, mRenderField); } return mHadBarrier; } private boolean removeHwRenderBarrier() { Log.e(TAG, "removeHwRenderBarrier"); if(mHadBarrier) { Object baseRootImpl = ViewRootImplUtil.getRootImpl(mBaseView); Object attachInfo = ViewRootImplUtil.getBaseAttachInfo(baseRootImpl); if (attachInfo != null) { mHadBarrier = !ReflectUtil.setObjectByFiled(attachInfo, mBaseHwRender, mRenderField); if (!mHadBarrier) { mBaseHwRender = null; } } } return !mHadBarrier; } private boolean needBarrier(){ Object baseRootImpl = ViewRootImplUtil.getRootImpl(mBaseView); boolean ret = !ViewRootImplUtil.getNeedNewSurface(baseRootImpl); return ret; } public void onWindowVisibilityChanged(int visibility) { if(visibility != View.VISIBLE && needBarrier()) { setHwRenderBarrier(); } } public void onAttachedToWindow() { Object baseRootImpl = ViewRootImplUtil.getRootImpl(mBaseView); boolean ret = ViewRootImplUtil.setRootImplSurface(baseRootImpl, mProxySurface); if(!ret) { Log.e(TAG, "setRootImplSurface failed, " + Log.getStackTraceString(new Throwable())); } ViewTreeObserver observer = mBaseView.getViewTreeObserver(); observer.addOnPreDrawListener(mPredrawListener); } public void onDetachedFromWindow() { ViewTreeObserver observer = mBaseView.getViewTreeObserver(); observer.removeOnPreDrawListener(mPredrawListener); } public void onStop() { setHwIsAvaliable(false); //boolean ret = isHwAvaliable(); } public void onStart() { setHwIsAvaliable(baseIsAvailable); //boolean ret = isHwAvaliable(); } public void onDestory() { //removeHwRenderBarrier(); setHwIsAvaliable(baseIsAvailable); } }
true
454c8f942ce3c4d55a76ead566a4bdb0368df3cd
Java
alkinemy/algospot
/src/com/joke/algospot/quadtree/QuadTree.java
UTF-8
1,820
3.640625
4
[]
no_license
package com.joke.algospot.quadtree; import java.util.Scanner; /** * https://algospot.com/judge/problem/read/QUADTREE */ public class QuadTree { private String tree; public QuadTree(String tree) { this.tree = tree; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int caseCount = scanner.nextInt(); String[] result = new String[caseCount]; for(int i = 0; i < caseCount; i++) { String tree = scanner.next(); result[i] = new QuadTree(tree).solve(); } for(int i = 0; i < caseCount; i++) { System.out.println(result[i]); } } private String solve() { return assemble(tree); } private String assemble(String tree) { if ("w".equals(tree) || "b".equals(tree)) { return tree; } String[] parts = getParts(tree); return new StringBuilder().append("x").append(assemble(parts[2])).append(assemble(parts[3])).append(assemble(parts[0])).append(assemble(parts[1])).toString(); } private String[] getParts(String tree) { String[] parts = new String[4]; int startPoint = 1; for(int part = 0; part < 4; part++) { int current = startPoint; int readCount = 1; StringBuilder builder = new StringBuilder(); while(readCount != 0 && startPoint < tree.length()) { char color = tree.charAt(current); if (color == 'x') { readCount += 4; } builder.append(color); readCount--; current++; } parts[part] = builder.toString(); startPoint = current; } return parts; } }
true
318f5c5650c2fb75b91f64e99396338b1eb36357
Java
tongchenghao/studyRepository
/Design-Patterns/tch-study-factory/src/net/tch/java/abstr/DefaultFactory.java
UTF-8
248
2.140625
2
[]
no_license
package abstr; import bean.Car; /** * @description: * @auth tongchenghao * @date 2019/12/26 */ public class DefaultFactory extends AbstractFactory{ @Override protected Car getCar() { return new BaoMaFacoty().getCar(); } }
true
6b572550c2d3551aa95835ac11d93f6e806d15b0
Java
betterphp/MineBans
/src/main/java/com/minebans/minebans/evidence/GriefEvidenceCollector.java
UTF-8
436
2.03125
2
[]
no_license
package com.minebans.minebans.evidence; import java.util.HashMap; import com.minebans.minebans.MineBans; public class GriefEvidenceCollector extends EvidenceCollector { private MineBans plugin; public GriefEvidenceCollector(MineBans plugin){ this.plugin = plugin; } @Override public HashMap<String, HashMap<Integer, Integer>> collect(String playerName){ return plugin.loggingPlugin.getBlockChanges(playerName); } }
true
ba5562d2383b7d459513af2b632c455576cb3085
Java
tutuchui/LeetCode
/src/Game2048.java
UTF-8
2,484
3.15625
3
[]
no_license
import java.util.Scanner; public class Game2048 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int operation = Integer.valueOf(scanner.nextLine()); int[][] matrix = new int[4][4]; for(int i = 0; i < 4; i++){ String tmp = scanner.nextLine(); matrix[i][0] = Integer.valueOf(tmp.split(" ")[0]); matrix[i][1] = Integer.valueOf(tmp.split(" ")[1]); matrix[i][2] = Integer.valueOf(tmp.split(" ")[2]); matrix[i][3] = Integer.valueOf(tmp.split(" ")[3]); } switch (operation){ case 1: for(int j = 0; j < 4;j++){ for(int i = 0; i < 3;i++){ if(matrix[i][j]!=0 && matrix[i][j] == matrix[i+1][j]){ matrix[i][j] = 2 * matrix[i][j]; matrix[i+1][j] = -1; } } for(int i = 0; i < 3;i++){ if(matrix[i][j] == -1){ matrix[i][j] = matrix[i+1][j]; matrix[i+1][j] = 0; } } for(int i = 0; i < 4;i++){ if(matrix[i][j] == -1){ matrix[i][j] = 0; } } } break; case 2: for(int j = 0; j < 4;j++){ for(int i = 3; i > 0;i--){ if(matrix[i][j]!=0 && matrix[i][j] == matrix[i-1][j]){ matrix[i][j] = 2 * matrix[i][j]; matrix[i-1][j] = -1; } } for(int i = 0; i < 3;i++){ if(matrix[i][j] == -1){ matrix[i][j] = matrix[i-1][j]; matrix[i-1][j] = 0; } } for(int i = 0; i < 4;i++){ if(matrix[i][j] == -1){ matrix[i][j] = 0; } } } break; } for(int i = 0; i < 4;i++) { for (int j = 0; j < 4; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
true
83ddedeba2e75058d141f3ff96820e73366a88bf
Java
JellySenpai/MediMind
/app/src/main/java/com/example/rayhardi/medimind/MediMindMessage.java
UTF-8
1,151
2.1875
2
[]
no_license
package com.example.rayhardi.medimind; import android.app.NotificationManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; /** * Created by rayhardi on 10/15/2017. */ public class MediMindMessage extends FirebaseMessagingService { private static final String TAG = "FCM Service"; @Override public void onMessageReceived (RemoteMessage remoteMessage) { String remoteMess = remoteMessage.getNotification().getBody(); Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMess); NotificationCompat.Builder builder; int notificationId = 7; builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.brain) .setContentTitle("Medication Reminder").setContentText(remoteMess); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build()); } }
true
aca505b8058fb43e087576875a6e33a3e17a81cd
Java
freemocker/Distributed-Systems
/后端/utils/src/main/java/icbc/utils/entity/NthpaBrpTableEntityPK.java
UTF-8
1,485
2.234375
2
[ "MIT" ]
permissive
package icbc.utils.entity; import javax.persistence.Column; import javax.persistence.Id; import java.io.Serializable; import java.util.Objects; public class NthpaBrpTableEntityPK implements Serializable { private long snId; private int zoneno; private int brno; private int mbrno; @Column(name = "sn_id") @Id public long getSnId() { return snId; } public void setSnId(long snId) { this.snId = snId; } @Column(name = "zoneno") @Id public int getZoneno() { return zoneno; } public void setZoneno(int zoneno) { this.zoneno = zoneno; } @Column(name = "brno") @Id public int getBrno() { return brno; } public void setBrno(int brno) { this.brno = brno; } @Column(name = "mbrno") @Id public int getMbrno() { return mbrno; } public void setMbrno(int mbrno) { this.mbrno = mbrno; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NthpaBrpTableEntityPK that = (NthpaBrpTableEntityPK) o; return snId == that.snId && Objects.equals(zoneno, that.zoneno) && Objects.equals(brno, that.brno) && Objects.equals(mbrno, that.mbrno); } @Override public int hashCode() { return Objects.hash(snId, zoneno, brno, mbrno); } }
true
a9e51859bc5591dc09f62fba06eb358b08afc6f1
Java
CS2103JAN2018-W14-B1/main
/src/test/java/seedu/address/testutil/modelstub/ModelStubThrowingDuplicateEventException.java
UTF-8
887
2.640625
3
[ "MIT" ]
permissive
package seedu.address.testutil.modelstub; import seedu.address.model.AddressBook; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.event.Appointment; import seedu.address.model.event.Task; import seedu.address.model.event.exceptions.DuplicateEventException; //@@author Sisyphus25 /** * A Model stub that always throw a DuplicateEventException when trying to add an appointment/task. */ public class ModelStubThrowingDuplicateEventException extends ModelStub { @Override public void addAppointment (Appointment appointment) throws DuplicateEventException { throw new DuplicateEventException(); } @Override public void addTask (Task task) throws DuplicateEventException { throw new DuplicateEventException(); } @Override public ReadOnlyAddressBook getAddressBook() { return new AddressBook(); } }
true
668e62764b24863454c97ebbb39dd8b24e12b8f7
Java
laci6599/LWI9Z1xmlGyak
/Beadandó/DOM program/src/hu/domparse/LWI9Z1/DOMReadLWI9Z1.java
UTF-8
8,280
2.875
3
[]
no_license
package hu.domparse.LWI9Z1; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.util.Scanner; public class DOMReadLWI9Z1 { public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException { try { File xmlFile = new File("src/hu/domparse/LWI9Z1/XMLlwi9z1.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = factory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); System.out.println("Nagy LászlĂł LWI9Z1 XML fĂ©lĂ©ves feladat"); Action(doc); }catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } } public static void Action(Document doc) throws TransformerException { System.out.println("\nOlvasni vagy modosĂ­tani szeretne?"); System.out.println("1 - olvasás"); System.out.println("2 - mĂłdosĂ­tás"); int action = ReadCategory(); switch (action) { case 1: Read(doc); break; case 2: Update(doc); break; default: Action(doc); break; } } //Kategória beolvasása public static int ReadCategory() { Scanner scan = new Scanner(System.in); System.out.print("\nAdja meg a sorszámot:"); int readCategory = scan.nextInt(); return readCategory; } //Módosítani kívánt adat sorszámának bekérése public static void Update(Document doc) throws TransformerException { System.out.println("\nXML MĂłdosĂ­tás\n"); System.out.println("KĂ©rem adja meg mit szeretne mĂłdosĂ­tani"); System.out.println("1 - szĂ­nház\n2 - igazgatĂł\n3 - elĹ‘adás\n4 - elĹ‘adĂł\n5 - jegy"); int category = 0; category = ReadCategory(); ShowElementUpdates(category, doc); } //Olvasni kívánt adatok sorszámának bekérése public static void Read(Document doc) { System.out.println("\nXML Olvasás\n"); System.out.println("KĂ©rem adja meg mit szeretne olvasni"); System.out.println("1 - szĂ­nház\n2 - igazgatĂł\n3 - elĹ‘adás\n4 - elĹ‘adĂł\n5 - jegy"); int category = 0; category = ReadCategory(); ShowCategoryElements(category, doc); } public static void ShowCategoryElements(int category, Document doc) { switch (category) { case 1: ReadTheatre(doc); break; case 2: ReadPrincipal(doc); break; case 3: ReadShow(doc); break; case 4: ReadActor(doc); break; case 5: ReadTicket(doc); break; default: int newCategory = ReadCategory(); ShowCategoryElements(newCategory, doc); break; } } public static void ShowElementUpdates(int category, Document doc) throws TransformerException { switch (category) { case 1: DOMModifyLWI9Z1.UpdateTheatre(doc); break; case 2: DOMModifyLWI9Z1.UpdatePrincipal(doc); break; case 3: DOMModifyLWI9Z1.UpdateShow(doc); break; case 4: DOMModifyLWI9Z1.UpdateActor(doc); break; case 5: DOMModifyLWI9Z1.UpdateTicket(doc); break; default: int newCategory = ReadCategory(); ShowElementUpdates(newCategory, doc); break; } } public static void ReadTheatre(Document doc) { NodeList nList = doc.getElementsByTagName("theatre"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nNode; String theatreid = element.getAttribute("id"); String principalid = element.getAttribute("principalid"); String showid = element.getAttribute("showid"); Node node1 = element.getElementsByTagName("name").item(0); String name = node1.getTextContent(); String zipcode = ""; String country = ""; String city = ""; for (int j = 0; j < nList.getLength(); j++) { Node nnode1 = element.getElementsByTagName("zipcode").item(0); Node cnode1 = null; country = cnode1.getTextContent(); Node nnode2 = element.getElementsByTagName("country").item(0); Node cnode2 = null; country = cnode2.getTextContent(); Node cnode3 = element.getElementsByTagName("city").item(0); city = cnode3.getTextContent(); } System.out.println("SzĂ­nház id:" + theatreid + "\tNev: " + name + "\tIrsz: " + zipcode + "\tOrszág: " + country + "\tVáros: " + city); } } } public static void ReadPrincipal(Document doc) { NodeList nList = doc.getElementsByTagName("principal"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nNode; String principalid = element.getAttribute("id"); Node node1 = element.getElementsByTagName("name").item(0); String name = node1.getTextContent(); System.out.println("IgazgatĂł id:" + principalid + "\tNev: " + name); } } } public static void ReadShow(Document doc) { NodeList nList = doc.getElementsByTagName("show"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); NodeList cList = nList.item(i).getChildNodes(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nNode; String showid = element.getAttribute("id"); Node node1 = element.getElementsByTagName("title").item(0); String title = node1.getTextContent(); Node node2 = element.getElementsByTagName("genre").item(0); String genre = node2.getTextContent(); Node node3 = element.getElementsByTagName("length").item(0); String length = node3.getTextContent(); Node node4 = element.getElementsByTagName("director").item(0); String director = node4.getTextContent(); System.out.println("ElĹ‘adás id:\t" + showid + "\tCĂ­m:\t" + title + "\tMűfaj:\t" + genre + "\tIdĹ‘tartam:\t" + length + "\tRendezĹ‘:\t" + director); } } } public static void ReadActor(Document doc) { NodeList nList = doc.getElementsByTagName("actor"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); NodeList cList = nList.item(i).getChildNodes(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nNode; String actorid = element.getAttribute("id"); Node node1 = element.getElementsByTagName("name").item(0); String name = node1.getTextContent(); Node node2 = element.getElementsByTagName("dramagroup").item(0); String dramagroup = node2.getTextContent(); String dateplace = ""; String datetime = ""; for (int j = 0; j < cList.getLength(); j++) { Node cnode1 = element.getElementsByTagName("dateplace").item(0); dateplace = cnode1.getTextContent(); Node cnode2 = element.getElementsByTagName("datetime").item(0); datetime = cnode2.getTextContent(); } System.out.println("ElĹ‘adĂł id:" + actorid + "\tNĂ©v: " + name + "\tTársulat: " + dramagroup + "\tSzĂĽletĂ©si hely: " + dateplace + "\tSzĂĽletĂ©si idĹ‘: " + datetime); } } } public static void ReadTicket(Document doc) { NodeList nList = doc.getElementsByTagName("ticket"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nNode; String ticketid = element.getAttribute("id"); Node node1 = element.getElementsByTagName("category").item(0); String category = node1.getTextContent(); Node node2 = element.getElementsByTagName("price").item(0); String price = node2.getTextContent(); System.out.println("Jegy id:" + ticketid + "\tKategĂłria: " + category + "\tĂ�r: " + price); } } } }
true
49b9a0b3280b0c873c0e23c2a2b8a0ce36297d66
Java
mukul2709/Smart-Attendence-App
/app/src/main/java/com/example/smartattendance/view_attendance.java
UTF-8
38,885
2.109375
2
[]
no_license
package com.example.smartattendance; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class view_attendance extends AppCompatActivity { private Spinner spinner1, spinner2,spinner3,spinner4; DatabaseReference ref; List<String> year; List<String> branch; List<String> class1; List<String> subject; ArrayAdapter<String> arrayAdapter1; ArrayAdapter<String> arrayAdapter2; ArrayAdapter<String> arrayAdapter3; ArrayAdapter<String> arrayAdapter4; String yearselected,branchselected,classselected,subjectselected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_attendance); spinner1 = findViewById(R.id.spinner1); spinner2 = findViewById(R.id.spinner2); spinner3 = findViewById(R.id.spinner3); spinner4 = findViewById(R.id.spinner4); year = new ArrayList<>(); arrayAdapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, year); arrayAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner1.setAdapter(arrayAdapter1); subject = new ArrayList<>(); arrayAdapter4 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, subject); arrayAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner4.setAdapter(arrayAdapter4); fetchyear(); branch=new ArrayList<>(); arrayAdapter2=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,branch); arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner2.setAdapter(arrayAdapter2); fetchbranch(); class1 = new ArrayList<>(); arrayAdapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, class1); arrayAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner3.setAdapter(arrayAdapter3); fetchclass(); } private void fetchbranch() { ref = FirebaseDatabase.getInstance().getReference().child("branch"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { branch.add(snapshot1.getValue().toString()); arrayAdapter2.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void fetchclass() { ref = FirebaseDatabase.getInstance().getReference().child("class"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { class1.add(snapshot1.getValue().toString()); arrayAdapter3.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { classselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void fetchyear() { ref = FirebaseDatabase.getInstance().getReference().child("year"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { year.add(snapshot1.getValue().toString()); arrayAdapter1.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(parent.getItemAtPosition(position).equals("Ist")){ yearselected= parent.getItemAtPosition(position).toString(); first(); } else if(parent.getItemAtPosition(position).equals("2nd")){ yearselected= (String) parent.getItemAtPosition(position); second(); } else if(parent.getItemAtPosition(position).equals("3rd")){ yearselected= (String) parent.getItemAtPosition(position); third(); } else if(parent.getItemAtPosition(position).equals("4th")){ yearselected= (String) parent.getItemAtPosition(position); fourth(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void first(){ spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(parent.getItemAtPosition(position).equals("Information Technology")){ branchselected=parent.getItemAtPosition(position).toString(); subject.clear(); ref = FirebaseDatabase.getInstance().getReference().child("IstIT"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Computer Science")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("IstCS"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Electrical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("IstEC"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Mechanical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("IstME"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Civil")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("IstCI"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void second(){ spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(parent.getItemAtPosition(position).equals("Information Technology")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("2ndIT"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Computer Science")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("2ndCS"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Electrical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("2ndEC"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Mechanical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("2ndME"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Civil")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("2ndCI"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void third(){ spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(parent.getItemAtPosition(position).equals("Information Technology")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("3rdIT"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Computer Science")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("3rdCS"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Electrical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("3rdEC"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Mechanical")){ subject.clear(); ref = FirebaseDatabase.getInstance().getReference().child("3rdME"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Civil")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("3rdCI"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void fourth(){ spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(parent.getItemAtPosition(position).equals("Information Technology")){ branchselected=parent.getItemAtPosition(position).toString(); subject.clear(); ref = FirebaseDatabase.getInstance().getReference().child("4thIT"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Computer Science")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("4thCS"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Electrical")){ subject.clear(); ref = FirebaseDatabase.getInstance().getReference().child("4thEC"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Mechanical")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("4thME"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else if(parent.getItemAtPosition(position).equals("Civil")){ subject.clear(); branchselected=parent.getItemAtPosition(position).toString(); ref = FirebaseDatabase.getInstance().getReference().child("4thCI"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { subject.add(snapshot1.getValue().toString()); arrayAdapter4.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void viewcard(View view) { spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { branchselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { subjectselected=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Intent intent = new Intent(this, view_card.class); intent.putExtra("year",yearselected); intent.putExtra("branch",branchselected); intent.putExtra("class",classselected); intent.putExtra("subject",subjectselected); startActivity(intent); } }
true
ff67f92a681a96eb28feac2bb91c5e2987970211
Java
NikosLv/Project-Logos
/src/main/java/com/logos/domain/EditRequest.java
UTF-8
959
2.234375
2
[]
no_license
package com.logos.domain; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter public class EditRequest { private int id; //@NotEmpty(message="Field email must be full") private String email; @NotEmpty(message="Field password must be full") private String password; @NotEmpty(message="Enter your first name") private String firstName; @NotEmpty(message="Enter your last name") private String lastName; @Min(value=18, message="May not be less than 18") @Max(value=70, message="Can not be greater than 70") private int age; @NotEmpty(message="Enter your city") private String city; @NotEmpty (message="Field phoneNumber can not be empty") private String phoneNumber; private String role; }
true
baee63ca65f8ad5390e5171f560de93cd1335664
Java
cckmit/erp-4
/Maven_Accounting_Libs/mavenAccCommonLibs/src/main/java/com/krawler/spring/accounting/handler/AccountingHandlerDAO.java
UTF-8
19,673
1.546875
2
[]
no_license
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.krawler.spring.accounting.handler; import com.krawler.common.admin.CustomerAddressDetails; import com.krawler.common.admin.NewProductBatch; import com.krawler.common.admin.VendorAddressDetails; import com.krawler.common.service.ServiceException; import com.krawler.hql.accounting.AccountingException; import com.krawler.inventory.model.store.Store; import com.krawler.spring.common.KwlReturnObject; import com.krawler.utils.json.base.JSONArray; import com.krawler.utils.json.base.JSONObject; import java.text.DateFormat; import java.util.*; import javax.script.ScriptException; import javax.servlet.http.HttpServletRequest; /** * * @author krawler */ public interface AccountingHandlerDAO { public KwlReturnObject getObject(String classpath, String id) throws ServiceException; public boolean checkForProductCategoryForProduct(JSONArray productDiscountMapList, int appliedUpon, String rule); public KwlReturnObject loadObject(String classpath, String id) throws ServiceException; public KwlReturnObject getInvoiceFromFirstDB(String [] subdomain,String dbName) throws ServiceException; public KwlReturnObject getVendorInvoiceFromFirstDB(String [] subdomain,String dbName) throws ServiceException; public KwlReturnObject getCustomerCreditNoteFromFirstDB(String [] subdomain,String dbName) throws ServiceException; public KwlReturnObject getCustomerDebitNoteFromFirstDB(String [] subdomain,String dbName) throws ServiceException; public KwlReturnObject getFieldParamsFromFirstDB(HashMap<String, Object> requestParams,String dbName); public KwlReturnObject getReceiptFromFirstDB(String [] subdomain,String dbName) throws ServiceException ; public KwlReturnObject getOpeningInvoiceFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getVendorOpeningInvoiceFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getCustomerOpeningCreditNoteFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getCustomerOpeningDebitNoteFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getOpeningReceiptFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getOpeningPaymentFromFirstDB(String[] subdomain,String dbName) throws ServiceException; public KwlReturnObject getPaymentFromFirstDB(String [] subdomain,String dbName) throws ServiceException; public String getCustomDataUsingColNumInv(HashMap<String, Object> requestParams) ; public String getCustomDataUsingColNumRec(HashMap<String, Object> requestParams) ; public String getCustomDataUsingColNumVal(String id); public String getCustomDataUsingColNum(HashMap<String, Object> requestParams,String dbName) ; public KwlReturnObject getObject(String classpath, Integer id) throws ServiceException; public KwlReturnObject saveOrUpdateObject(Object object) throws ServiceException; public void evictObj(Object currentSessionObject) ; //Synchronizes hibernate session with database, i.e. saves any unsaved objects/operations in database public void flushHibernateSession(); public Boolean checkSecurityGateFunctionalityisusedornot(String companyid) throws ServiceException; public Boolean checkIsVendorAsCustomer(String companyid,String customerId) throws ServiceException; public ArrayList getApprovalFlagForAmount(Double invoiceamount, String typeid, String fieldtype, String companyid) throws ServiceException; public ArrayList getApprovalFlagForProductsDiscount(Double discamount, String productid, String typeid, String fieldtype, String companyid, boolean approvalFlag, int approvallevel) throws ServiceException; public ArrayList getApprovalFlagForProducts(ArrayList productlist, String typeid, String fieldtype, String companyid) throws ServiceException; // public Object invokeMethod(String modulename, String method, Object[] params) throws ServiceException; public KwlReturnObject updateApprovalHistory(HashMap hm) throws ServiceException; public String getApprovalHistory(String billid, String companyid, DateFormat df,HashMap<String, Object> hm) throws ServiceException; public KwlReturnObject getApprovalHistoryForExport(String billid, String companyid) throws ServiceException; public KwlReturnObject getCustomizeReportViewMappingField(HashMap hashMap) throws ServiceException; public KwlReturnObject deleteCustomizeReportColumn(String id,String companyId, int reportId) throws ServiceException; /** * @param mailParameters (String Number, String fromName, String[] emails, String fromEmailId, String moduleName, String companyid, String PAGE_URL) */ public void sendApprovalEmails(Map<String, Object> mailParameters); public void sendApprovedEmails(Map<String, Object> mailParameters); public void sendReorderLevelEmails(String Sender,String[] emails,String moduleName, HashMap<String,String> data)throws ServiceException; public void sendTransactionEmails(String[] toEmailIds,String ccmailids,String subject,String htmlMsg,String plainMsg,String companyid) throws ServiceException ; public String getTabularFormatHTMLForNotificationMail(List<String> headerItemsList, List rowDetailMapList); public Boolean checkForMultiLevelApprovalRule(int level, String companyid, String amount, String userid, int moduleid) throws AccountingException, ServiceException, ScriptException; public Boolean checkForMultiLevelApprovalRules(HashMap<String, Object> requestParams) throws AccountingException, ServiceException, ScriptException; public String[] getApprovalUserList(HttpServletRequest request, String moduleName, int approvalLevel); public String[] getApprovalUserListJson(JSONObject jobj, String moduleName, int approvalLevel); public KwlReturnObject saveModuleTemplate(HashMap hm) throws ServiceException; public KwlReturnObject getModuleTemplates(HashMap hm); public void setDefaultModuleTemplates(HashMap hm) throws ServiceException; public KwlReturnObject getModuleTemplateForTemplatename(HashMap hm); public KwlReturnObject deleteModuleTemplates(String companyId, String templateId) throws ServiceException; public KwlReturnObject getDuedateCustomerInvoiceInfoList() throws ServiceException; public KwlReturnObject getDuedateVendorInvoiceList(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getDuedateVendorBillingInvoiceList(String companyId, String date) throws ServiceException; public KwlReturnObject getDuedateCustomerInvoiceList(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getSOdateSalesOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getSOdateBillingSalesOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getPOdatePurchaseOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getPOdateBillingPurchaseOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getDOdateDeliveryOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getProductExpdateDeliveryOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getProductExpdateGoodsReceiptOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getGRODateGoodsReceiptOrderList(String companyId, String date) throws ServiceException; public KwlReturnObject getSRDateSalesReturnList(String companyId, String date) throws ServiceException; public KwlReturnObject getPRDatePurchaseReturnList(String companyId, String date) throws ServiceException; public KwlReturnObject getCustomerCreationDateCustomerList(String companyId, String date) throws ServiceException; public KwlReturnObject getVendorCreationDateVendorList(String companyId, String date) throws ServiceException; public KwlReturnObject getInvoiceCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getVendorInvoiceCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getCustomerQuotationCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getVendorQuotationCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getSalesOrderDateCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getPurchaseOrderCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getDeliveryOrderCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getGoodsReceiptOrderCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getJournalEntryCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getSalesReturnCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getPurchaseReturnCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getCustomerCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getVendorCustomFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getCustomerInvoiceLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getVendorInvoiceLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getCustomerQuotationDetailsLineCustomDateFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getVendorQuotationDetailsLineCustomDateFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getSalesOrderDetailsLineCustomDateFields(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getPurchaseOrderDetailLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getDeliveryOrderDetailLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getGoodsReceiptOrderDetailLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getSalesReturnDetailLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getPurchaseReturnDetailLineCustomDateFieldMails(HashMap<String, Object> requestParams) throws ServiceException; public KwlReturnObject getDuedateCustomerBillingInvoiceList(String companyId, String date) throws ServiceException; public KwlReturnObject getCompanyList() throws ServiceException; public KwlReturnObject getCompanyList(int offset,int limit) throws ServiceException; public List getPOSCompanyList() throws ServiceException; public KwlReturnObject getFieldParamsForProject(String companyid, String projectid) throws ServiceException; public KwlReturnObject getFieldParamsForLinkProjectToInvoice(HashMap<String, Object> requestParams); public KwlReturnObject getReceiptDetails(String companyId,String receiptId) throws ServiceException ; public KwlReturnObject getFieldParamsForTask(String companyid) throws ServiceException; public KwlReturnObject getFieldComboDataForProject(String fieldId, String projectid) throws ServiceException; public KwlReturnObject getFieldComboDataForTask(String fieldId, String projectid, String taskid) throws ServiceException; public KwlReturnObject getNotifications(String companyId) throws ServiceException; public KwlReturnObject getDueJournalEntryList(String companyId, Long dbDuedate1, Long dbDuedate2, String columnname) throws ServiceException; public KwlReturnObject getDuedateCustomefield(String companyId) throws ServiceException; public KwlReturnObject getUserDetailObj(String[] userids) throws ServiceException; public KwlReturnObject saveAddressDetail(Map<String, Object> addressParams, String companyid) throws ServiceException; public KwlReturnObject saveVendorAddressesDetails(HashMap<String, Object> addressParams, String companyid) throws ServiceException; public KwlReturnObject deleteVendorAddressDetails(String vendorID, String companyid)throws ServiceException; public KwlReturnObject getVendorAddressDetails(HashMap<String, Object> requestParams)throws ServiceException; public KwlReturnObject saveCustomerAddressesDetails(HashMap<String, Object> addressesMap, String companyid) throws ServiceException; public KwlReturnObject deleteCustomerAddressDetails(String customerID, String companyid)throws ServiceException; public KwlReturnObject deleteCustomerAddressByID(String id, String companyid) throws ServiceException; public KwlReturnObject deleteVendorAddressByID(String id, String companyid) throws ServiceException; public KwlReturnObject getCustomerAddressDetails(HashMap<String, Object> requestParams)throws ServiceException; public KwlReturnObject getCustomerAddressDetailsMap(HashMap<String, Object> addrRequestParams) throws ServiceException; public void updateCustomerAddressDefaultValueToFalse(String customerid,boolean isBillingAddress)throws ServiceException; public void sendSaveTransactionEmails(String documentNumber, String moduleName, String[] tomailids, String userName, boolean isEditMail, String companyid)throws ServiceException; public void sendSaveTransactionEmails(String documentNumber, String moduleName, String[] tomailids,String ccmailids, String userName, boolean isEditMail, String companyid)throws ServiceException; public int getNature(String grpname, String companyid) throws ServiceException; public void updateAdvanceDetailAmountDueOnAmountReceived(String advancedetailid, double amountreceived) throws ServiceException; public List getPaymentAdvanceDetailsInRefundCase(String advancedetailid) throws ServiceException; public KwlReturnObject getProductExpiryList(String companyId) throws ServiceException; public List getDescriptionConfig(HashMap<String, Object> requestParams) throws ServiceException; public String getCustomerAddress(HashMap<String, Object> addrRequestParams); public String getVendorAddress(HashMap<String, Object> addrRequestParams); public VendorAddressDetails getVendorAddressObj(HashMap<String, Object> addrRequestParams); public String getVendorAddressForSenwanTec(HashMap<String, Object> addrRequestParams); public String getTotalVendorAddress(HashMap<String, Object> addrRequestParams); public CustomerAddressDetails getCustomerAddressobj(HashMap<String, Object> addrRequestParams); public String getCustomerAddressForSenwanTec(HashMap<String, Object> addrRequestParams); public String getTotalCustomerAddress(HashMap<String, Object> addrRequestParams); public KwlReturnObject getCompanyAddressDetails(HashMap<String, Object> requestParams)throws ServiceException; public KwlReturnObject getEmailTemplateTosendApprovalMail(String companyid, String fieldid, int moduleid)throws ServiceException; public void insertDocumentMailMapping(String documentid, int moduleid, String ruleid, String companyid) throws ServiceException; public int getDocumentMailCount(String documentid, String companyid, String ruleid) throws ServiceException; public KwlReturnObject getApprovalHistory(HashMap<String, Object> approvalHisMap) throws ServiceException; public KwlReturnObject getProductMasterFieldsToShowAtLineLevel(Map<String, Object> ProductFieldsRequestParams) throws ServiceException; public Boolean checkInventoryModuleFunctionalityIsUsedOrNot(String companyid) throws ServiceException; public Boolean checkSerialNoFunctionalityisusedornot(String companyid, String checkColumn) throws ServiceException; public KwlReturnObject getMasterItemByUserID(Map<String,Object> salesPersonParams) throws ServiceException; public Map<String, String> getMasterItemByCompanyID(Map<String,Object> requestParams) throws ServiceException; public KwlReturnObject getExciseTemplatesMap(HashMap hm); public KwlReturnObject getExciseDetails(String receiptId) throws ServiceException; public KwlReturnObject getSMTPAuthenticationDetails(HashMap<String, Object> requestParams)throws ServiceException; public KwlReturnObject getAdvancePayDetails(String paymentid)throws ServiceException; public KwlReturnObject getinvoiceDocuments(HashMap<String, Object> dataMap) throws ServiceException; public KwlReturnObject getAddressDetailsFromCompanyId(Map<String,Object> reqParams) throws ServiceException; public KwlReturnObject populateMasterInformation(Map<String, String> requestParams) throws ServiceException ; public KwlReturnObject getAccountidforDummyAccount(HashMap<String, Object> dataMap) throws ServiceException; public KwlReturnObject getEntityDetails(Map<String, Object> paramsMap) throws ServiceException; /** * Desc:This function is used to get NewProductBatch object from warehouse,location,row,rack,bin,batch name. * @param requestParams * @return : NewProductBatch Object * @throws ServiceException */ public NewProductBatch getERPProductBatch(Map<String, Object> requestParams) throws ServiceException; /** * Desc:This method is used to get warehouse from warehouse name. * @param requestParams * @return String * @throws ServiceException */ public String getStoreByTypes(Map<String, Object> requestParams) throws ServiceException; /** * Format double value to remove trailing zeros. * Example: 0.2500 -> 0.25, 1.0026500 -> 1.0265, 1.0 -> 1, 0.1260000 -> 0.126 * * @param double * @return String */ public String formatDouble(double d); public JSONObject getUserPermissionForFeature(HashMap<String, Object> params) throws ServiceException; }
true
d5a6e3624457a815be614e06689c60afda5b017a
Java
nishikun18/170174
/UserReg.java
UTF-8
783
2.8125
3
[]
no_license
import javax.swing.*; import java.awt.*; public class UserReg extends JFrame{ UserReg(String title){ setTitle(title); setSize(300,300); setLocation(500,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField fie=new JTextField(10); JPasswordField pas=new JPasswordField(10); JLabel lab=new JLabel("メールアドレス"); JLabel lab1=new JLabel("パスワード"); JPanel pan=new JPanel(); pan.setLayout(new GridLayout(2,2)); pan.add(lab,BorderLayout.CENTER); pan.add(fie,BorderLayout.CENTER); pan.add(lab1,BorderLayout.CENTER); pan.add(pas,BorderLayout.CENTER); Container c=getContentPane(); c.add(pan,BorderLayout.CENTER); } public static void main(String[] args){ UserReg usa=new UserReg("Hello"); usa.setVisible(true); } }
true
b4ce162f9f5b85716de869006daa0636e8f77acd
Java
coolzosel/coding_test_2020
/lecture/0523_online/chapter06/01_empty/factorial_dp.java
UTF-8
502
3.40625
3
[ "MIT" ]
permissive
import java.util.*; class Main { public static void main(String[] args) { System.out.println(fact(5)); System.out.println(factDP(5)); } // 재귀 호출의 경우 public static int fact(int n) { // 종료 조건 // 큰 문제를 작은 문제로 => 점화식 return 0; } // 동적계획법의 경우 public static int factDP(int n) { // 메모이제이션 해줄 자료 구조 // 큰 문제를 작은 문제로 => 점화식 return 0; } }
true
37f35aca94372c66ac18d083c45fc2f2e419d82a
Java
EloMeerkat/Fractal
/src/Complex.java
UTF-8
562
3.171875
3
[]
no_license
public class Complex implements Cloneable { private double re=0; private double im=0; public Complex() {} public Complex(double r, double i) { re=r; im=i; } public double sqrModulus() { return re*re+im*im; } public Complex sqr() { return new Complex(re*re-im*im, 2*re*im); } public Complex add(Complex z) { return new Complex(re+z.re, im+z.im); } public double getReal() { return re; } public double getImg() { return im; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
true
3e512a81bafcd43a955c99c3ad2941a7dc4f13e5
Java
LukeIsCodingNet/UsefulCommands
/src/net/lukeiscoding/spigot/usefulcommands/commands/CommandDestroyItems.java
UTF-8
1,369
2.765625
3
[]
no_license
package net.lukeiscoding.spigot.usefulcommands.commands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; public class CommandDestroyItems implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // cast the Player to the CommandSender Player p = (Player) sender; // create the inventory final Inventory inventory = Bukkit.createInventory(null, InventoryType.CHEST, ChatColor.AQUA + "Destroy Items"); // check if not the sender is a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "You need to be a player to use this command"); return true; } // check if the player has permission if (p.hasPermission("usefulcommands.destroyitems")) { // check for command if (cmd.getName().equalsIgnoreCase("destoryitems")) { // open the inventory p.openInventory(inventory); } } return false; } }
true
5554fcdeaeaad0370658dec817af4a6d7c90f45e
Java
90duc/HadoopIntellijPlugin2.6.0
/src/main/java/com/fangyuzhong/intelliJ/hadoop/core/table/IndexTableGutter.java
UTF-8
420
2.09375
2
[]
no_license
package com.fangyuzhong.intelliJ.hadoop.core.table; import javax.swing.*; /** * Created by fangyuzhong on 17-7-21. */ public class IndexTableGutter<T extends FileSystemTableWithGutter> extends FileSystemTableGutter<T> { public IndexTableGutter(T table) { super(table); } protected ListCellRenderer createCellRenderer() { return new IndexTableGutterCellRenderer(); } }
true
604e7e3abf9dfe873c8bf0e2f88f007826783a84
Java
future-architect/uroborosql
/src/test/java/jp/co/future/uroborosql/mapping/IdentityGeneratedKeysTest.java
UTF-8
84,942
1.9375
2
[ "MIT" ]
permissive
package jp.co.future.uroborosql.mapping; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.*; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import jp.co.future.uroborosql.SqlAgent; import jp.co.future.uroborosql.UroboroSQL; import jp.co.future.uroborosql.config.SqlConfig; import jp.co.future.uroborosql.enums.GenerationType; import jp.co.future.uroborosql.enums.InsertsType; import jp.co.future.uroborosql.exception.UroborosqlRuntimeException; import jp.co.future.uroborosql.filter.AuditLogSqlFilter; import jp.co.future.uroborosql.filter.SqlFilterManagerImpl; import jp.co.future.uroborosql.mapping.annotations.GeneratedValue; import jp.co.future.uroborosql.mapping.annotations.Id; import jp.co.future.uroborosql.mapping.annotations.Table; public class IdentityGeneratedKeysTest { private static SqlConfig config; @BeforeClass public static void setUpBeforeClass() throws Exception { String url = "jdbc:h2:mem:IdentityGeneratedKeysTest;DB_CLOSE_DELAY=-1"; String user = null; String password = null; try (Connection conn = DriverManager.getConnection(url, user, password)) { conn.setAutoCommit(false); // テーブル作成 try (Statement stmt = conn.createStatement()) { stmt.execute("drop table if exists test"); stmt.execute("drop sequence if exists test_id_seq"); stmt.execute("create sequence test_id_seq"); stmt.execute( "create table if not exists test( id bigint not null default nextval('test_id_seq'), name text, primary key(id))"); stmt.execute("drop table if exists test_ids cascade"); stmt.execute( "create table if not exists test_ids (id_str uuid not null default random_uuid(), id_uuid uuid not null default random_uuid(), id_int integer not null default 0 auto_increment, id_bigint bigint not null default 0 auto_increment, id_decimal decimal not null default 0 auto_increment)"); stmt.execute("drop table if exists test_auto cascade"); stmt.execute( "create table if not exists test_auto( id bigint auto_increment, name text, primary key(id))"); stmt.execute("drop table if exists test_multikey"); stmt.execute("drop sequence if exists test_multikey_id_seq"); stmt.execute("create sequence test_multikey_id_seq"); stmt.execute("drop sequence if exists test_multikey_id2_seq"); stmt.execute("create sequence test_multikey_id2_seq start with 100"); stmt.execute( "create table if not exists test_multikey( id bigint not null default nextval('test_multikey_id_seq'), id2 bigint not null default nextval('test_multikey_id2_seq'), name text, primary key(id, id2))"); } } config = UroboroSQL.builder(url, user, password) .setSqlFilterManager(new SqlFilterManagerImpl().addSqlFilter(new AuditLogSqlFilter())) .build(); } @Before public void setUpBefore() throws Exception { try (SqlAgent agent = config.agent()) { agent.updateWith("delete from test").count(); agent.updateWith("delete from test_multikey").count(); agent.commit(); } } @Test public void testInsert() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithId test1 = new TestEntityWithId("name1"); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestEntityWithId test2 = new TestEntityWithId("name2"); agent.insert(test2); assertThat(test2.getId(), is(++currVal)); TestEntityWithId test3 = new TestEntityWithId("name3"); agent.insert(test3); assertThat(test3.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testInsertWithNoId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); TestAutoEntityWithNoId test1 = new TestAutoEntityWithNoId("name1"); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestAutoEntityWithNoId test2 = new TestAutoEntityWithNoId("name2"); agent.insert(test2); assertThat(test2.getId(), is(++currVal)); TestAutoEntityWithNoId test3 = new TestAutoEntityWithNoId("name3"); agent.insert(test3); assertThat(test3.getId(), is(++currVal)); TestAutoEntityWithNoId data = agent.find(TestAutoEntityWithNoId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestAutoEntityWithNoId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestAutoEntityWithNoId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testInsertWithNoIdObj() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); long idVal = currVal + 100; TestAutoEntityWithNoIdObj test1 = new TestAutoEntityWithNoIdObj("name1"); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestAutoEntityWithNoIdObj test2 = new TestAutoEntityWithNoIdObj("name2"); test2.id = idVal; agent.insert(test2); assertThat(test2.getId(), is(idVal)); TestAutoEntityWithNoIdObj data = agent.find(TestAutoEntityWithNoIdObj.class, test1.getId()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestAutoEntityWithNoIdObj.class, test2.getId()).orElse(null); assertThat(data, is(test2)); }); } } @Test public void testInsertWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithId test1 = new TestEntityWithId("name1"); test1.setId(100); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); }); } } @Test public void testInsertWithObjectKeyValueNotSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestEntityWithIdObj data = agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null); assertThat(data, is(test1)); }); } } @Test public void testInsertWithObjectKeyValueSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long id = currVal + 100; TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); test1.setId(id); agent.insert(test1); assertThat(test1.getId(), is(id)); TestEntityWithIdObj data = agent.find(TestEntityWithIdObj.class, id).orElse(null); assertThat(data, is(test1)); }); } } @Test public void testInserts() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestEntityWithId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsNoId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); List<TestAutoEntityWithNoId> entities = new ArrayList<>(); TestAutoEntityWithNoId test1 = new TestAutoEntityWithNoId("name1"); entities.add(test1); TestAutoEntityWithNoId test2 = new TestAutoEntityWithNoId("name2"); entities.add(test2); TestAutoEntityWithNoId test3 = new TestAutoEntityWithNoId("name3"); entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestAutoEntityWithNoId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsNoIdObjNotSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); List<TestAutoEntityWithNoIdObj> entities = new ArrayList<>(); TestAutoEntityWithNoIdObj test1 = new TestAutoEntityWithNoIdObj("name1"); entities.add(test1); TestAutoEntityWithNoIdObj test2 = new TestAutoEntityWithNoIdObj("name2"); entities.add(test2); TestAutoEntityWithNoIdObj test3 = new TestAutoEntityWithNoIdObj("name3"); entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsNoIdObjSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by sequence_name") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); long idVal = currVal + 100; List<TestAutoEntityWithNoIdObj> entities = new ArrayList<>(); TestAutoEntityWithNoIdObj test1 = new TestAutoEntityWithNoIdObj("name1"); test1.id = idVal + 1; entities.add(test1); TestAutoEntityWithNoIdObj test2 = new TestAutoEntityWithNoIdObj("name2"); test2.id = idVal + 2; entities.add(test2); TestAutoEntityWithNoIdObj test3 = new TestAutoEntityWithNoIdObj("name3"); test3.id = idVal + 3; entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(idVal + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); test1.id = idVal++; entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); test2.id = idVal++; entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); test3.id = idVal++; entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestEntityWithId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsWithObjectKeyValueNotSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); List<TestEntityWithIdObj> entities = new ArrayList<>(); TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); entities.add(test1); TestEntityWithIdObj test2 = new TestEntityWithIdObj("name2"); entities.add(test2); TestEntityWithIdObj test3 = new TestEntityWithIdObj("name3"); entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsWithObjectKeyValueSetValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; List<TestEntityWithIdObj> entities = new ArrayList<>(); TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); test1.id = idVal; entities.add(test1); TestEntityWithIdObj test2 = new TestEntityWithIdObj("name2"); test2.id = idVal + 1; entities.add(test2); TestEntityWithIdObj test3 = new TestEntityWithIdObj("name3"); test3.id = idVal + 2; entities.add(test3); agent.inserts(entities.stream()); assertThat(test1.getId(), is(idVal)); assertThat(test2.getId(), is(idVal + 1)); assertThat(test3.getId(), is(idVal + 2)); assertThat(agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatch() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestEntityWithId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatchNoId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); List<TestAutoEntityWithNoId> entities = new ArrayList<>(); TestAutoEntityWithNoId test1 = new TestAutoEntityWithNoId("name1"); entities.add(test1); TestAutoEntityWithNoId test2 = new TestAutoEntityWithNoId("name2"); entities.add(test2); TestAutoEntityWithNoId test3 = new TestAutoEntityWithNoId("name3"); entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestAutoEntityWithNoId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatchNoIdNotSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by current_value desc") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); List<TestAutoEntityWithNoIdObj> entities = new ArrayList<>(); TestAutoEntityWithNoIdObj test1 = new TestAutoEntityWithNoIdObj("name1"); entities.add(test1); TestAutoEntityWithNoIdObj test2 = new TestAutoEntityWithNoIdObj("name2"); entities.add(test2); TestAutoEntityWithNoIdObj test3 = new TestAutoEntityWithNoIdObj("name3"); entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatchNoIdSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = agent.queryWith( "select sequence_schema, sequence_name, current_value, increment from information_schema.sequences order by sequence_name") .stream() .filter(map -> Objects.toString(map.get("SEQUENCE_NAME")).startsWith("SYSTEM_SEQUENCE")) .mapToLong(map -> (Long) map.get("CURRENT_VALUE")) .findFirst().getAsLong(); long idVal = currVal + 100; List<TestAutoEntityWithNoIdObj> entities = new ArrayList<>(); TestAutoEntityWithNoIdObj test1 = new TestAutoEntityWithNoIdObj("name1"); test1.id = idVal + 1; entities.add(test1); TestAutoEntityWithNoIdObj test2 = new TestAutoEntityWithNoIdObj("name2"); test2.id = idVal + 2; entities.add(test2); TestAutoEntityWithNoIdObj test3 = new TestAutoEntityWithNoIdObj("name3"); test3.id = idVal + 3; entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(idVal + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestAutoEntityWithNoIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatchWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); test1.id = idVal; entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); test2.id = idVal + 1; entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); test3.id = idVal + 2; entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(agent.find(TestEntityWithId.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithId.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithId.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsBatchWithObjectKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; List<TestEntityWithIdObj> entities = new ArrayList<>(); TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); test1.id = idVal; entities.add(test1); TestEntityWithIdObj test2 = new TestEntityWithIdObj("name2"); test2.id = idVal + 1; entities.add(test2); TestEntityWithIdObj test3 = new TestEntityWithIdObj("name3"); test3.id = idVal + 2; entities.add(test3); agent.inserts(entities.stream(), InsertsType.BATCH); assertThat(test1.getId(), is(idVal)); assertThat(test2.getId(), is(idVal + 1)); assertThat(test3.getId(), is(idVal + 2)); assertThat(agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null), is(test1)); assertThat(agent.find(TestEntityWithIdObj.class, test2.getId()).orElse(null), is(test2)); assertThat(agent.find(TestEntityWithIdObj.class, test3.getId()).orElse(null), is(test3)); }); } } @Test public void testInsertsAndReturn() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); entities.add(test3); List<TestEntityWithId> insertedEntities = agent.insertsAndReturn(entities.stream()) .collect(Collectors.toList()); assertThat(insertedEntities.get(0).getId(), is(++currVal)); assertThat(insertedEntities.get(1).getId(), is(++currVal)); assertThat(insertedEntities.get(2).getId(), is(++currVal)); assertThat(insertedEntities.get(0), is(test1)); assertThat(insertedEntities.get(1), is(test2)); assertThat(insertedEntities.get(2), is(test3)); }); } } @Test public void testInsertsAndReturnBatch() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); List<TestEntityWithId> entities = new ArrayList<>(); TestEntityWithId test1 = new TestEntityWithId("name1"); entities.add(test1); TestEntityWithId test2 = new TestEntityWithId("name2"); entities.add(test2); TestEntityWithId test3 = new TestEntityWithId("name3"); entities.add(test3); List<TestEntityWithId> insertedEntities = agent.insertsAndReturn(entities.stream(), InsertsType.BATCH) .collect(Collectors.toList()); assertThat(insertedEntities.get(0).getId(), is(++currVal)); assertThat(insertedEntities.get(1).getId(), is(++currVal)); assertThat(insertedEntities.get(2).getId(), is(++currVal)); assertThat(insertedEntities.get(0), is(test1)); assertThat(insertedEntities.get(1), is(test2)); assertThat(insertedEntities.get(2), is(test3)); }); } } @Test public void testInsertAndUpdate() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithId test1 = new TestEntityWithId("name1"); agent.insert(test1); assertThat(test1.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data.getName(), is("name1")); test1.setName("rename1"); agent.update(test1); data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data.getName(), is("rename1")); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testEntityNotGeneratedValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestEntityWithIdError test1 = new TestEntityWithIdError("name1"); agent.insert(test1); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testEntityInvalidTypeGeneratedValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestEntityWithIdError2 test1 = new TestEntityWithIdError2("name1"); agent.insert(test1); }); } } @Test public void testInsertMultiKey() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); agent.insert(test1); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); agent.insert(test2); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); agent.insert(test3); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testInsertMultiKeyWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); // 複数のIDすべてに値を設定した場合 TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); test1.id = idCurrVal + 10; test1.id2 = id2CurrVal + 10; agent.insert(test1); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); // 複数のIDの片方に値を設定した場合 TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); test2.id = idCurrVal + 10; agent.insert(test2); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); test3.id2 = id2CurrVal + 10; agent.insert(test3); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testInsertIdType() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIds test1 = new TestIds(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdUuid(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIds test2 = new TestIds(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdUuid(), not(test1.getIdUuid())); assertThat(test2.getIdInt(), is(test1.getIdInt() + 1)); assertThat(test2.getIdBigint(), is(test1.getIdBigint() + 1)); assertThat(test2.getIdDecimal(), is(test1.getIdDecimal().add(BigDecimal.ONE))); }); } } @Test public void testInsertIdTypeStr() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsStr test1 = new TestIdsStr(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIdsStr test2 = new TestIdsStr(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdInt(), is(String.valueOf(Integer.valueOf(test1.getIdInt()) + 1))); assertThat(test2.getIdBigint(), is(String.valueOf(Integer.valueOf(test1.getIdBigint()) + 1))); assertThat(test2.getIdDecimal(), is(String.valueOf(Integer.valueOf(test1.getIdDecimal()) + 1))); }); } } @Test public void testInsertIdTypeInteger() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsInteger test1 = new TestIdsInteger(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIdsInteger test2 = new TestIdsInteger(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdInt(), is(test1.getIdInt() + 1)); assertThat(test2.getIdBigint(), is(test1.getIdBigint() + 1)); assertThat(test2.getIdDecimal(), is(test1.getIdDecimal() + 1)); }); } } @Test public void testInsertIdTypeLong() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsLong test1 = new TestIdsLong(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIdsLong test2 = new TestIdsLong(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdInt(), is(test1.getIdInt() + 1)); assertThat(test2.getIdBigint(), is(test1.getIdBigint() + 1)); assertThat(test2.getIdDecimal(), is(test1.getIdDecimal() + 1)); }); } } @Test public void testInsertIdTypeBigInteger() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsBigInteger test1 = new TestIdsBigInteger(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIdsBigInteger test2 = new TestIdsBigInteger(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdInt(), is(test1.getIdInt().add(BigInteger.ONE))); assertThat(test2.getIdBigint(), is(test1.getIdBigint().add(BigInteger.ONE))); assertThat(test2.getIdDecimal(), is(test1.getIdDecimal().add(BigInteger.ONE))); }); } } @Test public void testInsertIdTypeBigDecimal() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsBigDecimal test1 = new TestIdsBigDecimal(); agent.insert(test1); assertThat(test1.getIdStr(), not(nullValue())); assertThat(test1.getIdInt(), not(nullValue())); assertThat(test1.getIdBigint(), not(nullValue())); assertThat(test1.getIdDecimal(), not(nullValue())); TestIdsBigDecimal test2 = new TestIdsBigDecimal(); agent.insert(test2); assertThat(test2.getIdStr(), not(test1.getIdStr())); assertThat(test2.getIdInt(), is(test1.getIdInt().add(BigDecimal.ONE))); assertThat(test2.getIdBigint(), is(test1.getIdBigint().add(BigDecimal.ONE))); assertThat(test2.getIdDecimal(), is(test1.getIdDecimal().add(BigDecimal.ONE))); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testInsertIdTypeErrInteger() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsErrInteger test1 = new TestIdsErrInteger(); agent.insert(test1); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testInsertIdTypeErrBigint() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsErrBigint test1 = new TestIdsErrBigint(); agent.insert(test1); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testInsertIdTypeErrBigInteger() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsErrBigInteger test1 = new TestIdsErrBigInteger(); agent.insert(test1); }); } } @Test(expected = UroborosqlRuntimeException.class) public void testInsertIdTypeErrBigDecimal() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { TestIdsErrBigDecimal test1 = new TestIdsErrBigDecimal(); agent.insert(test1); }); } } @Test public void testInsertMultiKeyWithObjectKeyValueNotSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); agent.insert(test1); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); agent.insert(test2); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); agent.insert(test3); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testInsertMultiKeyWithObjectKeyValueSetId() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long idVal = idCurrVal + 100; long id2Val = id2CurrVal + 100; // 複数のIDすべてに値を設定した場合 TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); test1.id = idVal; test1.id2 = id2Val; agent.insert(test1); assertThat(test1.getId(), is(idVal)); assertThat(test1.getId2(), is(id2Val)); // 複数のIDの片方に値を設定した場合 TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); test2.id = ++idVal; agent.insert(test2); assertThat(test2.getId(), is(idVal)); assertThat(test2.getId2(), is(++id2CurrVal)); TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); test3.id2 = ++id2Val; agent.insert(test3); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(id2Val)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); }); } } @Test public void testBulkInsert() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithId test1 = new TestEntityWithId("name1"); TestEntityWithId test2 = new TestEntityWithId("name2"); TestEntityWithId test3 = new TestEntityWithId("name3"); TestEntityWithId test4 = new TestEntityWithId("name4"); int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(test4.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithId.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInsertWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; TestEntityWithId test1 = new TestEntityWithId("name1"); test1.id = idVal + 1; TestEntityWithId test2 = new TestEntityWithId("name2"); test2.id = idVal + 2; TestEntityWithId test3 = new TestEntityWithId("name3"); test3.id = idVal + 3; TestEntityWithId test4 = new TestEntityWithId("name4"); test4.id = idVal + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(test4.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithId.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInsertWithObjectKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); test1.id = idVal + 1; TestEntityWithIdObj test2 = new TestEntityWithIdObj("name2"); test2.id = idVal + 2; TestEntityWithIdObj test3 = new TestEntityWithIdObj("name3"); test3.id = idVal + 3; TestEntityWithIdObj test4 = new TestEntityWithIdObj("name4"); test4.id = idVal + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(idVal + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(test4.getId(), is(idVal + 4)); TestEntityWithIdObj data = agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithIdObj.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithIdObj.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithIdObj.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInserMultikey() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); TestEntityWithMultiId test4 = new TestEntityWithMultiId("name4"); int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiId.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInserMultikeyWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long idVal = idCurrVal + 100; long id2Val = id2CurrVal + 100; TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); test1.id = idVal + 1; test1.id2 = id2Val + 1; TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); test1.id = idVal + 2; test1.id2 = id2Val + 2; TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); test1.id = idVal + 3; test1.id2 = id2Val + 3; TestEntityWithMultiId test4 = new TestEntityWithMultiId("name4"); test1.id = idVal + 4; test1.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiId.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInserMultikeyWithObjectKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long idVal = idCurrVal + 100; long id2Val = id2CurrVal + 100; TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); test1.id = idVal + 1; test1.id2 = id2Val + 1; TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); test2.id = idVal + 2; test2.id2 = id2Val + 2; TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); test3.id = idVal + 3; test3.id2 = id2Val + 3; TestEntityWithMultiIdObj test4 = new TestEntityWithMultiIdObj("name4"); test4.id = idVal + 4; test4.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(idVal + 1)); assertThat(test1.getId2(), is(id2Val + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test2.getId2(), is(id2Val + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(test3.getId2(), is(id2Val + 3)); assertThat(test4.getId(), is(idVal + 4)); assertThat(test4.getId2(), is(id2Val + 4)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiIdObj.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBulkInserMultikeyWithObjectKeyValue2() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long id2Val = id2CurrVal + 100; TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); test1.id2 = id2Val + 1; TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); test2.id2 = id2Val + 2; TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); test3.id2 = id2Val + 3; TestEntityWithMultiIdObj test4 = new TestEntityWithMultiIdObj("name4"); test4.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BULK); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(id2Val + 1)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(id2Val + 2)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(id2Val + 3)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(id2Val + 4)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiIdObj.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsert() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); TestEntityWithId test1 = new TestEntityWithId("name1"); TestEntityWithId test2 = new TestEntityWithId("name2"); TestEntityWithId test3 = new TestEntityWithId("name3"); TestEntityWithId test4 = new TestEntityWithId("name4"); int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(test4.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithId.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; TestEntityWithId test1 = new TestEntityWithId("name1"); test1.id = idVal + 1; TestEntityWithId test2 = new TestEntityWithId("name2"); test2.id = idVal + 2; TestEntityWithId test3 = new TestEntityWithId("name3"); test3.id = idVal + 3; TestEntityWithId test4 = new TestEntityWithId("name4"); test4.id = idVal + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(++currVal)); assertThat(test2.getId(), is(++currVal)); assertThat(test3.getId(), is(++currVal)); assertThat(test4.getId(), is(++currVal)); TestEntityWithId data = agent.find(TestEntityWithId.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithId.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithId.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithId.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertWithObjectKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long currVal = (Long) agent.queryWith("select currval('test_id_seq') as id").findFirst().get() .get("ID"); long idVal = currVal + 100; TestEntityWithIdObj test1 = new TestEntityWithIdObj("name1"); test1.id = idVal + 1; TestEntityWithIdObj test2 = new TestEntityWithIdObj("name2"); test2.id = idVal + 2; TestEntityWithIdObj test3 = new TestEntityWithIdObj("name3"); test3.id = idVal + 3; TestEntityWithIdObj test4 = new TestEntityWithIdObj("name4"); test4.id = idVal + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(idVal + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(test4.getId(), is(idVal + 4)); TestEntityWithIdObj data = agent.find(TestEntityWithIdObj.class, test1.getId()).orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithIdObj.class, test2.getId()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithIdObj.class, test3.getId()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithIdObj.class, test4.getId()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertMultikey() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); TestEntityWithMultiId test4 = new TestEntityWithMultiId("name4"); int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiId.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertMultikeyWithPrimitiveKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long idVal = idCurrVal + 100; long id2Val = id2CurrVal + 100; TestEntityWithMultiId test1 = new TestEntityWithMultiId("name1"); test1.id = idVal + 1; test1.id2 = id2Val + 1; TestEntityWithMultiId test2 = new TestEntityWithMultiId("name2"); test2.id = idVal + 2; test2.id2 = id2Val + 2; TestEntityWithMultiId test3 = new TestEntityWithMultiId("name3"); test3.id = idVal + 3; test3.id2 = id2Val + 3; TestEntityWithMultiId test4 = new TestEntityWithMultiId("name4"); test4.id = idVal + 4; test4.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(++id2CurrVal)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(++id2CurrVal)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(++id2CurrVal)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(++id2CurrVal)); TestEntityWithMultiId data = agent.find(TestEntityWithMultiId.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiId.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiId.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiId.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertMultikeyWithObjectKeyValue() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long idVal = idCurrVal + 100; long id2Val = id2CurrVal + 100; TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); test1.id = idVal + 1; test1.id2 = id2Val + 1; TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); test2.id = idVal + 2; test2.id2 = id2Val + 2; TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); test3.id = idVal + 3; test3.id2 = id2Val + 3; TestEntityWithMultiIdObj test4 = new TestEntityWithMultiIdObj("name4"); test4.id = idVal + 4; test4.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(idVal + 1)); assertThat(test1.getId2(), is(id2Val + 1)); assertThat(test2.getId(), is(idVal + 2)); assertThat(test2.getId2(), is(id2Val + 2)); assertThat(test3.getId(), is(idVal + 3)); assertThat(test3.getId2(), is(id2Val + 3)); assertThat(test4.getId(), is(idVal + 4)); assertThat(test4.getId2(), is(id2Val + 4)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiIdObj.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Test public void testBatchInsertMultikeyWithObjectKeyValue2() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { long idCurrVal = (Long) agent.queryWith("select currval('test_multikey_id_seq') as id").findFirst() .get().get("ID"); long id2CurrVal = (Long) agent.queryWith("select currval('test_multikey_id2_seq') as id").findFirst() .get().get("ID"); long id2Val = id2CurrVal + 100; TestEntityWithMultiIdObj test1 = new TestEntityWithMultiIdObj("name1"); test1.id2 = id2Val + 1; TestEntityWithMultiIdObj test2 = new TestEntityWithMultiIdObj("name2"); test2.id2 = id2Val + 2; TestEntityWithMultiIdObj test3 = new TestEntityWithMultiIdObj("name3"); test3.id2 = id2Val + 3; TestEntityWithMultiIdObj test4 = new TestEntityWithMultiIdObj("name4"); test4.id2 = id2Val + 4; int count = agent.inserts(Stream.of(test1, test2, test3, test4), (ctx, idx, entity) -> idx == 2, InsertsType.BATCH); assertThat(count, is(4)); assertThat(test1.getId(), is(++idCurrVal)); assertThat(test1.getId2(), is(id2Val + 1)); assertThat(test2.getId(), is(++idCurrVal)); assertThat(test2.getId2(), is(id2Val + 2)); assertThat(test3.getId(), is(++idCurrVal)); assertThat(test3.getId2(), is(id2Val + 3)); assertThat(test4.getId(), is(++idCurrVal)); assertThat(test4.getId2(), is(id2Val + 4)); TestEntityWithMultiIdObj data = agent .find(TestEntityWithMultiIdObj.class, test1.getId(), test1.getId2()) .orElse(null); assertThat(data, is(test1)); data = agent.find(TestEntityWithMultiIdObj.class, test2.getId(), test2.getId2()).orElse(null); assertThat(data, is(test2)); data = agent.find(TestEntityWithMultiIdObj.class, test3.getId(), test3.getId2()).orElse(null); assertThat(data, is(test3)); data = agent.find(TestEntityWithMultiIdObj.class, test4.getId(), test4.getId2()).orElse(null); assertThat(data, is(test4)); }); } } @Table(name = "TEST") public static class TestEntityWithId { @Id @GeneratedValue private long id; private String name; public TestEntityWithId() { } public TestEntityWithId(final String name) { this.name = name; } public long getId() { return this.id; } public String getName() { return this.name; } public void setId(final long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestEntityWithId other = (TestEntityWithId) obj; if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestEntityWithId [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST_AUTO") public static class TestAutoEntityWithNoId { private long id; private String name; public TestAutoEntityWithNoId() { } public TestAutoEntityWithNoId(final String name) { this.name = name; } public long getId() { return this.id; } public String getName() { return this.name; } public void setId(final long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestAutoEntityWithNoId other = (TestAutoEntityWithNoId) obj; if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestAutoEntityWithNoId [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST_AUTO") public static class TestAutoEntityWithNoIdObj { private Long id; private String name; public TestAutoEntityWithNoIdObj() { } public TestAutoEntityWithNoIdObj(final String name) { this.name = name; } public Long getId() { return this.id; } public String getName() { return this.name; } public void setId(final Long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestAutoEntityWithNoIdObj other = (TestAutoEntityWithNoIdObj) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestAutoEntityWithNoIdObj [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST") public static class TestEntityWithIdObj { @Id @GeneratedValue private Long id; private String name; public TestEntityWithIdObj() { } public TestEntityWithIdObj(final String name) { this.name = name; } public Long getId() { return this.id; } public String getName() { return this.name; } public void setId(final Long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestEntityWithIdObj other = (TestEntityWithIdObj) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestEntityWithIdObj [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST") public static class TestEntityWithIdError { @Id private long id; private String name; public TestEntityWithIdError() { } public TestEntityWithIdError(final String name) { this.name = name; } public long getId() { return this.id; } public String getName() { return this.name; } public void setId(final long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestEntityWithIdError other = (TestEntityWithIdError) obj; if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestEntityWithIdError [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST") public static class TestEntityWithIdError2 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Clob id; private String name; public TestEntityWithIdError2() { } public TestEntityWithIdError2(final String name) { this.name = name; } public Clob getId() { return this.id; } public String getName() { return this.name; } public void setId(final Clob id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public String toString() { return "TestEntityWithIdError2 [id=" + id + ", name=" + name + "]"; } } @Table(name = "TEST_MULTIKEY") public static class TestEntityWithMultiId { @Id @GeneratedValue private long id; @Id @GeneratedValue private long id2; private String name; public TestEntityWithMultiId() { } public TestEntityWithMultiId(final String name) { this.name = name; } public long getId() { return id; } public long getId2() { return id2; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (int) (id2 ^ id2 >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestEntityWithMultiId other = (TestEntityWithMultiId) obj; if (id != other.id) { return false; } if (id2 != other.id2) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestEntityWithMultiId [id=" + id + ", id2=" + id2 + ", name=" + name + "]"; } } @Table(name = "TEST_MULTIKEY") public static class TestEntityWithMultiIdObj { @Id @GeneratedValue private Long id; @Id @GeneratedValue private Long id2; private String name; public TestEntityWithMultiIdObj() { } public TestEntityWithMultiIdObj(final String name) { this.name = name; } public long getId() { return id; } public long getId2() { return id2; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (id2 == null ? 0 : id2.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestEntityWithMultiIdObj other = (TestEntityWithMultiIdObj) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (id2 == null) { if (other.id2 != null) { return false; } } else if (!id2.equals(other.id2)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "TestEntityWithMultiIdObj [id=" + id + ", id2=" + id2 + ", name=" + name + "]"; } } @Table(name = "TEST_IDS") public static class TestIds { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private Long idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public Long getIdBigint() { return idBigint; } public void setIdBigint(final Long idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsStr { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private String idInt; @Id @GeneratedValue private String idBigint; @Id @GeneratedValue private String idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public String getIdInt() { return idInt; } public void setIdInt(final String idInt) { this.idInt = idInt; } public String getIdBigint() { return idBigint; } public void setIdBigint(final String idBigint) { this.idBigint = idBigint; } public String getIdDecimal() { return idDecimal; } public void setIdDecimal(final String idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsInteger { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private int idBigint; @Id @GeneratedValue private Integer idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public int getIdBigint() { return idBigint; } public void setIdBigint(final int idBigint) { this.idBigint = idBigint; } public Integer getIdDecimal() { return idDecimal; } public void setIdDecimal(final Integer idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsLong { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Long idInt; @Id @GeneratedValue private long idBigint; @Id @GeneratedValue private Long idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public Long getIdInt() { return idInt; } public void setIdInt(final Long idInt) { this.idInt = idInt; } public long getIdBigint() { return idBigint; } public void setIdBigint(final long idBigint) { this.idBigint = idBigint; } public Long getIdDecimal() { return idDecimal; } public void setIdDecimal(final Long idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsBigInteger { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private BigInteger idInt; @Id @GeneratedValue private BigInteger idBigint; @Id @GeneratedValue private BigInteger idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public BigInteger getIdInt() { return idInt; } public void setIdInt(final BigInteger idInt) { this.idInt = idInt; } public BigInteger getIdBigint() { return idBigint; } public void setIdBigint(final BigInteger idBigint) { this.idBigint = idBigint; } public BigInteger getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigInteger idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsBigDecimal { @Id @GeneratedValue private String idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private BigDecimal idInt; @Id @GeneratedValue private BigDecimal idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public String getIdStr() { return idStr; } public void setIdStr(final String idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public BigDecimal getIdInt() { return idInt; } public void setIdInt(final BigDecimal idInt) { this.idInt = idInt; } public BigDecimal getIdBigint() { return idBigint; } public void setIdBigint(final BigDecimal idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsErrInteger { @Id @GeneratedValue private Integer idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private Long idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public Integer getIdStr() { return idStr; } public void setIdStr(final Integer idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public Long getIdBigint() { return idBigint; } public void setIdBigint(final Long idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsErrBigint { @Id @GeneratedValue private Long idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private Long idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public Long getIdStr() { return idStr; } public void setIdStr(final Long idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public Long getIdBigint() { return idBigint; } public void setIdBigint(final Long idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsErrBigInteger { @Id @GeneratedValue private BigInteger idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private Long idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public BigInteger getIdStr() { return idStr; } public void setIdStr(final BigInteger idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public Long getIdBigint() { return idBigint; } public void setIdBigint(final Long idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } @Table(name = "TEST_IDS") public static class TestIdsErrBigDecimal { @Id @GeneratedValue private BigDecimal idStr; @Id @GeneratedValue private UUID idUuid; @Id @GeneratedValue private Integer idInt; @Id @GeneratedValue private Long idBigint; @Id @GeneratedValue private BigDecimal idDecimal; public BigDecimal getIdStr() { return idStr; } public void setIdStr(final BigDecimal idStr) { this.idStr = idStr; } public UUID getIdUuid() { return idUuid; } public void setIdUuid(final UUID idUuid) { this.idUuid = idUuid; } public Integer getIdInt() { return idInt; } public void setIdInt(final Integer idInt) { this.idInt = idInt; } public Long getIdBigint() { return idBigint; } public void setIdBigint(final Long idBigint) { this.idBigint = idBigint; } public BigDecimal getIdDecimal() { return idDecimal; } public void setIdDecimal(final BigDecimal idDecimal) { this.idDecimal = idDecimal; } } }
true
6dc00d5dea030fb118ae1bd6b512f3ce54d51b64
Java
Jeolpe/Programacion
/Ejercicios del libro Tema 8/Ejercicios 54/Ejercicio56.java
UTF-8
2,891
3.328125
3
[]
no_license
/* * @utor Jesús María Olalla Pérez * 1º DAW Programación */ import Arreglos.arrays; import java.util.Scanner; public class Ejercicio56 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Escribe el número de filas: "); int filas = sc.nextInt(); System.out.print("Escribe el número de columnas: "); int columnas = sc.nextInt(); System.out.print("Escribe el número minimo de la Matriz: "); int minimo = sc.nextInt(); System.out.print("Escribe el número Máximo de la Matriz: "); int Maximo = sc.nextInt(); int[][] a = generarMatriz(filas, columnas, minimo, Maximo); System.out.println("La Matriz original es: "); mostrarMatriz(a); System.out.println(); int[] b = corteza(a); System.out.println("La corteza de la Matriz es: "); arrays.mostrarArray(b); } public static int[][] generarMatriz(int filas, int columnas, int minimo, int Maximo) { int[][] Matriz = new int[filas][columnas]; if (minimo > Maximo) { int aux = Maximo; Maximo = minimo; minimo = aux; } for (int i = 0; i < Matriz.length; i++) { for (int j = 0; j < Matriz[0].length; j++) { Matriz[i][j] = (int) (Math.random() * (Maximo - minimo + 1)) + 1; } System.out.println(); } return Matriz; } public static void mostrarMatriz(int[][] x) { for (int i = 0; i < x.length; i++) { for (int j = 0; j < x[0].length; j++) { System.out.printf("%5d", x[i][j]); } System.out.println(); } } public static int[] corteza(int[][] x) { int[] arr = new int[(x.length * 2) + ((x[0].length * 2) - 4)]; int[] aux = new int[x[0].length]; int[] aux2 = new int[x.length - 2]; int contCorteza = 0; int countAux = 0; int countAux2 = 0; for (int i = 0; i < x.length; i++) { for (int j = 0; j < x[0].length; j++) { if (i == 0) { arr[contCorteza++] = x[0][j]; } if ((i > 0 && i < x.length - 1) && (j == x[0].length - 1)) { arr[contCorteza++] = x[i][x[0].length - 1]; } if (i == x.length - 1) { aux[countAux++] = x[x.length - 1][j]; } if ((i > 0 && i < x.length - 1) && (j == 0)) { aux2[countAux2++] = x[i][0]; } } } for (int i = x[0].length - 1; i >= 0; i--) { arr[contCorteza++] = aux[i]; } for (int i = x.length - 3; i >= 0; i--) { arr[contCorteza++] = aux2[i]; } return arr; } }
true
5f22565cdb83a47ee5e4461c241b2ddc11995e41
Java
zyLear/BlokusOnline-web-server
/blokus-server/blokus-websocket-server/src/main/java/com/zylear/blokus/wsserver/bean/transfer/base/TransferBean.java
UTF-8
987
2.125
2
[]
no_license
package com.zylear.blokus.wsserver.bean.transfer.base; import io.netty.channel.Channel; /** * Created by xiezongyu on 2018/7/10. */ public class TransferBean { public TransferBean() { } public TransferBean(Channel channel, MessageBean messageBean) { this.channel = channel; this.messageBean = messageBean; } private Channel channel; private MessageBean messageBean; public MessageBean getMessageBean() { return messageBean; } public void setMessageBean(MessageBean messageBean) { this.messageBean = messageBean; } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } @Override public String toString() { return "TransferBean{" + "channel=" + channel + // ", handle=" + handle + ", messageBean=" + messageBean + '}'; } }
true
93d384627ade0edbafdb63786cb107588d4e7055
Java
kelemen/netbeans-gradle-project
/buildSrc/src/main/groovy/org/netbeans/gradle/build/PropertyUtils.java
UTF-8
1,084
2.46875
2
[]
no_license
package org.netbeans.gradle.build; import java.util.Locale; import org.gradle.api.Project; public final class PropertyUtils { public static String getStringProperty(Project project, String name, String defaultValue) { if (!project.hasProperty(name)) { return defaultValue; } Object propertyValue = project.property(name); String result = propertyValue != null ? propertyValue.toString() : null; return result != null ? result.trim() : defaultValue; } public static boolean getBoolProperty(Project project, String name, boolean defaultValue) { String strValue = getStringProperty(project, name, null); if (strValue == null) { return defaultValue; } String normValue = strValue.toLowerCase(Locale.ROOT).trim(); if ("true".equals(normValue)) { return true; } if ("false".equals(normValue)) { return false; } return defaultValue; } private PropertyUtils() { throw new AssertionError(); } }
true
2389a5aa2c1b6f4fb038d40ad5581eb18444da8a
Java
andrewflik/ProjectEuler
/src/euler005.java
UTF-8
852
3.15625
3
[]
no_license
/* Author - Devesh Problem - Euler 005 Time Complexity - O(nlogn) */ import java.util.Scanner; public class euler005 { static long ar[] = new long[41]; static void solve(){ for(int i=1; i<=40; i++) ar[i] = i; for(int i=3; i<=40; i++){ ar[i] = lcm(ar[i-1], ar[i]); System.out.print(ar[i] + " "); } } static long lcm(long a, long b){ return (a*b)/gcd(a, b); } static long gcd(long a, long b){ if(a == 0) return b; return gcd(b%a, a); } public static void main(String[] args) { solve(); Scanner inp = new Scanner(System.in); int t; t = inp.nextInt(); while(t-- > 0){ int n; n = inp.nextInt(); System.out.println(ar[n]); } } }
true
acd6232f82cb4d58dc8393b0301d251b6ef0d531
Java
sydneyyyyy/StoryPitch2
/src/main/java/com/porter/services/EditorServicesImpl.java
UTF-8
1,011
2.359375
2
[]
no_license
package com.porter.services; import java.util.List; import com.porter.daos.EditorDAO; import com.porter.daos.EditorDAOImpl; import com.porter.models.Editor; public class EditorServicesImpl implements EditorServices { private EditorDAO edao = new EditorDAOImpl(); @Override public Editor createEditor() { Editor newEditor = new Editor(); return edao.createEditor(newEditor); } @Override public List<Editor> getAllEditors() { return edao.getAllEditors(); } @Override public Editor getEditorById(Integer i) { return edao.getEditorById(i); } @Override public Editor getEditorByUsername(String username) { return edao.getEditorByUsername(username); } @Override public boolean updateEditor(Editor eChange) { return edao.updateEditor(eChange); } @Override public boolean removeEditor(Editor e) { return edao.removeEditor(e); } // @Override // public Editor getEditorByGenreTitle(String genre, String title) { // return edao.getEditorByGenreTitle(genre, title); // } }
true
26c92ef4a5ee08731457cd51199b50417337b838
Java
floryan62160/Cinema
/src/main/java/com/example/cinema/repositories/CinemaRepository.java
UTF-8
229
1.585938
2
[]
no_license
package com.example.cinema.repositories; import com.example.cinema.models.Cinema; import org.springframework.data.mongodb.repository.MongoRepository; public interface CinemaRepository extends MongoRepository<Cinema,String> { }
true
a6747b39669478de64d3c58f7bd304888610dd46
Java
engru/Android
/NewDevelop/src/com/oppo/transfer/core/socket/Server.java
UTF-8
7,071
2.203125
2
[]
no_license
package com.oppo.transfer.core.socket; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Looper; import com.oppo.transfer.core.utils.Constants; import com.oppo.transfer.core.utils.StateListener; import com.oppo.transfer.core.utils.TransStateMachine; import com.oppo.transfer.ui.WifiTransferActivity; public class Server { Context mContext; ServerSocket server = null; //多线程 private static List<Socket> list = new ArrayList<Socket>(); // 保存连接对象 private ExecutorService exec; FileReceiver fr = null; TransStateMachine mStateMachine; public Server(){ server = SocketUtils.getInstance().getServerInstance(null); listening(); } public Server(Context mContext){ this.mContext = mContext; server = SocketUtils.getInstance().getServerInstance(null); listening(); } public Server(Context mContext,StateListener sl){ this.mContext = mContext; mStateMachine = new TransStateMachine(); mStateMachine.registerSateListener(sl); server = SocketUtils.getInstance().getServerInstance(null); listening(); } private void listening() { // TODO Auto-generated method stub exec = Executors.newCachedThreadPool(); while (true) { try { Socket client = server.accept(); fr = new FileReceiver(client,mStateMachine);///////////////// if(false){ //sendFileToClient(socketToClient); //socketToClient.close(); }else{ list.add(client); exec.execute(new Task(client)); } } catch (IOException e) { e.printStackTrace(); } } } class Task implements Runnable{ Socket socket = null; public Task(Socket client) { // TODO Auto-generated constructor stub this.socket = client; //初始化的消息和操作 } @Override public void run() { //sendFile(socket); try { receiveInfo(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void receiveInfo() throws IOException { // TODO Auto-generated method stub mStateMachine.setState(TransStateMachine.Negotiate); getSendReq(); /*String CTR = null; while(true){ CTR = fr.getMsg(); //是文件还是文件夹, if(CTR.equals(Constants.END) || CTR.equals(Constants.EXCEP)){ //完成 socket.close(); return; }else if(CTR.equals(Constants.FILE)){ ReceiveFile(socket); }else if(CTR.equals(Constants.DIR)){ ReceiveFolder(socket); }else if(CTR.equals(Constants.DEFINED)){ ReceiveDefined(socket); } //协商参数 //正式传输 }*/ } private void getSendReq() { // TODO Auto-generated method stub try { String req = fr.getMsg(); if(req.equals(Constants.REQSEND)){ //dialog Looper.prepare(); if(mContext!=null){ System.out.println("mcontext "+mContext.toString()); }else{ System.out.println("mcontext null"); } AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage("收到发送请求").setTitle("是否接收?"); builder.setPositiveButton("确认接收", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点击“确认”后的操作 //返回确认 dialog.dismiss(); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub fr.sendMsg(Constants.ALLOW); try { receiveContent(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { fr.sendMsg(Constants.DENY); try { if(fr.getMsg().equals(Constants.END)) receiveComplete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } dialog.dismiss(); } }); AlertDialog ad = builder.create(); ad.show(); Looper.loop(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void receiveContent() throws IOException{ mStateMachine.setState(TransStateMachine.Transfer); String CTR = null; while(true){ CTR = fr.getMsg(); //是文件还是文件夹, if(CTR == null){ receiveComplete(); return; }else if(CTR.equals(Constants.END) || CTR.equals(Constants.EXCEP)){ //完成 receiveComplete(); return; }else if(CTR.equals(Constants.FILE)){ ReceiveFile(socket); }else if(CTR.equals(Constants.DIR)){ ReceiveFolder(socket); }else if(CTR.equals(Constants.DEFINED)){ ReceiveDefined(socket); } //协商参数 //正式传输 } } private void receiveComplete() throws IOException{ socket.close(); mStateMachine.setState(TransStateMachine.Complete); } } private void ReceiveFile(Socket socket){ try { String str = fr.getMsg(); System.out.println("receiverFile:begain"); if(str.equals(Constants.ONLYFILE)){ fr.downloadFile(); }else{ fr.downloadFile(str); } System.out.println("receiverFile:end"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String rePath = "/sdcard/Storage/"; private void ReceiveFolder(Socket socket){ try { String path = fr.getMsg(); if(path.equals(Constants.DIR)) path = fr.getMsg(); new File(rePath+path).mkdirs(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void ReceiveDefined(Socket socket){ new File("Defined").mkdir(); } /* private static final String fileToTransfer = "files/testing.xml"; private void sendFile(Socket socketToClient) throws IOException { try { FileSender sender = new FileSender(socketToClient); sender.sendFile(fileToTransfer); } catch (Exception ex) { System.out.println("Error communicating with client: " + ex.getMessage()); } } */ }
true
ead06b6e51d3c139ca8a9c025bd624f6e35178dc
Java
ProyectoDuolingo/lib
/src/main/java/lib/duolingoproject/hibernate/dao/UserDaoImpl.java
UTF-8
3,018
2.65625
3
[]
no_license
package lib.duolingoproject.hibernate.dao; import lib.duolingoproject.hibernate.dao.i.IUserDao; import lib.duolingoproject.hibernate.model.User; import lib.duolingoproject.hibernate.util.HibernateUtil; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; public class UserDaoImpl implements IUserDao{ // saveUser // getAllUsers // getUserById // updateUser // deleteUserById public User getUserById(long id) { Transaction transaction = null; User user = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // Start the transaction transaction = session.beginTransaction(); // Get User object user = session.get(User.class, id); // Commit the transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } return user; } public List<User> getAllUsers() { Transaction transaction = null; List<User> usersList = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // Start the transaction transaction = session.beginTransaction(); // Get Users list usersList = session.createQuery("from User").list(); // Commit the transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } return usersList; } public void saveUser(User user) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // Start the transaction transaction = session.beginTransaction(); // Save User object session.save(user); // Commit the transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } } public void updateUser(User user) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // Start the transaction transaction = session.beginTransaction(); // Save User object session.saveOrUpdate(user); // Commit the transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } } public void deleteUserById(long id) { Transaction transaction = null; User user = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // Start the transaction transaction = session.beginTransaction(); // Get User object user = session.get(User.class, id); // Delete User object session.delete(user); // Commit the transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } } }
true
36edc3c4a6370db2cfbd13228d618bf4adca40ba
Java
DungeonCore/Rires-Shine
/src/com/github/kasheight/Rire.java
UTF-8
748
3.140625
3
[]
no_license
package com.github.kasheight; import java.util.regex.*; public class Rire { static Character[] isCharacter = {'り', 'れ', 'す', 'し', 'ね'}; static Character charSet() { int random = (int)(Math.random() * 5); return Rire.isCharacter[random]; } public static void main(String[] args) { String content = ""; String truth = "りれすしね"; int i = 0; Pattern p = Pattern.compile(truth); Matcher m; do { System.out.print(charSet()); System.out.print(" ,"); m = p.matcher(content); content = content + charSet().toString(); i++; } while (!m.find()); System.out.println(""); System.out.println(i + "回目でりれすしねが見つかりました!"); } }
true
370867099c3437fc9aae5637b77e921aaf93855c
Java
TeishaMurray/MOD3_HW
/MOD3_Wk2_Hw3/src/OOP/Person.java
UTF-8
610
3.546875
4
[]
no_license
package OOP; public class Person { private String fname; private String lname; private String email; int age; public Person() { } public Person(String fname, String lname, String email, int age) { this.fname=fname; this.lname=lname; this.email=email; this.age=age; } void pInfo() { System.out.println(fname + " " + lname); System.out.println("Age " + age); } public static void main(String[] args) { //testing create object Person p1 = new Person(); p1.fname = "Teisha"; p1.lname = "Murray"; p1.email = "tmurrmurr@gmail.net"; p1.age = 35; p1.pInfo(); } }
true
a3c8899b77466ae7ac8c0aaf901d7ff11fc759e2
Java
oisindillon/checkers
/Board.java
UTF-8
6,899
3.203125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Board extends JFrame implements ActionListener{ //attributes private Checkers check; private Boolean firstClick = true; private int previous; private Boolean whiteTurn = true; //constructor public Board(Checkers c){ check = c; //initialises the frame this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(800,800); this.setLayout(new GridLayout(8, 8)); //initialising variables boolean colour = false; String type; for(int i=0; i<8; i++){ //Changes starting colour of each row if(colour == true) colour = false; else colour = true; for(int j=0; j<8; j++){ type = "NONE"; //Makes the colours alternate if(colour == true){ colour = false; } else{ colour = true; if(i <=8 && i >=5){ type = "WHITE"; } if(i>=0 && i<=2){ type = "RED"; } } //generates tile check.getArray()[i*8 + j] = new Square(i*100,j*100,colour,type); check.getArray()[i*8 + j].getTile().addActionListener(this); //Adds the tile to the board this.add(check.getArray()[i*8 + j].getTile()); } } this.setVisible(true); } //methods public void showOption(int change, boolean add, Square source){ //Shows the yellow panels where moves are possible if(add == true){ if(change != 0){ //checks to make sure the square in front is empty and that there is no overlapping from the array on the board int jumps =0; for(int j=0; j<64; j++){ int middle = check.getArray()[j].getX() - source.getX(); middle = middle/2; middle = previous+change*8+middle; Square mid = check.getArray()[middle]; //Sets a temporary "middle" value (value inbetween target and source) if(source.canJumpTo(check.getArray()[j], whiteTurn, mid)==true){ check.getArray()[j].editPiece("MAYBE"); jumps++; } } //only if there are no jumps available then it will show the moves available if(jumps == 0){ for(int j=0; j<64; j++){ if(source.canMoveTo(check.getArray()[j], whiteTurn)==true){ check.getArray()[j].editPiece("MAYBE"); } } } } } else{ //removes the yellow option tiles after the checker has not been moved //checks to see if the piece is yellow and then changes it to white //does not need to check for overlap as the overlapped tiles aren't yellow for(int j=0; j<64; j++){ if(check.getArray()[j].getPiece()=="MAYBE"){ check.getArray()[j].editPiece("NONE"); } } } } public boolean checkPossibleJump(int change){ int jumps =0; for(int i=0; i<64; i++){ for(int j=0; j<64; j++){ int middle = check.getArray()[j].getX() - check.getArray()[i].getX(); middle = middle/2; middle = previous+change*8+middle; Square mid = check.getArray()[middle]; //Sets a temporary "middle" value (value inbetween target and source) if(check.getArray()[i].canJumpTo(check.getArray()[j], whiteTurn, mid)==true){ jumps++; } } } if(jumps >0){ System.out.println(jumps); return true; } else{ return false; } } //ActionEvent for clicks public void actionPerformed(ActionEvent e){ int change; //Identifies first click if(firstClick==true){ for(int i =0; i<64; i++){ if(e.getSource() == check.getArray()[i].getTile()){ previous = i; } } firstClick = false; change = check.getArray()[previous].isWhite(); //works out diretion pieces are meant to move in this.showOption(change, true, check.getArray()[previous]); //displays possible moves by highlighting them } else{ //Identifies second click for(int i =0; i<64; i++){ if(e.getSource() == check.getArray()[i].getTile()){//Identifies which tile is selected change = check.getArray()[previous].isWhite();//works out diretion pieces are meant to move in //works out what the middle tile bewtween the previous and selected value int middle = check.getArray()[i].getX() - check.getArray()[previous].getX(); middle = middle/2; middle = previous+change*8+middle; //Moves the piece if(check.getArray()[i].getPiece() == "MAYBE"){ //only lets the peice move if its appears as yellow (a possible move) if(check.getArray()[previous].canJumpTo(check.getArray()[i], whiteTurn, check.getArray()[middle]) == true){ check.getArray()[middle].editPiece("NONE"); } //if the jump was big then it will change the middle piece so there is nothing there (the piece is eaten) check.getArray()[previous].editPiece(check.getArray()[previous].moveTo(check.getArray()[i])); //performs move to function //Changes turns of the player if(whiteTurn==true) whiteTurn=false; else whiteTurn=true; } this.showOption(change, false, check.getArray()[previous]);//removes the highlighted options change = check.getArray()[previous].isWhite();//works out diretion pieces are meant to move in if(checkPossibleJump(change)==true){ System.out.println("It works"); } } } firstClick = true; } } }
true
3c397048001486d94ea3a0e4d194f9fdd66dc7a0
Java
RayWP/FindEventWeb
/src/main/java/Servlet/UserRegistration.java
UTF-8
1,750
2.59375
3
[]
no_license
package Servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Entity.User; import Service.UserService; /** * Servlet implementation class UserRegistration */ @WebServlet("/UserRegistration") public class UserRegistration extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); request.setAttribute("username", username); String email = request.getParameter("email"); request.setAttribute("email", email); String description = request.getParameter("description"); request.setAttribute("description", description); String password = request.getParameter("password"); String re_password = request.getParameter("re_password"); // if password and re-type password is not the same if(!password.equals(re_password)) { request.setAttribute("error", "Password and re-type do not match!"); request.getRequestDispatcher("/register_user.jsp").forward(request, response); } else { User user = new User(username, re_password, email, description); int result = UserService.register(user); // if: failed to create account, else: success create account if(result<=0) { request.setAttribute("alert", "Email has been used"); request.getRequestDispatcher("/register_user.jsp").forward(request, response); } else { request.getRequestDispatcher("/UserLogin").forward(request, response); } } } }
true
443b071995987a372b563380fbc058731c330ac7
Java
Lik7/theInternet
/src/main/java/pages/DynamicLoadingPage.java
UTF-8
2,795
2.734375
3
[]
no_license
package pages; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class DynamicLoadingPage { private WebDriver driver; private By example1Link = By.linkText("Example 1: Element on page that is hidden"); private final By example2Link = By.linkText("Example 2: Element rendered after the fact"); public DynamicLoadingPage(WebDriver driver) { this.driver = driver; } public Example1Page clickExample1() { driver.findElement(example1Link).click(); return new Example1Page(driver); } public Example2Page clickExample2Link() { driver.findElement(example2Link).click(); return new Example2Page(driver); } // ctrl+click test private final By startButton = By.cssSelector("#start button"); public void ctrllickExample2Link() { Actions actions = new Actions(driver); actions.keyDown(Keys.LEFT_CONTROL).click(driver.findElement(example2Link)).perform(); } public Boolean checkStartButtonPresence() { return driver.findElement(startButton).isDisplayed(); } public class Example1Page { WebDriver driver; private By startButton = By.cssSelector("#start button"); private By loadingIndicator = By.id("loading"); private By finishText = By.id("finish"); public Example1Page(WebDriver driver) { this.driver = driver; } public void clickStartButton() { driver.findElement(startButton).click(); WebDriverWait wait = new WebDriverWait(driver, 8); wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loadingIndicator))); } public String getFinishText() { return driver.findElement(finishText).getText(); } } public static class Example2Page { private final WebDriver driver; private final By startButton = By.cssSelector("#start button"); private final By loadedText = By.id("finish"); public Example2Page(WebDriver driver) { this.driver = driver; } // loadedText element is absent, may not be checked immediately because it needs time to appear public void clickStartButton() { driver.findElement(startButton).click(); WebDriverWait webDriverWait = new WebDriverWait(driver, 5); webDriverWait.until(ExpectedConditions.presenceOfElementLocated(loadedText)); } public String getLoadedText() { return driver.findElement(loadedText).getText(); } } }
true
c1463518a75c6cff67bc146bc00016d2bb888deb
Java
ckliu2/chongkai
/java_src/zion/generated/src/com/web/dao/BulletinDAO.java
UTF-8
896
1.757813
2
[]
no_license
package com.web.dao; import com.web.value.Bulletin; import java.util.*; import com.common.dao.CommonDAO; /** WebWork Application Generator V 1.0 Copyright 2006 Chih-Shyang Chang Created Date: Wed Jun 04 15:59:11 CST 2014 */ public interface BulletinDAO extends CommonDAO { public abstract void saveBulletin(Bulletin val); public abstract void removeBulletin(Bulletin val); public abstract void removeBulletin(Long id); public abstract Bulletin findBulletinById(Long id); public abstract List<Bulletin> findAllBulletin(); public abstract List<Member> findLastModifiedUserList(); public abstract List<Member> findCreatedUserList(); public abstract List<UploadedFile> findFileList(); public abstract List<UploadedFile> findVoiceList(); public abstract List<UploadedFile> findVedioList(); public abstract List<UploadedFile> findFrontcoverList(); }
true
e8e18cc7ed675b91abb9df26e2a146c99353b787
Java
angelwsin/pn-server
/pn/androidpn-server/server/src/main/java/org/androidpn/server/xmpp/router/PacketRouter.java
UTF-8
1,947
2.21875
2
[]
no_license
/* * Copyright (C) 2010 Moduad Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.androidpn.server.xmpp.router; import java.util.HashMap; import java.util.Map; import org.xmpp.packet.Packet; import org.xmpp.packet.Roster; /** * This class is to handle incoming packets and route them to their corresponding handler. * * @author Sehwan Noh (devnoh@gmail.com) */ public class PacketRouter{ static final Map<Class<?>,Router> routers = new HashMap<Class<?>, Router>(4); /** * Routes the packet based on its type. * * @param packet the packet to route */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void route(Packet packet) { Router router= routers.get(packet.getClass()); if(router==null){ throw new IllegalArgumentException(); } router.route(packet); } static { Router messageRouter = new MessageRouter(); Router presenceRouter = new PresenceRouter(); Router iqRouter = new IQRouter(); routers.put(messageRouter.interest(), messageRouter); routers.put(presenceRouter.interest(), presenceRouter); routers.put(iqRouter.interest(), iqRouter); routers.put(Roster.class, iqRouter); } }
true
c19562620e73081bc638ab9858c9d4e79d6b02d1
Java
karakays/leetcode
/src/test/java/com/karakays/leetcode/solutions/S5Test.java
UTF-8
694
2.4375
2
[]
no_license
package com.karakays.leetcode.solutions; import org.junit.Assert; import org.junit.Test; public class S5Test extends Base { S5 s5 = new S5(); @Test public void test1() { Assert.assertEquals("bab", s5.longestPalindrome("babad")); } @Test public void test2() { Assert.assertEquals("bb", s5.longestPalindrome("cbbd")); } @Test public void test3() { Assert.assertEquals("a", s5.longestPalindrome("a")); } @Test public void test4() { Assert.assertEquals("a", s5.longestPalindrome("ab")); } @Test public void test5() { Assert.assertEquals("abccbaqq", s5.longestPalindrome("abccba")); } }
true
072d5481b87f8b1f57688882c8fdacec5d07ee8c
Java
abhilashjn85/high-power-microservice
/src/main/java/com/practice/highpower/configuration/RedisCacheConfiguration.java
UTF-8
1,702
2.3125
2
[]
no_license
package com.practice.highpower.configuration; import com.practice.highpower.entity.TweetEntity; import com.practice.highpower.service.SequenceGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.core.ReactiveRedisOperations; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import javax.annotation.PostConstruct; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.UUID; @Component class RedisCacheConfiguration { private final ReactiveRedisConnectionFactory factory; private final ReactiveRedisOperations<String, TweetEntity> tweetOps; @Autowired private SequenceGenerator sequenceGenerator; public RedisCacheConfiguration(ReactiveRedisConnectionFactory factory, ReactiveRedisOperations<String, TweetEntity> tweetOps) { this.factory = factory; this.tweetOps = tweetOps; } @PostConstruct public void loadData() { factory.getReactiveConnection().serverCommands().flushAll().thenMany( Flux.just("Jet Black Redis", "Darth Redis", "Black Alert Redis") .map(name -> new TweetEntity(sequenceGenerator.getNextSequenceId(TweetEntity.SEQUENCE_NAME), name)) .flatMap(tweet -> tweetOps.opsForValue().set(String.valueOf(tweet.getId()), tweet, Duration.of(30, ChronoUnit.SECONDS)))) .thenMany(tweetOps.keys("*") .flatMap(tweetOps.opsForValue()::get)) .subscribe(System.out::println); } }
true
e0b7f0fd6df1704026886ce7223aa33480bb2e52
Java
efreihpc/Backend
/application/src/main/java/backend/model/serviceprovider/ServiceProvider.java
UTF-8
924
2.21875
2
[]
no_license
package backend.model.serviceprovider; import java.util.HashMap; import backend.model.descriptor.ServiceDescriptor; import backend.model.result.Result; import backend.model.service.Service; import backend.model.service.ServiceEntity; import backend.system.GlobalPersistenceUnit; public interface ServiceProvider { public void persistenceUnit(GlobalPersistenceUnit persistenceUnit); public GlobalPersistenceUnit persistenceUnit(); // returns a hasmap cansisting of a preconfigured Service and the services description HashMap<String, ServiceDescriptor> services(); ServiceDescriptor serviceDescriptor(String serviceIdentifier); // returns the service identified by its Classname public <T extends Result> Service<T> service(String serviceName, Result configuration) throws InstantiationException, IllegalAccessException; public <T extends Result> void executeService(ServiceEntity<T> serviceToExecute); }
true
30cfbe9a4c086f671770021a46940fb59754ce24
Java
YangHanlin/kwic
/src/main/java/com/patterndemo/kwic/service/impl/IndexedResultServiceImpl.java
UTF-8
1,625
2.078125
2
[]
no_license
package com.patterndemo.kwic.service.impl; import com.patterndemo.kwic.entity.CorpusItem; import com.patterndemo.kwic.entity.IndexedResult; import com.patterndemo.kwic.repository.IndexedResultRepository; import com.patterndemo.kwic.service.IndexedResultService; import com.patterndemo.kwic.util.Constant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Service public class IndexedResultServiceImpl implements IndexedResultService { @Autowired private IndexedResultRepository repository; @Autowired private HttpSession session; @Override public List<IndexedResult> getBatch(String batchId) { return repository.findByBatchId(batchId); } @Override public void saveBatch(String batchId, List<IndexedResult> results) { results.forEach(result -> result.setBatchId(batchId)); repository.saveAll(results); } @Override public String saveBatch(List<IndexedResult> results) { String batchId = UUID.randomUUID().toString(); saveBatch(batchId, results); return batchId; } @Override public List<IndexedResult> getCache() { Object cache = session.getAttribute(Constant.INDEXED_RESULTS_CACHE_KEY); return cache == null ? new ArrayList<>() : (List<IndexedResult>) cache; } @Override public void saveCache(List<IndexedResult> results) { session.setAttribute(Constant.INDEXED_RESULTS_CACHE_KEY, results); } }
true