hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
364556b276663e0ef5b4cf7c303d1e8960b11387
314
package ntut.csie.accountManagementService.useCase.login; import ntut.csie.accountManagementService.useCase.Input; public interface LoginInput extends Input { public String getUsername(); public void setUsername(String username); public String getPassword(); public void setPassword(String password); }
20.933333
57
0.808917
a94f7964b8d8ef28edfc5f5bf572671b4d99679b
1,749
package kg.apc.perfmon.metrics.jmx; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; /** * @author undera */ public class JMXConnectorHelper { private static final Logger log = LoggingManager.getLoggerForClass(); public MBeanServerConnection getServerConnection(String url, String user, String pwd) { try { JMXConnector connector = getJMXConnector(url, user, pwd); return connector.getMBeanServerConnection(); } catch (Exception ex) { log.error("Failed to get JMX Connector", ex); throw new RuntimeException("Failed to get JMX Connector", ex); } } private JMXConnector getJMXConnector(String url, String usr, String pwd) throws MalformedURLException, IOException { String serviceUrl = "service:jmx:rmi:///jndi/rmi://" + url + "/jmxrmi"; if (usr == null || usr.trim().length() <= 0 || pwd == null || pwd.trim().length() <= 0) { JMXServiceURL surl = new JMXServiceURL(serviceUrl); return JMXConnectorFactory.connect(surl); } Map envMap = new HashMap(); envMap.put("jmx.remote.credentials", new String[]{usr, pwd}); envMap.put(Context.SECURITY_PRINCIPAL, usr); envMap.put(Context.SECURITY_CREDENTIALS, pwd); return JMXConnectorFactory.connect(new JMXServiceURL(serviceUrl), envMap); } }
37.212766
97
0.692396
fe4e3ac5c8ae60170b5587ec7c07cfeb4cabae63
1,539
package comp346pa3s2020; public class Producer extends Thread { private int[] buffer; private int index = 0; private double q = 0; private Semaphore mutex; private Semaphore full; private Semaphore empty; public Producer(int[] buffer, double q, Semaphore mutex, Semaphore full, Semaphore empty) { this.buffer = buffer; this.q = q; this.mutex = mutex; this.full = full; this.empty = empty; } public void produce() { while(true) { // --- Production block --- int next_produced; double P = Math.random(); //System.out.println("P = " + P + " q = " + q); if (P < q) { next_produced = (int)((Math.random() * 100 + 1)); if (empty.getS() == 0) System.out.println("DEBUG ::: BUFFER FULL, BUSY WAITING"); empty.wait(empty); if (mutex.getS() == buffer.length) System.out.println("DEBUG ::: MUTEX LOCKED, BUSY WAITING"); mutex.wait(mutex); // Add next produced to the buffer System.out.println("DEBUG ::: PRODUCING " + next_produced); buffer[index] = next_produced; index++; if (index == buffer.length) index = 0; System.out.println("DEBUG ::: BUFFER: [" + buffer[0] + ", " + buffer[1] + ", " + buffer[2] + ", " + buffer[3] + ", " + buffer[4] + ", " + buffer[5] + ", " + buffer[6] + ", " + buffer[7] + ", " + buffer[8] + ", " + buffer[9] + "]"); mutex.signal(mutex); full.signal(full); } System.out.println("DEBUG ::: MUTEX " + mutex + ", FULL " + full + ", EMPTY " + empty); } } public void run() { produce(); } }
30.176471
101
0.578947
3b2fcfd4c2c2ad0cc9e70f1f3e3a80d377eb2ae8
815
package com.thinkgem.jeesite.common.commonPay.pay.unionpay.config; import com.thinkgem.jeesite.common.commonPay.pay.unionpay.sdk.SDKConfig; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpServlet; public class InitAcpConfig extends HttpServlet implements ServletContextListener { //服务器关闭时执行 public void contextDestroyed(ServletContextEvent arg0) { System.out.println("--------server is close"); } //服务器启动时执行 public void contextInitialized(ServletContextEvent arg0) { System.out.println("--------server is start"); try { SDKConfig.getConfig().loadPropertiesFromSrc();// 从classpath加载acp_sdk.properties文件 }catch (Exception e){ e.printStackTrace(); } } }
27.166667
93
0.712883
4a67db7bfa9a90f1bf4522a91d22982f1574e5b1
2,375
package ro.pub.cs.systems.pdsd.practicaltest01; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; public class PracticalTest01SecondaryActivity extends ActionBarActivity { private static final int RESULT_OK = 1; private static final int RESULT_CANCEL = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test01_secondary); Intent rec_intent = getIntent(); if (rec_intent != null) { String number = rec_intent.getStringExtra("sum_display"); if (number != null) { EditText e = (EditText) findViewById(R.id.editText3); e.setText(number); } } Button b1 = (Button) findViewById(R.id.button4); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }); Button b2 = (Button) findViewById(R.id.button5); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); setResult(RESULT_CANCEL, intent); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_practical_test01_secondary, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
32.094595
80
0.626105
afa5c15b381d0ef9cdd3117111379373368690eb
2,335
package top.littlerich.virtuallocation.base; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import top.littlerich.virtuallocation.view.CustomProgressDialog; /** * Created by xuqingfu on 2017/4/15. */ public abstract class BaseActivity extends Activity { protected View mView; protected CustomProgressDialog progressDialog; protected Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); Object object = getContentViewId(); if (object instanceof Integer) { mView = LayoutInflater.from(this).inflate((Integer) object, null); } else if (object instanceof View) { mView = (View) object; } setContentView(mView); // toolbar = (Toolbar) findViewById(R.id.toolbar); IniView(); progressDialog = new CustomProgressDialog(this); progressDialog.setCancelable(true); progressDialog.setCanceledOnTouchOutside(false); IniLister(); IniData(); } /** * @Title: getContentViewId * @Description: 布局文件Id */ protected abstract Object getContentViewId(); /** * @Title: IniView * @Description: 初始化View */ protected abstract void IniView(); /** * @Title: IniLister * @Description: 初始化接口 */ protected abstract void IniLister(); /** * @Title: IniData * @Description: 初始化数据 */ protected abstract void IniData(); /** * thisFinish 当前关闭 */ protected abstract void thisFinish(); @Override public void onBackPressed() { thisFinish(); } /** * showProgressDialog 显示等待框 * * @param text 显示文字 */ public void showProgressDialog(String text) { if (progressDialog != null) { progressDialog.show(); progressDialog.setMessage(text); } } /** * cancelProgressDialog 取消等待框 */ public void cancelProgressDialog() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } }
24.322917
78
0.629122
db63a1514e9ade11f83af724737992c0e13f0708
10,287
/* * Sakuli - Testing and Monitoring-Tool for Websites and common UIs. * * Copyright 2013 - 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.sakuli.datamodel; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.sakuli.datamodel.state.SakuliState; import org.sakuli.exceptions.SakuliExceptionHandler; import org.sakuli.exceptions.SakuliExceptionWithScreenshot; import org.sakuli.services.InitializingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * @author tschneck * Date: 12.07.13 */ public abstract class AbstractTestDataEntity<S extends SakuliState> implements Comparable<AbstractTestDataEntity> { public final static DateFormat GUID_DATE_FORMATE = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SS"); public final static DateFormat PRINT_DATE_FORMATE = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); protected transient final Logger logger = LoggerFactory.getLogger(this.getClass()); protected Date startDate; protected Date stopDate; protected Exception exception; protected S state; protected String name; /** * is initial set to -1, if the database forwarder profile is enabled the service call {@link InitializingService#initTestSuite()} * should set the primary key. */ protected int dbPrimaryKey = -1; /** * needed to be set to -1, so the function {@link org.sakuli.actions.TestCaseAction#addTestCaseStep(String, String, String, int, int, boolean)} * can check if the method {@link org.sakuli.actions.TestCaseAction#initWarningAndCritical(int, int)} * have been called at the beginning of this test case. */ protected int warningTime = -1; protected int criticalTime = -1; protected String id; /** * represent the creation date for this entity, to enable effective sorting after it. * This is only for INTERNAL use. To get the date of starting this entity, see {@link #startDate}. **/ private DateTime creationDate; public AbstractTestDataEntity() { creationDate = new DateTime(); } protected static String getMessageOrClassName(Throwable e) { return StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage(); } /** * set the times to the format "time in millisec / 1000" * * @param date regular {@link Date} object * @return UNIX-Time formatted String */ protected String createUnixTimestamp(Date date) { if (date == null) { return "-1"; } else { String milliSec = String.valueOf(date.getTime()); return new StringBuilder(milliSec).insert(milliSec.length() - 3, ".").toString(); } } /** * calculate the duration * * @return the duration in seconds */ public float getDuration() { try { float result = (float) ((stopDate.getTime() - startDate.getTime()) / 1000.0); return (result < 0) ? -1 : result; } catch (NullPointerException e) { return -1; } } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getStopDate() { return stopDate; } public void setStopDate(Date stopDate) { this.stopDate = stopDate; } public String getStartDateAsUnixTimestamp() { return createUnixTimestamp(startDate); } public String getStopDateAsUnixTimestamp() { return createUnixTimestamp(stopDate); } public void addException(Exception e) { if (exception == null) { this.exception = e; } else { exception.addSuppressed(e); } } public Exception getException() { return exception; } public void clearException() { this.exception = null; } public String getExceptionMessages(boolean flatFormatted) { if (exception != null) { String msg = getMessageOrClassName(exception); //add suppressed exceptions for (Throwable ee : exception.getSuppressed()) { if (flatFormatted) { msg += " -- Suppressed EXCEPTION: " + getMessageOrClassName(ee); } else { msg += "\n\t\tSuppressed EXCEPTION: " + getMessageOrClassName(ee); } } if (flatFormatted) { msg = StringUtils.replace(msg, "\n", " "); msg = StringUtils.replace(msg, "\t", " "); } return msg; } else { return null; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDbPrimaryKey() { return dbPrimaryKey; } public void setDbPrimaryKey(int dbPrimaryKey) { this.dbPrimaryKey = dbPrimaryKey; } public int getWarningTime() { return warningTime; } /** * If the threshold is set to 0, the execution time will never exceed, so the state will be always OK! * * @param warningTime time in seconds */ public void setWarningTime(int warningTime) { this.warningTime = warningTime; } public int getCriticalTime() { return criticalTime; } /** * If the threshold is set to 0, the execution time will never exceed, so the state will be always OK! * * @param criticalTime time in seconds */ public void setCriticalTime(int criticalTime) { this.criticalTime = criticalTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * refresh the current state based on the set warning and critical times */ public abstract void refreshState(); public Path getScreenShotPath() { return SakuliExceptionHandler.getScreenshotFile(exception); } protected String getResultString() { String stout = "\nname: " + this.getName() + "\nRESULT STATE: " + this.getState(); if (this.getState() != null) { stout += "\nresult code: " + this.getState().getErrorCode(); } //if no exception is there, don't print it if (this.exception != null) { stout += "\nERRORS:" + this.getExceptionMessages(false); if (this.exception instanceof SakuliExceptionWithScreenshot) { stout += "\nERROR - SCREENSHOT: " + this.getScreenShotPath().toFile().getAbsolutePath(); } } stout += "\ndb primary key: " + this.getDbPrimaryKey() + "\nduration: " + this.getDuration() + " sec."; if (!(warningTime == -1)) { stout += "\nwarning time: " + this.getWarningTime() + " sec."; } if (!(criticalTime == -1)) { stout += "\ncritical time: " + this.getCriticalTime() + " sec."; } if (this.getStartDate() != null) { stout += "\nstart time: " + PRINT_DATE_FORMATE.format(this.getStartDate()); } if (this.getStopDate() != null) { stout += "\nend time: " + PRINT_DATE_FORMATE.format(this.getStopDate()); } return stout; } /** * @return a unique identifier for each execution of the test data entity */ public String getGuid() { Date guidDate = startDate != null ? startDate : new Date(); return id + "__" + GUID_DATE_FORMATE.format(guidDate); } public S getState() { return state; } public void setState(S state) { this.state = state; } public DateTime getCreationDate() { return creationDate; } public void setCreationDate(DateTime creationDate) { this.creationDate = creationDate; } @Override public int compareTo(AbstractTestDataEntity abstractSakuliTest) { if (abstractSakuliTest == null) { return 1; } if (super.equals(abstractSakuliTest)) { return 0; } Date startDate2 = abstractSakuliTest.getStartDate(); if (this.startDate == null || startDate2 == null || this.startDate.compareTo(startDate2) == 0) { boolean boothNull = this.startDate == null && startDate2 == null; if (!boothNull) { if (this.startDate == null) { return 1; } if (startDate2 == null) { return -1; } } return creationDate.compareTo(abstractSakuliTest.getCreationDate()); } return this.startDate.compareTo(startDate2); } @Override public boolean equals(Object obj) { if (obj instanceof AbstractTestDataEntity) { return compareTo((AbstractTestDataEntity) obj) == 0; } return super.equals(obj); } @Override public String toString() { return "startDate=" + startDate + ", stopDate=" + stopDate + ", exception=" + exception + ", state=" + state + ", name='" + name + '\'' + ", dbPrimaryKey=" + dbPrimaryKey + ", warningTime=" + warningTime + ", criticalTime=" + criticalTime ; } public String toStringShort() { return String.format("%s [id = %s, name = %s]", this.getClass().getSimpleName(), id, name); } }
30.891892
147
0.598231
266342920ef0c71e03744f19238dcceefe4d5e2f
453
package daggerok.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties(prefix = "boot-reactive-backend") public class ReactiveBackendConfig { String ip; Integer port; String baseUrl; Credentials credentials; @Data public static class Credentials { String username; String password; } }
19.695652
75
0.783664
704acc233a114e3e6a1035bc5554e79eda558a88
10,362
package com.melissadata.personatorworld.model; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class PersonatorWorldOptions { private final StringProperty optionCorrectFirstName; private final StringProperty optionNameHint; private final StringProperty optionGenderPopulation; private final StringProperty optionGenderAggression; private final StringProperty optionMiddleNameLogic; private final StringProperty optionDeliveryLines; private final StringProperty optionLineSeparator; private final StringProperty optionOutputScript; private final StringProperty optionPhoneVerifyLevel; private final StringProperty optionCallerID; private final StringProperty optionDefaultCallingCode; private final StringProperty optionTimeToWaitPhone; private final StringProperty optionEmailVerifyMailboxLevel; private final StringProperty optionDomainCorrection; private final StringProperty optionTimeToWaitEmail; public PersonatorWorldOptions() { optionCorrectFirstName = new SimpleStringProperty(""); optionNameHint = new SimpleStringProperty(""); optionGenderPopulation = new SimpleStringProperty(""); optionGenderAggression = new SimpleStringProperty(""); optionMiddleNameLogic = new SimpleStringProperty(""); optionDeliveryLines = new SimpleStringProperty(""); optionLineSeparator = new SimpleStringProperty(""); optionOutputScript = new SimpleStringProperty(""); optionPhoneVerifyLevel = new SimpleStringProperty(""); optionCallerID = new SimpleStringProperty(""); optionDefaultCallingCode = new SimpleStringProperty(""); optionTimeToWaitPhone = new SimpleStringProperty(""); optionEmailVerifyMailboxLevel = new SimpleStringProperty(""); optionDomainCorrection = new SimpleStringProperty(""); optionTimeToWaitEmail = new SimpleStringProperty(""); } public String generateOptionString() { String optionString = ""; String nameOptions = generateNameOptionString(); String addressOptions = generateAddressOptionString(); String phoneOptions = generatePhoneOptionString(); String emailOptions = generateEmailOptionString(); if(!nameOptions.equals("")) optionString += "&nameOpt=" + nameOptions; if(!addressOptions.equals("")) optionString += "&AddrOpt=" + addressOptions; if(!phoneOptions.equals("")) optionString += "&PhoneOpt=" + phoneOptions; if(!emailOptions.equals("")) optionString += "&EmailOpt=" + emailOptions; return optionString; } // Generate Name Options Portion of String public String generateNameOptionString(){ String[] options = { generateOptionParam("CorrectFirstName", getOptionCorrectFirstName()), generateOptionParam("NameHint", getOptionNameHint()), generateOptionParam("GenderPopulation", getOptionGenderPopulation()), generateOptionParam("GenderAggression", getOptionGenderAggression()), generateOptionParam("MiddleNameLogic", getOptionMiddleNameLogic()), }; return joinOptionParams(options); } // Generate Address Option Portion of String public String generateAddressOptionString(){ String[] options = { generateOptionParam("DeliveryLines", getOptionDeliveryLines()), generateOptionParam("LineSeparator", getOptionLineSeparator()), generateOptionParam("OutputScript", getOptionOutputScript()), }; return joinOptionParams(options); } // Generate Phone Option Portion of String public String generatePhoneOptionString(){ String[] options = { generateOptionParam("VerifyPhone", getOptionPhoneVerifyLevel()), generateOptionParam("CallerID", getOptionCallerID()), generateOptionParam("DefaultCallingCode", getOptionDefaultCallingCode()), generateOptionParam("TimeToWait", getOptionTimeToWaitPhone()), }; return joinOptionParams(options); } // Generate Email Option Portion of String public String generateEmailOptionString() { String[] options = { generateOptionParam("VerifyMailbox", getOptionEmailVerifyMailboxLevel()), generateOptionParam("DomainCorrection", getOptionDomainCorrection()), generateOptionParam("TimeToWait", getOptionTimeToWaitEmail()), }; return joinOptionParams(options); } private String generateOptionParam(String name, String value) { return value.equals("") ? "" : name + ":" + value; } private String joinOptionParams(String[] options) { List<String> optionList = new ArrayList<>(); for (String option : options) { if(!option.equals("")) optionList.add(option); } return String.join(",", optionList); } public String getOptionCorrectFirstName() { return optionCorrectFirstName.get(); } public StringProperty optionCorrectFirstNameProperty() { return optionCorrectFirstName; } public void setOptionCorrectFirstName(String optionCorrectFirstName) { this.optionCorrectFirstName.set(optionCorrectFirstName); } public String getOptionNameHint() { return optionNameHint.get(); } public StringProperty optionNameHintProperty() { return optionNameHint; } public void setOptionNameHint(String optionNameHint) { this.optionNameHint.set(optionNameHint); } public String getOptionGenderPopulation() { return optionGenderPopulation.get(); } public StringProperty optionGenderPopulationProperty() { return optionGenderPopulation; } public void setOptionGenderPopulation(String optionGenderPopulation) { this.optionGenderPopulation.set(optionGenderPopulation); } public String getOptionGenderAggression() { return optionGenderAggression.get(); } public StringProperty optionGenderAggressionProperty() { return optionGenderAggression; } public void setOptionGenderAggression(String optionGenderAggression) { this.optionGenderAggression.set(optionGenderAggression); } public String getOptionMiddleNameLogic() { return optionMiddleNameLogic.get(); } public StringProperty optionMiddleNameLogicProperty() { return optionMiddleNameLogic; } public void setOptionMiddleNameLogic(String optionMiddleNameLogic) { this.optionMiddleNameLogic.set(optionMiddleNameLogic); } public String getOptionDeliveryLines() { return optionDeliveryLines.get(); } public StringProperty optionDeliveryLinesProperty() { return optionDeliveryLines; } public void setOptionDeliveryLines(String optionDeliveryLines) { this.optionDeliveryLines.set(optionDeliveryLines); } public String getOptionLineSeparator() { return optionLineSeparator.get(); } public StringProperty optionLineSeparatorProperty() { return optionLineSeparator; } public void setOptionLineSeparator(String optionLineSeparator) { this.optionLineSeparator.set(optionLineSeparator); } public String getOptionOutputScript() { return optionOutputScript.get(); } public StringProperty optionOutputScriptProperty() { return optionOutputScript; } public void setOptionOutputScript(String optionOutputScript) { this.optionOutputScript.set(optionOutputScript); } public String getOptionPhoneVerifyLevel() { return optionPhoneVerifyLevel.get(); } public StringProperty optionPhoneVerifyLevelProperty() { return optionPhoneVerifyLevel; } public void setOptionPhoneVerifyLevel(String optionPhoneVerifyLevel) { this.optionPhoneVerifyLevel.set(optionPhoneVerifyLevel); } public String getOptionCallerID() { return optionCallerID.get(); } public StringProperty optionCallerIDProperty() { return optionCallerID; } public void setOptionCallerID(String optionCallerID) { this.optionCallerID.set(optionCallerID); } public String getOptionDefaultCallingCode() { return optionDefaultCallingCode.get(); } public StringProperty optionDefaultCallingCodeProperty() { return optionDefaultCallingCode; } public void setOptionDefaultCallingCode(String optionDefaultCallingCode) { this.optionDefaultCallingCode.set(optionDefaultCallingCode); } public String getOptionTimeToWaitPhone() { return optionTimeToWaitPhone.get(); } public StringProperty optionTimeToWaitPhoneProperty() { return optionTimeToWaitPhone; } public void setOptionTimeToWaitPhone(String optionTimeToWaitPhone) { this.optionTimeToWaitPhone.set(optionTimeToWaitPhone); } public String getOptionEmailVerifyMailboxLevel() { return optionEmailVerifyMailboxLevel.get(); } public StringProperty optionEmailVerifyMailboxLevelProperty() { return optionEmailVerifyMailboxLevel; } public void setOptionEmailVerifyMailboxLevel(String optionEmailVerifyMailboxLevel) { this.optionEmailVerifyMailboxLevel.set(optionEmailVerifyMailboxLevel); } public String getOptionDomainCorrection() { return optionDomainCorrection.get(); } public StringProperty optionDomainCorrectionProperty() { return optionDomainCorrection; } public void setOptionDomainCorrection(String optionDomainCorrection) { this.optionDomainCorrection.set(optionDomainCorrection); } public String getOptionTimeToWaitEmail() { return optionTimeToWaitEmail.get(); } public StringProperty optionTimeToWaitEmailProperty() { return optionTimeToWaitEmail; } public void setOptionTimeToWaitEmail(String optionTimeToWaitEmail) { this.optionTimeToWaitEmail.set(optionTimeToWaitEmail); } }
33.533981
88
0.704111
1c63e0fa85c1debb836268183cdc4b7acc0ecd1a
2,683
package ibm.wjx.osserver.web.controller; import ibm.wjx.osserver.manager.PodNetworkManager; import ibm.wjx.osserver.pojo.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.stream.Collectors; /** * Create Date: 1/5/18 * * @author <a href="mailto:wu812730157@gmail.com">Wujunxian</a> * Description: */ @RestController @RequestMapping("/pod-network") public class PodNetworkController { @Autowired private PodNetworkManager podNetworkManager; @RequestMapping(value = "/join-project", params = {"to", "selector"}) public Result<Boolean> joinProject(@RequestParam("to") String toProject, @RequestParam("selector") String selector) { return podNetworkManager.joinProjects(toProject, selector); } /** * @param toProject * @param projects project names split using comma. * @return true indicate success, false otherwise */ @RequestMapping(value = "/join-project", params = {"to", "projects"}) public Result<Boolean> joinProjects(@RequestParam("to") String toProject, @RequestParam("projects") String projects) { return podNetworkManager.joinProjects(toProject, Arrays.stream(projects.split(",")).collect(Collectors.toList())); } @RequestMapping(value = "/isolate-project", params = "selector") public Result<Boolean> isolateProject(String selector) { return podNetworkManager.isolateProjects(selector); } /** * @param projects project names split using comma. * @return true indicate success, false otherwise */ @RequestMapping(value = "/isolate-project", params = "projects") public Result<Boolean> isolateProjects(@RequestParam("projects") String projects) { return podNetworkManager.isolateProjects(Arrays.stream(projects.split(",")).collect(Collectors.toList())); } @RequestMapping(value = "/make-project-global", params = "selector") public Result<Boolean> makeProjectGlobal(@RequestParam("selector") String selector) { return podNetworkManager.makeProjectsGlobal(selector); } /** * @param projects project names split using comma. * @return true indicate success, false otherwise */ @RequestMapping(value = "/make-project-global", params = "projects") public Result<Boolean> makeProjectsGlobal(String projects) { return podNetworkManager.makeProjectsGlobal(Arrays.stream(projects.split(",")).collect(Collectors.toList())); } }
37.788732
122
0.723071
f9608b5dc93b49cc09d8888932f1cb7ff77f5dbf
1,554
package mage.cards.w; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.effects.common.turn.AddExtraTurnTargetEffect; import mage.abilities.keyword.BuybackAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterControlledPermanent; import mage.target.TargetPlayer; import mage.target.common.TargetControlledPermanent; import java.util.UUID; /** * @author LevelX2 */ public final class WalkTheAeons extends CardImpl { private static final FilterControlledPermanent filter = new FilterControlledPermanent("Islands"); static { filter.add(SubType.ISLAND.getPredicate()); } public WalkTheAeons(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{4}{U}{U}"); // Buyback—Sacrifice three Islands. (You may sacrifice three Islands in addition to any other costs as you cast this spell. If you do, put this card into your hand as it resolves.) this.addAbility(new BuybackAbility(new SacrificeTargetCost(new TargetControlledPermanent(3, filter)))); // Target player takes an extra turn after this one. this.getSpellAbility().addEffect(new AddExtraTurnTargetEffect()); this.getSpellAbility().addTarget(new TargetPlayer()); } private WalkTheAeons(final WalkTheAeons card) { super(card); } @Override public WalkTheAeons copy() { return new WalkTheAeons(this); } }
33.06383
188
0.741956
5289b8ed8f19ca7e85606163da85935ee8e26ce8
80
package lara; class F { void test1() { System.out.println("test1"); } }
8
30
0.5875
9f782fa9f50f49c2f85b457b7dec1463eeb45330
1,002
package com.stylefeng.guns.rest.modular.order.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; public class MyJsonUtils { public static <T> T readJsonFromClassPath(String path, Type type) throws IOException { ClassPathResource resource = new ClassPathResource(path); if (resource.exists()) { return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type, // 自动关闭流 Feature.AutoCloseSource, // 允许注释 Feature.AllowComment, // 允许单引号 Feature.AllowSingleQuotes, // 使用 Big decimal Feature.UseBigDecimal); } else { throw new IOException(); } } }
33.4
93
0.596806
658c1f09046c4818461974d593b354b984040549
6,199
package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.equalTo; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.io.FileUtils; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.util.CompressArchiveUtil; @Test(groups = "integration") public class CopyArchiveToContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws Exception { super.beforeTest(); } @AfterTest public void afterTest() { super.afterTest(); } @BeforeMethod public void beforeMethod(Method method) { super.beforeMethod(method); } @AfterMethod public void afterMethod(ITestResult result) { super.afterMethod(result); } @Test public void copyFileToContainer() throws Exception { CreateContainerResponse container = prepareContainerForCopy(); Path temp = Files.createTempFile("", ".tar.gz"); CompressArchiveUtil.tar(Paths.get("src/test/resources/testReadFile"), temp, true, false); try (InputStream uploadStream = Files.newInputStream(temp)) { dockerClient.copyArchiveToContainerCmd(container.getId()).withTarInputStream(uploadStream).exec(); assertFileCopied(container); } } @Test public void copyStreamToContainer() throws Exception { CreateContainerResponse container = prepareContainerForCopy(); dockerClient.copyArchiveToContainerCmd(container.getId()).withHostResource("src/test/resources/testReadFile") .exec(); assertFileCopied(container); } private CreateContainerResponse prepareContainerForCopy() { CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withName("docker-java-itest-copyToContainer").exec(); LOG.info("Created container: {}", container); assertThat(container.getId(), not(isEmptyOrNullString())); dockerClient.startContainerCmd(container.getId()).exec(); // Copy a folder to the container return container; } private void assertFileCopied(CreateContainerResponse container) throws IOException { try (InputStream response = dockerClient.copyArchiveFromContainerCmd(container.getId(), "testReadFile").exec()) { boolean bytesAvailable = response.available() > 0; assertTrue(bytesAvailable, "The file was not copied to the container."); } } @Test(expectedExceptions = NotFoundException.class) public void copyToNonExistingContainer() throws Exception { dockerClient.copyArchiveToContainerCmd("non-existing").withHostResource("src/test/resources/testReadFile").exec(); } @Test public void copyDirWithLastAddedTarEntryEmptyDir() throws Exception{ // create a temp dir Path localDir = Files.createTempDirectory(null); localDir.toFile().deleteOnExit(); // create empty sub-dir with name b Files.createDirectory(localDir.resolve("b")); // create sub-dir with name a Path dirWithFile = Files.createDirectory(localDir.resolve("a")); // create file in sub-dir b, name or conter are irrelevant Files.createFile(dirWithFile.resolve("file")); // create a test container CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withCmd("sleep", "9999") .exec(); // start the container dockerClient.startContainerCmd(container.getId()).exec(); // copy data from local dir to container dockerClient.copyArchiveToContainerCmd(container.getId()) .withHostResource(localDir.toString()) .exec(); // cleanup dir FileUtils.deleteDirectory(localDir.toFile()); } @Test public void copyFileWithExecutePermission() throws Exception { // create script file, add permission to execute Path scriptPath = Files.createTempFile("run", ".sh"); boolean executable = scriptPath.toFile().setExecutable(true, false); if (!executable){ throw new Exception("Execute permission on file not set!"); } String snippet = "Running script with execute permission."; String scriptTextStr = "#!/bin/sh\necho \"" + snippet + "\""; // write content for created script Files.write(scriptPath, scriptTextStr.getBytes()); // create a test container which starts and waits 3 seconds for the // script to be copied to the container's home dir and then executes it String containerCmd = "sleep 3; /home/" + scriptPath.getFileName().toString(); CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withName("test") .withCmd("/bin/sh", "-c", containerCmd) .exec(); // start the container dockerClient.startContainerCmd(container.getId()).exec(); // copy script to container home dir dockerClient.copyArchiveToContainerCmd(container.getId()) .withRemotePath("/home") .withHostResource(scriptPath.toString()) .exec(); // await exid code int exitCode = dockerClient.waitContainerCmd(container.getId()) .exec(new WaitContainerResultCallback()) .awaitStatusCode(); // check result assertThat(exitCode, equalTo(0)); } }
40.253247
122
0.683336
a92981b4e6bfbbeddffda00d8057e5f9c82e5bc9
3,893
/* * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. */ package jsystem.treeui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import jsystem.framework.scenario.JTest; import jsystem.framework.scenario.MultipleScenarioOps; import jsystem.treeui.teststable.TestsTableController; /** * this class builds the user documentation text area and listens to the APPLY * button on the test information TAB * * @author Nizan Freedman * */ public class UserDocumentation extends JPanel implements MouseListener { /** * */ private static final long serialVersionUID = 1L; private String doc; private static Logger log = Logger.getLogger(UserDocumentation.class.getName()); private JTextArea testUserDocumentation; private JButton applyButton; private JButton clearButton; private JSplitPane sp; private JTest currentTest; private TestsTableController testTableController; public UserDocumentation(TestsTableController testTableController) { this.testTableController = testTableController; buildTextArea(); } /** * build a JTextArea with a scroll panel and a "update button" for the user * test documentation * */ private void buildTextArea() { setLayout(new BorderLayout()); applyButton = new JButton("Apply"); applyButton.addMouseListener(this); applyButton.setSize(new Dimension(80, 20)); clearButton = new JButton("Clear"); clearButton.addMouseListener(this); clearButton.setSize(new Dimension(80, 20)); int width = 250; JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(applyButton, BorderLayout.WEST); p.setBackground(new Color(0xf6, 0xf6, 0xf6)); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); p2.add(clearButton, BorderLayout.WEST); p2.setBackground(new Color(0xf6, 0xf6, 0xf6)); sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p, p2); sp.setDividerLocation(width / 3); sp.setDividerSize(0); testUserDocumentation = new JTextArea(); JScrollPane userSP = new JScrollPane(testUserDocumentation); userSP.setSize(200, 100); add(userSP, BorderLayout.CENTER); add(sp, BorderLayout.SOUTH); resetText("", false); } /** * the implementation is for the APPLY and CLEAR buttons which updates the * appropriate xml file */ public void mousePressed(MouseEvent e) { Object source = e.getSource(); JTest test = currentTest; if (source.equals(applyButton)) { doc = testUserDocumentation.getText(); try { MultipleScenarioOps.updateDocumentation(test, doc); testTableController.refreshTree(); } catch (Exception e1) { log.log(Level.WARNING, "Fail to update scenario after userDoc Apply", e1); } } else if (source.equals(clearButton)) { test.setDocumentation(""); testUserDocumentation.setText(""); } } /** * reset the text area * * @param txt - * the txt to show * @param enable - * to enable editing + button */ public void resetText(String txt, boolean enable) { setEnabled(enable); testUserDocumentation.setEnabled(enable); applyButton.setEnabled(enable); clearButton.setEnabled(enable); testUserDocumentation.setText(txt); } public void setTest(JTest test) { this.currentTest = test; } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }
23.883436
81
0.73234
476c541980679ce66db2468c72742e3def77e99d
84
package com.ubuntuvim.spring.autowire; public interface Fruit { void eatable(); }
14
38
0.761905
716236bf5e9ed61cffb22e372bca668a30202ccb
12,597
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk.filemetadata; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.google.android.apps.forscience.javalib.FailureListener; import com.google.android.apps.forscience.javalib.MaybeConsumers; import com.google.android.apps.forscience.whistlepunk.AppSingleton; import com.google.android.apps.forscience.whistlepunk.ElapsedTimeFormatter; import com.google.android.apps.forscience.whistlepunk.R; import com.google.android.apps.forscience.whistlepunk.SensorAppearanceProvider; import com.google.android.apps.forscience.whistlepunk.SensorAppearanceProviderImpl; import com.google.android.apps.forscience.whistlepunk.data.GoosciSensorAppearance; import com.google.android.apps.forscience.whistlepunk.data.GoosciSensorLayout; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciCaption; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciLabel; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciPictureLabelValue; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciTrial; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a recorded trial. * All changes should be made using the getters and setters provided, rather than by getting the * underlying protocol buffer and making changes to that directly. */ public class Trial extends LabelListHolder { private static final String TAG = "Trial"; public static final Comparator<Trial> COMPARATOR_BY_TIMESTAMP = (first, second) -> { // Sort based on the recording first timestamp. return Long.compare(first.getOriginalFirstTimestamp(), second.getOriginalFirstTimestamp()); }; interface OnLabelChangeListener { void onPictureLabelAdded(Label label); void beforeDeletingPictureLabel(Label label); } private GoosciTrial.Trial mTrial; private Map<String, TrialStats> mTrialStats; private OnLabelChangeListener mOnLabelChangeListener; /** * Populates the Trial from an existing proto. */ public static Trial fromTrial(GoosciTrial.Trial trial) { return new Trial(trial); } /** * Invoked when recording begins to save the metadata about what's being recorded. */ public static Trial newTrial(long startTimeMs, GoosciSensorLayout.SensorLayout[] sensorLayouts, SensorAppearanceProvider provider, Context context) { String trialId = java.util.UUID.randomUUID().toString(); return new Trial(startTimeMs, sensorLayouts, trialId, provider, context); } private Trial(GoosciTrial.Trial trial) { mTrial = trial; mTrialStats = TrialStats.fromTrial(mTrial); mLabels = new ArrayList<>(); for (GoosciLabel.Label proto : mTrial.labels) { mLabels.add(Label.fromLabel(proto)); } } // TODO: eventually provider should go away, in favor of a different structure containing // sensor_specs private Trial(long startTimeMs, GoosciSensorLayout.SensorLayout[] sensorLayouts, String trialId, SensorAppearanceProvider provider, Context context) { mTrial = new GoosciTrial.Trial(); mTrial.creationTimeMs = startTimeMs; mTrial.recordingRange = new GoosciTrial.Range(); mTrial.recordingRange.startMs = startTimeMs; mTrial.sensorLayouts = sensorLayouts; mTrial.trialId = trialId; mTrial.sensorAppearances = new GoosciTrial.Trial.AppearanceEntry[sensorLayouts.length]; for (int i = 0; i < sensorLayouts.length; i++) { GoosciTrial.Trial.AppearanceEntry entry = new GoosciTrial.Trial.AppearanceEntry(); GoosciSensorLayout.SensorLayout layout = sensorLayouts[i]; entry.sensorId = layout.sensorId; entry.rememberedAppearance = SensorAppearanceProviderImpl.appearanceToProto( provider.getAppearance(layout.sensorId), context); mTrial.sensorAppearances[i] = entry; } mLabels = new ArrayList<>(); mTrialStats = new HashMap<>(); } public GoosciPictureLabelValue.PictureLabelValue getCoverPictureLabelValue() { for (Label label : mLabels) { if (label.getType() == GoosciLabel.Label.PICTURE) { return label.getPictureLabelValue(); } } return null; } public long getCreationTimeMs() { return mTrial.creationTimeMs; } public long getFirstTimestamp() { return mTrial.cropRange == null ? mTrial.recordingRange.startMs : mTrial.cropRange.startMs; } public long getLastTimestamp() { return mTrial.cropRange == null ? mTrial.recordingRange.endMs : mTrial.cropRange.endMs; } public long getOriginalFirstTimestamp() { return mTrial.recordingRange.startMs; } public long getOriginalLastTimestamp() { return mTrial.recordingRange.endMs; } public void setRecordingEndTime(long recordingEndTime) { mTrial.recordingRange.endMs = recordingEndTime; } public GoosciTrial.Range getOriginalRecordingRange() { return mTrial.recordingRange; } public GoosciTrial.Range getCropRange() { return mTrial.cropRange; } public void setCropRange(GoosciTrial.Range cropRange) { mTrial.cropRange = cropRange; } public List<String> getSensorIds() { List<String> result = new ArrayList<>(); for (GoosciSensorLayout.SensorLayout layout : mTrial.sensorLayouts) { result.add(layout.sensorId); } return result; } public long elapsedSeconds() { if (!isValid()) { return 0; } return Math.round((getLastTimestamp() - getFirstTimestamp()) / 1000.0); } public boolean isValid() { return getOriginalFirstTimestamp() > 0 && getOriginalLastTimestamp() > getOriginalFirstTimestamp(); } public String getTitleWithDuration(Context context) { return context.getString(R.string.title_with_duration, getTitle(context), ElapsedTimeFormatter.getInstance(context).format(elapsedSeconds())); } public String getTitle(Context context) { if (TextUtils.isEmpty(mTrial.title)) { return context.getString(R.string.default_trial_title, mTrial.trialNumberInExperiment); } else { return mTrial.title; } } public String getRawTitle() { return mTrial.title; } public void setTitle(String title) { mTrial.title = title; } public boolean isArchived() { return mTrial.archived; } public void setArchived(boolean isArchived) { mTrial.archived = isArchived; } public GoosciTrial.Trial getTrialProto() { updateTrialProtoWithStats(); updateTrialProtoWithLabels(); return mTrial; } public List<GoosciSensorLayout.SensorLayout> getSensorLayouts() { return new ArrayList(Arrays.asList(mTrial.sensorLayouts)); } @VisibleForTesting public void setSensorLayouts(List<GoosciSensorLayout.SensorLayout> sensorLayouts) { Preconditions.checkNotNull(sensorLayouts); mTrial.sensorLayouts = sensorLayouts.toArray(new GoosciSensorLayout.SensorLayout[ sensorLayouts.size()]); } public boolean getAutoZoomEnabled() { return mTrial.autoZoomEnabled; } public void setAutoZoomEnabled(boolean enableAutoZoom) { mTrial.autoZoomEnabled = enableAutoZoom; } /** * Gets a list of the stats for all sensors. */ public List<TrialStats> getStats() { return new ArrayList<>(mTrialStats.values()); } /** * Gets the stats for a sensor. */ public TrialStats getStatsForSensor(String sensorId) { return mTrialStats.get(sensorId); } /** * Sets the stats for a sensor. This will overwrite existing stats. * @param newTrialStats The new stats to save. */ public void setStats(TrialStats newTrialStats) { mTrialStats.put(newTrialStats.getSensorId(), newTrialStats); } // The Trial ID cannot be set after it is created. public String getTrialId() { return mTrial.trialId; } public String getCaptionText() { if (mTrial.caption == null) { return ""; } return mTrial.caption.text; } public void setCaption(GoosciCaption.Caption caption) { mTrial.caption = caption; } /** * Deletes the trial and any assets associated with it, including labels and label pictures, * run data, etc. */ public void deleteContents(Context context, String experimentId) { for (Label label : mLabels) { deleteLabelAssets(label, context, experimentId); } AppSingleton.getInstance(context).getDataController().deleteTrialData(this, MaybeConsumers.expectSuccess(new FailureListener() { @Override public void fail(Exception e) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Error deleting trial data"); } } })); // TODO: Also delete any other assets associated with this trial, including icons, etc // from the sensor appearance. } private void updateTrialProtoWithStats() { GoosciTrial.SensorTrialStats[] result = new GoosciTrial.SensorTrialStats[mTrialStats.size()]; int i = 0; for (String key : mTrialStats.keySet()) { result[i++] = mTrialStats.get(key).getSensorTrialStatsProto(); } mTrial.trialStats = result; } private void updateTrialProtoWithLabels() { GoosciLabel.Label[] result = new GoosciLabel.Label[mLabels.size()]; for (int i = 0; i < mLabels.size(); i++) { result[i] = mLabels.get(i).getLabelProto(); } mTrial.labels = result; } public void setOnLabelChangeListener(OnLabelChangeListener listener) { mOnLabelChangeListener = listener; } @Override protected void onPictureLabelAdded(Label label) { if (mOnLabelChangeListener != null) { mOnLabelChangeListener.onPictureLabelAdded(label); } } @Override protected void beforeDeletingPictureLabel(Label label) { if (mOnLabelChangeListener != null) { mOnLabelChangeListener.beforeDeletingPictureLabel(label); } } /** * @return a map of sensor ids (as returned from {@link #getSensorIds()}) to appearance * protos. This map should not be changed; changes have no effect. */ public Map<String, GoosciSensorAppearance.BasicSensorAppearance> getAppearances() { // TODO: need a putAppearance method for changes HashMap<String, GoosciSensorAppearance.BasicSensorAppearance> appearances = new HashMap<>(); for (GoosciTrial.Trial.AppearanceEntry entry : mTrial.sensorAppearances) { appearances.put(entry.sensorId, entry.rememberedAppearance); } return appearances; } @Override public String toString() { return "Trial{" + "mTrial=" + mTrial + ", mTrialStats=" + mTrialStats + '}'; } public void setTrialNumberInExperiment(int trialNumberInExperiment) { mTrial.trialNumberInExperiment = trialNumberInExperiment; } public int getTrialNumberInExperiment() { return mTrial.trialNumberInExperiment; } }
34.512329
100
0.669763
771b776934580b9ac90cf10f8cf7db03887a7efc
416
package tihkoff.taxi.dto; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import java.util.List; @Getter @Setter @NoArgsConstructor public class RateEntityDTO { private Long id; @NotNull @Length(max = 500) private String review; private TaxiOrderDTO taxiOrder; }
16
50
0.766827
73f6b3622d769810acf409e5b279f716c78b9e91
3,691
/* Copyright 2014 OPM.gov 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 gov.opm.scrd.entities.common; import static org.junit.Assert.assertEquals; import gov.opm.scrd.TestsHelper; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; /** * <p> * Unit tests for {@link BasePagedSearchParameters} class. * </p> * * @author sparemax * @version 1.0 */ public class BasePagedSearchParametersUnitTests { /** * <p> * Represents the <code>BasePagedSearchParameters</code> instance used in tests. * </p> */ private BasePagedSearchParameters instance; /** * <p> * Adapter for earlier versions of JUnit. * </p> * * @return a test suite. */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(BasePagedSearchParametersUnitTests.class); } /** * <p> * Sets up the unit tests. * </p> * * @throws Exception * to JUnit. */ @Before public void setUp() throws Exception { instance = new MockBasePagedSearchParameters(); } /** * <p> * Accuracy test for the constructor <code>BasePagedSearchParameters()</code>.<br> * Instance should be correctly created. * </p> */ @Test public void testCtor() { instance = new MockBasePagedSearchParameters(); assertEquals("'pageNumber' should be correct.", 0, TestsHelper.getField(instance, "pageNumber")); assertEquals("'pageSize' should be correct.", 0, TestsHelper.getField(instance, "pageSize")); } /** * <p> * Accuracy test for the method <code>getPageNumber()</code>.<br> * The value should be properly retrieved. * </p> */ @Test public void test_getPageNumber() { int value = 1; instance.setPageNumber(value); assertEquals("'getPageNumber' should be correct.", value, instance.getPageNumber()); } /** * <p> * Accuracy test for the method <code>setPageNumber(int pageNumber)</code>.<br> * The value should be properly set. * </p> */ @Test public void test_setPageNumber() { int value = 1; instance.setPageNumber(value); assertEquals("'setPageNumber' should be correct.", value, TestsHelper.getField(instance, "pageNumber")); } /** * <p> * Accuracy test for the method <code>getPageSize()</code>.<br> * The value should be properly retrieved. * </p> */ @Test public void test_getPageSize() { int value = 1; instance.setPageSize(value); assertEquals("'getPageSize' should be correct.", value, instance.getPageSize()); } /** * <p> * Accuracy test for the method <code>setPageSize(int pageSize)</code>.<br> * The value should be properly set. * </p> */ @Test public void test_setPageSize() { int value = 1; instance.setPageSize(value); assertEquals("'setPageSize' should be correct.", value, TestsHelper.getField(instance, "pageSize")); } }
26.177305
105
0.619615
f2df769d81d73fc21a7fa88f1c954a2699f7d002
2,160
package com.dao; import java.util.List; import java.util.Set; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.model.ItemDetailsDTO; import com.model.ItemTransactionDTO; @Repository public class ItemDAOImpl implements ItemDAO{ @Autowired private SessionFactory factory; @Override public List<ItemDetailsDTO> getAllItems(String category) { Session session=factory.getCurrentSession(); Criteria criteria=session.createCriteria(ItemDetailsDTO.class); criteria.add(Restrictions.eq("itemCategory", category)); List<ItemDetailsDTO> items=criteria.list(); return items; } public SessionFactory getFactory() { return factory; } public void setFactory(SessionFactory factory) { this.factory = factory; } @Override public void createItem(ItemDetailsDTO item) { Session session=factory.getCurrentSession(); session.persist(item); } @Override public ItemDetailsDTO getItemById(int id) { Session session = factory.getCurrentSession(); Criteria criteria = session.createCriteria(ItemDetailsDTO.class); criteria.add(Restrictions.idEq(id)); ItemDetailsDTO item=(ItemDetailsDTO)criteria.uniqueResult(); return item; } @Override public List<ItemDetailsDTO> getEveryItem() { Session session=factory.getCurrentSession(); List<ItemDetailsDTO> items = session.createQuery("from itemDetailsDTO").list(); return items; } @Override public void deleteitem(int uid) { Session session = factory.getCurrentSession(); Object persistentInstance = session.get(ItemDetailsDTO.class, uid); if (persistentInstance != null) { session.delete(persistentInstance); //return 1; } //return 0; } @Override public void updateitem(ItemDetailsDTO item) { Session session=factory.getCurrentSession(); session.saveOrUpdate(item); } }
24.269663
81
0.747222
e9e62b9bf3c11bc4ad1d55d12b2a2f355225ddf6
15,698
/** * BOSSWebServiceSoapImplServiceMessageReceiverInOut.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.3 Built on : Jun 27, 2015 (11:17:49 BST) */ package com.sysway.outwardtps.service.cfocn; /** * BOSSWebServiceSoapImplServiceMessageReceiverInOut message receiver */ public class BOSSWebServiceSoapImplServiceMessageReceiverInOut extends org.apache.axis2.receivers.AbstractInOutMessageReceiver { public void invokeBusinessLogic( org.apache.axis2.context.MessageContext msgContext, org.apache.axis2.context.MessageContext newMsgContext) throws org.apache.axis2.AxisFault { try { // get the implementation class for the Web Service Object obj = getTheImplementationObject(msgContext); BOSSWebServiceSoapImplServiceSkeletonInterface skel = (BOSSWebServiceSoapImplServiceSkeletonInterface) obj; //Out Envelop org.apache.axiom.soap.SOAPEnvelope envelope = null; //Find the axisOperation that has been set by the Dispatch phase. org.apache.axis2.description.AxisOperation op = msgContext.getOperationContext() .getAxisOperation(); if (op == null) { throw new org.apache.axis2.AxisFault( "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider"); } java.lang.String methodName; if ((op.getName() != null) && ((methodName = org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier( op.getName().getLocalPart())) != null)) { if ("replyManuallyInfluencedWorkOrder".equals(methodName)) { com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE replyManuallyInfluencedWorkOrderResponse7 = null; com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE wrappedParam = (com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE) fromOM(msgContext.getEnvelope() .getBody() .getFirstElement(), com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE.class, getEnvelopeNamespaces(msgContext.getEnvelope())); replyManuallyInfluencedWorkOrderResponse7 = skel.replyManuallyInfluencedWorkOrder(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), replyManuallyInfluencedWorkOrderResponse7, false, new javax.xml.namespace.QName( "http://cfocn.service.outwardtps.sysway.com/", "replyManuallyInfluencedWorkOrder")); } else if ("returnWorkOrder".equals(methodName)) { com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE returnWorkOrderResponse9 = null; com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE wrappedParam = (com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE) fromOM(msgContext.getEnvelope() .getBody() .getFirstElement(), com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE.class, getEnvelopeNamespaces(msgContext.getEnvelope())); returnWorkOrderResponse9 = skel.returnWorkOrder(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), returnWorkOrderResponse9, false, new javax.xml.namespace.QName( "http://cfocn.service.outwardtps.sysway.com/", "returnWorkOrder")); } else if ("deviceFeedBack".equals(methodName)) { com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE deviceFeedBackResponse11 = null; com.sysway.outwardtps.service.cfocn.DeviceFeedBackE wrappedParam = (com.sysway.outwardtps.service.cfocn.DeviceFeedBackE) fromOM(msgContext.getEnvelope() .getBody() .getFirstElement(), com.sysway.outwardtps.service.cfocn.DeviceFeedBackE.class, getEnvelopeNamespaces(msgContext.getEnvelope())); deviceFeedBackResponse11 = skel.deviceFeedBack(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deviceFeedBackResponse11, false, new javax.xml.namespace.QName( "http://cfocn.service.outwardtps.sysway.com/", "deviceFeedBack")); } else { throw new java.lang.RuntimeException("method not found"); } newMsgContext.setEnvelope(envelope); } } catch (java.lang.Exception e) { throw org.apache.axis2.AxisFault.makeFault(e); } } // private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.DeviceFeedBackE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.DeviceFeedBackE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.om.OMElement toOM( com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE param, boolean optimizeContent) throws org.apache.axis2.AxisFault { try { return param.getOMElement(com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory()); } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private org.apache.axiom.soap.SOAPEnvelope toEnvelope( org.apache.axiom.soap.SOAPFactory factory, com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE param, boolean optimizeContent, javax.xml.namespace.QName methodQName) throws org.apache.axis2.AxisFault { try { org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope(); emptyEnvelope.getBody() .addChild(param.getOMElement( com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE.MY_QNAME, factory)); return emptyEnvelope; } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE wrapreplyManuallyInfluencedWorkOrder() { com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE wrappedElement = new com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE(); return wrappedElement; } private org.apache.axiom.soap.SOAPEnvelope toEnvelope( org.apache.axiom.soap.SOAPFactory factory, com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE param, boolean optimizeContent, javax.xml.namespace.QName methodQName) throws org.apache.axis2.AxisFault { try { org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope(); emptyEnvelope.getBody() .addChild(param.getOMElement( com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE.MY_QNAME, factory)); return emptyEnvelope; } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE wrapreturnWorkOrder() { com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE wrappedElement = new com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE(); return wrappedElement; } private org.apache.axiom.soap.SOAPEnvelope toEnvelope( org.apache.axiom.soap.SOAPFactory factory, com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE param, boolean optimizeContent, javax.xml.namespace.QName methodQName) throws org.apache.axis2.AxisFault { try { org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope(); emptyEnvelope.getBody() .addChild(param.getOMElement( com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE.MY_QNAME, factory)); return emptyEnvelope; } catch (org.apache.axis2.databinding.ADBException e) { throw org.apache.axis2.AxisFault.makeFault(e); } } private com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE wrapdeviceFeedBack() { com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE wrappedElement = new com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE(); return wrappedElement; } /** * get the default envelope */ private org.apache.axiom.soap.SOAPEnvelope toEnvelope( org.apache.axiom.soap.SOAPFactory factory) { return factory.getDefaultEnvelope(); } private java.lang.Object fromOM(org.apache.axiom.om.OMElement param, java.lang.Class type, java.util.Map extraNamespaces) throws org.apache.axis2.AxisFault { try { if (com.sysway.outwardtps.service.cfocn.DeviceFeedBackE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.DeviceFeedBackE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } if (com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.DeviceFeedBackResponseE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } if (com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } if (com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.ReplyManuallyInfluencedWorkOrderResponseE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } if (com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.ReturnWorkOrderE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } if (com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE.class.equals( type)) { return com.sysway.outwardtps.service.cfocn.ReturnWorkOrderResponseE.Factory.parse(param.getXMLStreamReaderWithoutCaching()); } } catch (java.lang.Exception e) { throw org.apache.axis2.AxisFault.makeFault(e); } return null; } /** * A utility method that copies the namepaces from the SOAPEnvelope */ private java.util.Map getEnvelopeNamespaces( org.apache.axiom.soap.SOAPEnvelope env) { java.util.Map returnMap = new java.util.HashMap(); java.util.Iterator namespaceIterator = env.getAllDeclaredNamespaces(); while (namespaceIterator.hasNext()) { org.apache.axiom.om.OMNamespace ns = (org.apache.axiom.om.OMNamespace) namespaceIterator.next(); returnMap.put(ns.getPrefix(), ns.getNamespaceURI()); } return returnMap; } private org.apache.axis2.AxisFault createAxisFault(java.lang.Exception e) { org.apache.axis2.AxisFault f; Throwable cause = e.getCause(); if (cause != null) { f = new org.apache.axis2.AxisFault(e.getMessage(), cause); } else { f = new org.apache.axis2.AxisFault(e.getMessage()); } return f; } } //end of class
48.006116
157
0.619633
92020c994c20c66f7f2a88bcfd16122f3d388b1c
3,797
package com.candybar.dev.licenses; import candybar.lib.items.InAppBilling; public class License { /* * License Checker * private static final boolean ENABLE_LICENSE_CHECKER = true; --> enabled * Change to private static final boolean ENABLE_LICENSE_CHECKER = false; if you want to disable it * * NOTE: If you disable license checker you need to remove LICENSE_CHECK permission inside AndroidManifest.xml */ private static final boolean ENABLE_LICENSE_CHECKER = false; /* * NOTE: If license checker is disabled (above), just ignore this * * Generate 20 random bytes * For easy way, go to https://www.random.org/strings/ * Set generate 20 random strings * Each string should be 2 character long * Check numeric digit (0-9) * Choose each string should be unique * Get string */ private static final byte[] SALT = new byte[]{ //Put generated random bytes below, separate with comma, ex: 14, 23, 58, 85, ... }; /* * Your license key * If your app hasn't published at play store, publish it first as beta, get license key */ private static final String LICENSE_KEY = "YOUR LICENSE KEY"; /* * NOTE: Make sure your app name in project same as app name at play store listing * NOTE: Your InApp Purchase will works only after the apk published */ /* * NOTE: If premium request disabled, just ignored this * * InApp product id for premium request * Product name displayed the same as product name displayed at play store * So make sure to name it properly, like include number of icons * Format: new InAppBilling("premium request product id", number of icons) */ private static final InAppBilling[] PREMIUM_REQUEST_PRODUCTS = new InAppBilling[]{ new InAppBilling("your.product.id", 1), new InAppBilling("your.product.id", 2), new InAppBilling("your.product.id", 3), new InAppBilling("your.product.id", 4) }; /* * NOTE: If donation disabled, just ignored this * * InApp product id for donation * Product name displayed the same as product name displayed at play store * So make sure to name it properly * Format: new InAppBilling("donation product id") */ private static final InAppBilling[] DONATION_PRODUCT = new InAppBilling[]{ new InAppBilling("your.product.id"), new InAppBilling("your.product.id"), new InAppBilling("your.product.id"), new InAppBilling("your.product.id") }; public static boolean isLicenseCheckerEnabled() { return ENABLE_LICENSE_CHECKER; } public static String getLicenseKey() { return LICENSE_KEY; } public static byte[] getRandomString() { return SALT; } public static String[] getPremiumRequestProductsId() { String[] productId = new String[PREMIUM_REQUEST_PRODUCTS.length]; for (int i = 0; i < PREMIUM_REQUEST_PRODUCTS.length; i++) { productId[i] = PREMIUM_REQUEST_PRODUCTS[i].getProductId(); } return productId; } public static int[] getPremiumRequestProductsCount() { int[] productCount = new int[PREMIUM_REQUEST_PRODUCTS.length]; for (int i = 0; i < PREMIUM_REQUEST_PRODUCTS.length; i++) { productCount[i] = PREMIUM_REQUEST_PRODUCTS[i].getProductCount(); } return productCount; } public static String[] getDonationProductsId() { String[] productId = new String[DONATION_PRODUCT.length]; for (int i = 0; i < DONATION_PRODUCT.length; i++) { productId[i] = DONATION_PRODUCT[i].getProductId(); } return productId; } }
34.518182
114
0.647617
4cc82025988a202308abb6af97975c988d01fdc7
10,660
package slimeknights.tconstruct.gadgets.block; import com.google.common.collect.ImmutableList; import net.minecraft.block.BlockContainer; import net.minecraft.block.SoundType; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityHopper; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import slimeknights.tconstruct.gadgets.tileentity.TileWoodenHopper; import static net.minecraft.block.BlockHopper.FACING; @SuppressWarnings({"NullableProblems", "deprecation"}) public class BlockWoodenHopper extends BlockContainer { // Quitely stolen from RWTemas Diet Hoppers private static final EnumMap<EnumFacing, List<AxisAlignedBB>> bounds; static { List<AxisAlignedBB> commonBounds = ImmutableList.of( makeAABB(0, 10, 0, 16, 16, 16), makeAABB(4, 4, 4, 12, 10, 12) ); bounds = Stream.of(EnumFacing.values()) .filter(t -> t != EnumFacing.UP) .collect(Collectors.toMap(a -> a, a -> new ArrayList<>(commonBounds), (u, v) -> { throw new IllegalStateException(); }, () -> new EnumMap<>(EnumFacing.class))); bounds.get(EnumFacing.DOWN).add(makeAABB(6, 0, 6, 10, 4, 10)); bounds.get(EnumFacing.NORTH).add(makeAABB(6, 4, 0, 10, 8, 4)); bounds.get(EnumFacing.SOUTH).add(makeAABB(6, 4, 12, 10, 8, 16)); bounds.get(EnumFacing.WEST).add(makeAABB(0, 4, 6, 4, 8, 10)); bounds.get(EnumFacing.EAST).add(makeAABB(12, 4, 6, 16, 8, 10)); } public BlockWoodenHopper() { super(Material.WOOD, MapColor.STONE); this.setHardness(3.0F); this.setResistance(8.0F); this.setSoundType(SoundType.WOOD); this.setCreativeTab(CreativeTabs.REDSTONE); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.DOWN)); } private static AxisAlignedBB makeAABB(int fromX, int fromY, int fromZ, int toX, int toY, int toZ) { return new AxisAlignedBB(fromX / 16F, fromY / 16F, fromZ / 16F, toX / 16F, toY / 16F, toZ / 16F); } @SuppressWarnings("deprecation") @Override public RayTraceResult collisionRayTrace(IBlockState blockState, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d start, @Nonnull Vec3d end) { return bounds.get(blockState.getValue(FACING)).stream() .map(bb -> rayTrace(pos, start, end, bb)) .anyMatch(Objects::nonNull) ? super.collisionRayTrace(blockState, worldIn, pos, start, end) : null; } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileWoodenHopper(); } @Override public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { // no redstone } @Override public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { // no redstone } public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { EnumFacing enumfacing = facing.getOpposite(); if (enumfacing == EnumFacing.UP) { enumfacing = EnumFacing.DOWN; } return this.getDefaultState().withProperty(FACING, enumfacing); } public IBlockState getStateFromMeta(int meta) { EnumFacing facing = getFacing(meta); if(facing == EnumFacing.UP) { facing = EnumFacing.DOWN; } return this.getDefaultState().withProperty(FACING, facing); } public int getMetaFromState(IBlockState state) { int i = 0; i = i | state.getValue(FACING).getIndex(); return i; } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING); } // unchanged copied hopper code public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return FULL_BLOCK_AABB; } protected static final AxisAlignedBB BASE_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.625D, 1.0D); protected static final AxisAlignedBB SOUTH_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.125D); protected static final AxisAlignedBB NORTH_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.875D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB WEST_AABB = new AxisAlignedBB(0.875D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB EAST_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.125D, 1.0D, 1.0D); public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { addCollisionBoxToList(pos, entityBox, collidingBoxes, BASE_AABB); addCollisionBoxToList(pos, entityBox, collidingBoxes, EAST_AABB); addCollisionBoxToList(pos, entityBox, collidingBoxes, WEST_AABB); addCollisionBoxToList(pos, entityBox, collidingBoxes, SOUTH_AABB); addCollisionBoxToList(pos, entityBox, collidingBoxes, NORTH_AABB); } /** * Called by ItemBlocks after a block is set in the world, to allow post-place logic */ public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { super.onBlockPlacedBy(worldIn, pos, state, placer, stack); if (stack.hasDisplayName()) { TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntityHopper) { ((TileEntityHopper)tileentity).setCustomName(stack.getDisplayName()); } } } /** * Determines if the block is solid enough on the top side to support other blocks, like redstone components. */ public boolean isTopSolid(IBlockState state) { return true; } /** * Called when the block is right clicked by a player. */ public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (worldIn.isRemote) { return true; } else { TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntityHopper) { playerIn.displayGUIChest((TileEntityHopper)tileentity); playerIn.addStat(StatList.HOPPER_INSPECTED); } return true; } } /** * Called serverside after this block is replaced with another in Chunk, but before the Tile Entity is updated */ public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntityHopper) { InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityHopper)tileentity); worldIn.updateComparatorOutputLevel(pos, this); } super.breakBlock(worldIn, pos, state); } /** * The type of render function called. MODEL for mixed tesr and static model, MODELBLOCK_ANIMATED for TESR-only, * LIQUID for vanilla liquids, INVISIBLE to skip all rendering */ public EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.MODEL; } public boolean isFullCube(IBlockState state) { return false; } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ public boolean isOpaqueCube(IBlockState state) { return false; } public static EnumFacing getFacing(int meta) { return EnumFacing.getFront(meta & 7); } @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return true; } public boolean hasComparatorInputOverride(IBlockState state) { return true; } public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) { return Container.calcRedstone(worldIn.getTileEntity(pos)); } @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT_MIPPED; } /** * Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withRotation(IBlockState state, Rotation rot) { return state.withProperty(FACING, rot.rotate(state.getValue(FACING))); } /** * Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation(state.getValue(FACING))); } /** * Get the geometry of the queried face at the given position and state. This is used to decide whether things like * buttons are allowed to be placed on the face, or how glass panes connect to the face, among other things. * <p> * Common values are {@code SOLID}, which is the default, and {@code UNDEFINED}, which represents something that * does not fit the other descriptions and will generally cause other things not to connect to the face. * * @return an approximation of the form of the given face */ public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return face == EnumFacing.UP ? BlockFaceShape.BOWL : BlockFaceShape.UNDEFINED; } }
33.734177
192
0.72955
c5770f64684b06d854ce0c90f306e8a2620be4b0
2,316
package com.healthy.gym.trainings.component; import io.jsonwebtoken.SignatureAlgorithm; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.TestPropertySource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import static org.assertj.core.api.Assertions.assertThat; @Testcontainers @SpringBootTest @TestPropertySource( inheritProperties = false, properties = { "token.secret=testSecretToken", "token.expiration-time=360001", "authorization.token.header.name=Auth", "authorization.token.header.prefix=Bear" } ) @ActiveProfiles(value = "test") class TokenManagerTest { @Container static GenericContainer<?> rabbitMQContainer = new GenericContainer<>(DockerImageName.parse("gza73/agh-praca-inzynierska-rabbitmq")) .withExposedPorts(5672); @DynamicPropertySource static void setProperties(DynamicPropertyRegistry registry) { registry.add("spring.rabbitmq.port", rabbitMQContainer::getFirstMappedPort); } @Autowired private TokenManager tokenManager; @Test void shouldReturnProperSigningKey() { assertThat(tokenManager.getSigningKey()).isEqualTo("testSecretToken"); } @Test void shouldReturnProperTokenPrefix() { assertThat(tokenManager.getTokenPrefix()).isEqualTo("Bear"); } @Test void shouldReturnProperAuthorizationHeader() { assertThat(tokenManager.getHttpHeaderName()).isEqualTo("Auth"); } @Test void shouldReturnProperExpirationTime() { assertThat(tokenManager.getExpirationTimeInMillis()).isEqualTo(360001); } @Test void shouldReturnProperSignatureAlgorithm() { assertThat(tokenManager.getSignatureAlgorithm()).isEqualTo(SignatureAlgorithm.HS256); } }
33.565217
97
0.74266
957c1995163a784b9f426ed834141517b7572bb1
151
package org.frankframework.frankdoc.testtarget.examples.config.children2; public class Level2 extends Level1 { public void registerC(C child) { } }
21.571429
73
0.794702
c10a984ff8e83aa81ac479728e5bb33f7fabb82b
1,161
package com.ifsaid.shark.mapper; import com.ifsaid.shark.common.mapper.BaseMapper; import com.ifsaid.shark.entity.Relation; import com.ifsaid.shark.entity.SysUser; import java.util.List; import java.util.Set; /** * All rights Reserved, Designed By www.ifsaid.com * <p> * 用户 Mapper 接口 * </p> * * @author Wang Chen Chen <932560435@qq.com> * @version 2.0 * @date 2019/4/18 11:45 * @copyright 2019 http://www.ifsaid.com/ Inc. All rights reserved. */ public interface SysUserMapper extends BaseMapper<SysUser, Integer> { /** * 根据 用户名,和 昵称,模糊匹配 * * @param keywords * @return Set<SysRole> * @author Wang Chen Chen<932560435@qq.com> * @date 2019/12/14 0:04 */ Set<SysUser> selectByKeywords(String keywords); /** * 角色关联,多个角色 * * @param record * @return int * @author Wang Chen Chen<932560435@qq.com> * @date 2019/12/14 0:25 */ int insertByRoles(List<Relation> record); /** * 删除某个用户,拥有的角色 * * @param uid * @return int * @author Wang Chen Chen<932560435@qq.com> * @date 2019/12/14 0:25 */ int deleteHaveRoles(Integer uid); }
21.109091
69
0.625323
78e7c5ce0c013de57c8eb2455d2b9cbb359f746e
1,468
package com.philihp.weblabora.model.building; import static com.philihp.weblabora.model.TerrainTypeEnum.COAST; import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE; import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS; import java.util.EnumSet; import com.philihp.weblabora.model.Board; import com.philihp.weblabora.model.BuildCost; import com.philihp.weblabora.model.Player; import com.philihp.weblabora.model.SettlementRound; import com.philihp.weblabora.model.UsageParam; import com.philihp.weblabora.model.WeblaboraException; public class Alehouse extends Building { public Alehouse() { super("I20", SettlementRound.B, 3, "Alehouse", BuildCost.is().wood(1) .stone(1), 6, 3, EnumSet.of(COAST, PLAINS, HILLSIDE), false); } @Override public void use(Board board, UsageParam input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); int penniesToAdd = 0; if (input.getBeer() == 1) { player.subtractBeer(1); penniesToAdd += 8; } else if (input.getBeer() > 1) throw new WeblaboraException(getName() + " can only convert at most 1 beer, but was given " + input.getBeer()); if (input.getWhiskey() == 1) { player.subtractWhiskey(1); penniesToAdd += 7; } else if (input.getWhiskey() > 1) throw new WeblaboraException(getName() + " can only convert at most 1 whiskey, but was given " + input.getWhiskey()); player.addCoins(penniesToAdd); } }
31.234043
75
0.735695
2568dda3fd780c2ec8130126159b1fc39ed909ce
3,920
package edu.umass.ciir.proteus.athena.experiment; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class DateRerankerTest { private static ScoredDate mk(double score, int year) { return new ScoredDate(0, score, year); } private static List<ScoredDate> setRanks(ScoredDate... dates) { List<ScoredDate> data = new ArrayList<ScoredDate>(Arrays.asList(dates)); for (int i = 0; i < data.size(); i++) { data.get(i).rank = i+1; } return data; } public int[] getYears(List<ScoredDate> dates) { int years[] = new int[dates.size()]; for (int i = 0; i < dates.size(); i++) { years[i] = dates.get(i).year; } return years; } public String[] getScores(List<ScoredDate> dates) { String scores[] = new String[dates.size()]; for (int i = 0; i < dates.size(); i++) { scores[i] = String.format("%.2f",dates.get(i).score); } return scores; } private void checkRank(List<ScoredDate> results) { for(int i=0; i<results.size(); i++) { assertEquals(i+1, results.get(i).rank); } } @Test public void testUniform() throws Exception { final List<ScoredDate> dates = setRanks( mk(10.0, 1802), mk(10.0, 1802), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1801), mk(10.0, 1801), mk(10.0, 1801), mk(10.0, 1803), mk(10.0, 1803), mk(10.0, 1804), mk(10.0, 1804), mk(10.0, 1805) ); List<ScoredDate> uniform = DateReranker.process("uniform", dates); checkRank(uniform); assertArrayEquals(new int[]{1800, 1801, 1802, 1803, 1804, 1805}, getYears(uniform)); } @Test public void testTakeFirst() { final List<ScoredDate> dates = setRanks( mk(10.0, 1802), mk(10.0, 1802), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1801), mk(10.0, 1801), mk(10.0, 1801), mk(10.0, 1803), mk(10.0, 1803), mk(10.0, 1804), mk(10.0, 1804), mk(10.0, 1805) ); List<ScoredDate> res = DateReranker.process("takeFirst", dates); checkRank(res); assertArrayEquals(new int[] {1802,1800,1801,1803,1804,1805}, getYears(res)); } @Test public void testRecipRankWeight() throws Exception { final List<ScoredDate> dates = setRanks( mk(10.0, 1801), //1.0 mk(10.0, 1802), //0.5 mk(10.0, 1800), //0.33 mk(10.0, 1800), //0.25 mk(10.0, 1800), //0... mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800), mk(10.0, 1800) ); List<ScoredDate> results = DateReranker.process("recipRankWeight", dates); checkRank(results); assertArrayEquals(new String[] {"1.43","1.00","0.50"}, getScores(results)); assertArrayEquals(new int[] {1800,1801,1802}, getYears(results)); } @Test public void testNormalizedWeights() throws Exception { final List<ScoredDate> dates = setRanks( mk(-5.9, 1801), mk(-6.0, 1802), mk(-6.0, 1802), mk(-6.0, 1802), mk(-7.0, 1800) ); List<ScoredDate> results = DateReranker.process("rm", dates); checkRank(results); assertArrayEquals(new int[] {1802,1801,1800}, getYears(results)); } @Test public void testAllMethods() throws Exception { final List<ScoredDate> dates = setRanks( mk(2, 1801), mk(1, 1802) ); for(String method : DateReranker.Methods) { List<ScoredDate> results = DateReranker.process(method, dates); checkRank(results); assertArrayEquals(new int[]{1801, 1802}, getYears(results)); } try { DateReranker.process("bogus-method", dates); fail("bogus-method should have triggered an exception"); } catch(IllegalArgumentException iae) { assertNotNull(iae); } } }
26.666667
97
0.592602
f34759e55d36c0f5a8b4150167377e81ce443d16
1,951
package models.tarot; import org.junit.Test; import java.util.HashSet; import java.util.Stack; import static models.tarot.MajorArcanaCardTest.assertAllMajorArcanaCardsArePresent; import static models.tarot.MinorArcanaCardTest.assertAllMinorArcanaCardsArePresent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; public class TarotDeckTest { public static final int DEFAULT_DECK_SIZE = 78; @Test public void testNewTarotDeckHasCorrectNumberOfCards() { assertEquals(DEFAULT_DECK_SIZE, new TarotDeck().getPlayingCards().size()); } @Test public void testNewTarotDeckContainsAllTarotCards() { Stack<TarotCard> cardStack = new TarotDeck().getPlayingCards(); assertAllMinorArcanaCardsArePresent(cardStack); assertAllMajorArcanaCardsArePresent(cardStack); } @Test public void testNewTarotDeckContainsNoDuplicates() { Stack<TarotCard> playingCards = new TarotDeck().getPlayingCards(); assertEquals(playingCards.size(), new HashSet<>(playingCards).size()); } @Test public void testTarotDeckTracksStateWhenCardIsRemoved() { TarotDeck TarotDeck = new TarotDeck(); TarotDeck.getPlayingCards().pop(); assertEquals(DEFAULT_DECK_SIZE - 1, TarotDeck.getPlayingCards().size()); } @Test public void testTarotDeckEquality() { TarotDeck TarotDeck = new TarotDeck(); TarotDeck anotherTarotDeck = new TarotDeck(); assertEquals(TarotDeck, anotherTarotDeck); } @Test public void testTarotDeckShuffles() { int timesShuffledToSameState = 0; TarotDeck freshTarotDeck = new TarotDeck(); TarotDeck TarotDeckToShuffle = new TarotDeck(); for (int i = 0; i < 100000; i++) { TarotDeckToShuffle.shuffle(); if (freshTarotDeck.equals(TarotDeckToShuffle) && ++timesShuffledToSameState > 1) { fail(); } } assertNotEquals(freshTarotDeck, TarotDeckToShuffle); } }
30.484375
88
0.750384
9222a650e00968174a7f5865496ec43f3f645105
5,863
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xwine.end.mock.gson.internal.bind; import com.github.xwine.end.mock.gson.*; import com.github.xwine.end.mock.gson.internal.$Gson$Preconditions; import com.github.xwine.end.mock.gson.internal.Streams; import com.github.xwine.end.mock.gson.reflect.TypeToken; import com.github.xwine.end.mock.gson.stream.JsonReader; import com.github.xwine.end.mock.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; /** * Adapts a Gson 1.x tree-style adapter as a streaming TypeAdapter. Since the * tree adapter may be serialization-only or deserialization-only, this class * has a facility to lookup a delegate type adapter on demand. */ public final class TreeTypeAdapter<T> extends TypeAdapter<T> { private final JsonSerializer<T> serializer; private final JsonDeserializer<T> deserializer; final Gson gson; private final TypeToken<T> typeToken; private final TypeAdapterFactory skipPast; private final GsonContextImpl context = new GsonContextImpl(); /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter<T> delegate; public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer, Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) { this.serializer = serializer; this.deserializer = deserializer; this.gson = gson; this.typeToken = typeToken; this.skipPast = skipPast; } @Override public T read(JsonReader in) throws IOException { if (deserializer == null) { return delegate().read(in); } JsonElement value = Streams.parse(in); if (value.isJsonNull()) { return null; } return deserializer.deserialize(value, typeToken.getType(), context); } @Override public void write(JsonWriter out, T value) throws IOException { if (serializer == null) { delegate().write(out, value); return; } if (value == null) { out.nullValue(); return; } JsonElement tree = serializer.serialize(value, typeToken.getType(), context); Streams.write(tree, out); } private TypeAdapter<T> delegate() { TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(skipPast, typeToken)); } /** * Returns a new factory that will match each type against {@code exactType}. */ public static TypeAdapterFactory newFactory(TypeToken<?> exactType, Object typeAdapter) { return new SingleTypeFactory(typeAdapter, exactType, false, null); } /** * Returns a new factory that will match each type and its raw type against * {@code exactType}. */ public static TypeAdapterFactory newFactoryWithMatchRawType( TypeToken<?> exactType, Object typeAdapter) { // only bother matching raw types if exact type is a raw type boolean matchRawType = exactType.getType() == exactType.getRawType(); return new SingleTypeFactory(typeAdapter, exactType, matchRawType, null); } /** * Returns a new factory that will match each type's raw type for assignability * to {@code hierarchyType}. */ public static TypeAdapterFactory newTypeHierarchyFactory( Class<?> hierarchyType, Object typeAdapter) { return new SingleTypeFactory(typeAdapter, null, false, hierarchyType); } private static final class SingleTypeFactory implements TypeAdapterFactory { private final TypeToken<?> exactType; private final boolean matchRawType; private final Class<?> hierarchyType; private final JsonSerializer<?> serializer; private final JsonDeserializer<?> deserializer; SingleTypeFactory(Object typeAdapter, TypeToken<?> exactType, boolean matchRawType, Class<?> hierarchyType) { serializer = typeAdapter instanceof JsonSerializer ? (JsonSerializer<?>) typeAdapter : null; deserializer = typeAdapter instanceof JsonDeserializer ? (JsonDeserializer<?>) typeAdapter : null; $Gson$Preconditions.checkArgument(serializer != null || deserializer != null); this.exactType = exactType; this.matchRawType = matchRawType; this.hierarchyType = hierarchyType; } @SuppressWarnings("unchecked") // guarded by typeToken.equals() call @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { boolean matches = exactType != null ? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType() : hierarchyType.isAssignableFrom(type.getRawType()); return matches ? new TreeTypeAdapter<T>((JsonSerializer<T>) serializer, (JsonDeserializer<T>) deserializer, gson, type, this) : null; } } private final class GsonContextImpl implements JsonSerializationContext, JsonDeserializationContext { @Override public JsonElement serialize(Object src) { return gson.toJsonTree(src); } @Override public JsonElement serialize(Object src, Type typeOfSrc) { return gson.toJsonTree(src, typeOfSrc); } @SuppressWarnings("unchecked") @Override public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException { return (R) gson.fromJson(json, typeOfT); } }; }
36.874214
103
0.711069
b56468c77853ee0a293694abfc7fdebbd524ba79
1,867
package br.com.techHouse.zmed.to; import java.util.ArrayList; import java.util.Date; import java.util.List; public class FiltroTO<T> { private Integer inicio; private Integer tamanho; private Integer totalRegistros; private String ordenacao; private String campoOrdenacao; private Date dataInicio; private Date dataFim; private T objeto; private List<T> lista; private Class<T> tipoObjeto; public FiltroTO(Class<T> tipoObjeto) { this.tipoObjeto = tipoObjeto; } public Class<T> getTipoObjeto() { return tipoObjeto; } public Integer getInicio() { return inicio; } public void setInicio(Integer inicio) { this.inicio = inicio; } public Integer getTamanho() { return tamanho; } public void setTamanho(Integer tamanho) { this.tamanho = tamanho; } public String getOrdenacao() { return ordenacao; } public void setOrdenacao(String ordenacao) { this.ordenacao = ordenacao; } public String getCampoOrdenacao() { return campoOrdenacao; } public void setCampoOrdenacao(String campoOrdenacao) { this.campoOrdenacao = campoOrdenacao; } public T getObjeto() throws Exception { if (objeto == null) { objeto = tipoObjeto.newInstance(); } return objeto; } public void setObjeto(T t) { this.objeto = t; } public List<T> getLista() { if (lista == null) { lista = new ArrayList<>(); } return lista; } public void setLista(List<T> lista) { this.lista = lista; } public Integer getTotalRegistros() { return totalRegistros; } public void setTotalRegistros(Integer totalRegistros) { this.totalRegistros = totalRegistros; } public Date getDataFim() { return dataFim; } public void setDataFim(Date dataFim) { this.dataFim = dataFim; } public Date getDataInicio() { return dataInicio; } public void setDataInicio(Date dataInicio) { this.dataInicio = dataInicio; } }
17.613208
56
0.714515
282a9b70371e1fb8c84da60fc0bc4d11f81e1c73
1,235
package com.mojota.succulent.entity; import com.fasterxml.jackson.annotation.JsonInclude; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * App信息,升级用 * * @author jamie * @date 18-12-14 */ @Entity @Table(name = "app_info") @JsonInclude(JsonInclude.Include.NON_NULL) public class AppInfo { @Id Integer versionCode; @Column(nullable = false) String versionName; @Column String versionDesc; @Column String downloadUrl; public Integer getVersionCode() { return versionCode; } public void setVersionCode(Integer versionCode) { this.versionCode = versionCode; } public String getVersionName() { return versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } public String getVersionDesc() { return versionDesc; } public void setVersionDesc(String versionDesc) { this.versionDesc = versionDesc; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } }
18.712121
53
0.676113
2f405d1380bac74e9d8b2ae132c36edfa75add23
1,253
package com.yun.feign.client.service; import com.yun.bean.result.Result; import com.yun.feign.client.service.impl.FeignAuthInfoServiceImpl; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; /** * <p> * 服务类 * </p> * * @author wu_xufeng * @description 从ADMIN服务获取最新路由表信息 * @since 2020-11-06 */ @Component @FeignClient(name = "auth-server", fallback = FeignAuthInfoServiceImpl.class) public interface FeignAuthInfoService { @PostMapping(value = "/auth/permission") Result authClient(@RequestHeader(HttpHeaders.AUTHORIZATION) String authentication, @RequestParam("url") String url, @RequestParam("method") String method); @PostMapping(value = "/security/permission") Result authUser(@RequestHeader(HttpHeaders.AUTHORIZATION) String authentication, @RequestParam("url") String url, @RequestParam("method") String method); }
35.8
86
0.710295
1439ab48ecae2bc31a8d63dc052b95de07d46f16
647
package com.qijianguo.design.pattern.proxy.remote.v2.server; public class SoldOutState implements State { private transient StateMachine stateMachine; public SoldOutState(StateMachine stateMachine) { this.stateMachine = stateMachine; } @Override public void insertQuarter() { System.out.println("已售罄,无法投币!ERR"); } @Override public void ejectQuarter() { System.out.println("已售罄,无法退币"); } @Override public void turnCrank() { System.out.println("已售罄,无法摇动曲柄!ERR"); } @Override public void dispense() { System.out.println("已售罄,无法发放糖果!ERR"); } }
20.870968
60
0.646059
0896dcbece5b02328147be50b0ab338f7c421aef
1,480
/******************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2014,2015,2016 by Peter Pilgrim, Milton Keynes, P.E.A.T LTD * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU GPL v3.0 * which accompanies this distribution, and is available at: * http://www.gnu.org/licenses/gpl-3.0.txt * * Developers: * Peter Pilgrim -- design, development and implementation * -- Blog: http://www.xenonique.co.uk/blog/ * -- Twitter: @peter_pilgrim * * Contributors: * *******************************************************************************/ package org.mavenTest.mavenWebApp.exaCDI; import javax.ejb.Startup; import javax.ejb.Singleton; import java.util.Arrays; import java.util.List; /** * Created by ppilgrim on 20-Oct-2015. */ @Singleton @Startup public class MemoryDatabase { public List<LineItem> defaultLineItems() { return Arrays.asList( new LineItem( 1200L, "Iron Widget", 49.99F, 36), new LineItem( 4520L, "Power-core fitness bar", 19.99F, 3), new LineItem( 3720L, "Cereal bar breakfast", 3.99F, 12), new LineItem( 1300L, "Iron Bean", 99.99F, 66), new LineItem( 4020L, "Jim-power fitness bar", 29.99F, 53), new LineItem( 3750L, "Power-Bar breakfast", 13.99F, 22) ); } }
32.173913
81
0.579054
aa0dd03ead68e0156b992e409236762eb7a76961
2,496
package de.felixbruns.jotify.media; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import de.felixbruns.jotify.util.SpotifyChecksum; import de.felixbruns.jotify.util.XMLElement; public class PlaylistContainer implements Iterable<Playlist> { public static final PlaylistContainer EMPTY = new PlaylistContainer(); private String author; private List<Playlist> playlists; private long revision; private long checksum; public PlaylistContainer(){ this.author = null; this.playlists = new ArrayList<Playlist>(); this.revision = -1; this.checksum = -1; } public String getAuthor(){ return this.author; } public void setAuthor(String author){ this.author = author; } public List<Playlist> getPlaylists(){ return this.playlists; } public void setPlaylists(List<Playlist> playlists){ this.playlists = playlists; } public long getRevision(){ return this.revision; } public void setRevision(long revision){ this.revision = revision; } public long getChecksum(){ SpotifyChecksum checksum = new SpotifyChecksum(); for(Playlist playlist : this.playlists){ checksum.update(playlist); } this.checksum = checksum.getValue(); return this.checksum; } public void setChecksum(long checksum){ this.checksum = checksum; } public Iterator<Playlist> iterator(){ return this.playlists.iterator(); } public static PlaylistContainer fromXMLElement(XMLElement playlistsElement){ PlaylistContainer playlists = new PlaylistContainer(); /* Get "change" element. */ XMLElement changeElement = playlistsElement.getChild("next-change").getChild("change"); /* Get author. */ playlists.author = changeElement.getChildText("user").trim(); /* Get items (comma separated list). */ if(changeElement.getChild("ops").hasChild("add")){ String items = changeElement.getChild("ops").getChild("add").getChildText("items"); for(String id : items.split(",")){ playlists.playlists.add(new Playlist(id.trim().substring(0, 32), "", playlists.author, false)); } } /* Get "version" element. */ XMLElement versionElement = playlistsElement.getChild("next-change").getChild("version"); /* Split version string into parts. */ String[] parts = versionElement.getText().split(",", 4); /* Set values. */ playlists.revision = Long.parseLong(parts[0]); playlists.checksum = Long.parseLong(parts[2]); return playlists; } }
24.96
99
0.703926
cede0dcd2838e0aaad21348f1e94e94dd250f027
1,397
package com.kbhit.orangebox.trading.dbsetup.builders; import com.kbhit.orangebox.trading.domain.BidderId; import com.ninja_squad.dbsetup.operation.Operation; import java.util.TreeMap; import static com.kbhit.orangebox.trading.dbsetup.tables.BidderTable.*; import static com.ninja_squad.dbsetup.Operations.insertInto; public class BidderDummyBuilder { private TreeMap<String, Object> orderedValuesMap = new TreeMap<>(); public BidderDummyBuilder withId(String bidderId) { orderedValuesMap.put(BIDDER_ID.getColumnName(), bidderId); return this; } public BidderDummyBuilder withFirstName(String firstName) { orderedValuesMap.put(FIRST_NAME.getColumnName(), firstName); return this; } public BidderDummyBuilder withLastName(String lastName) { orderedValuesMap.put(LAST_NAME.getColumnName(), lastName); return this; } public BidderDummyBuilder withLogin(String login) { orderedValuesMap.put(LOGIN.getColumnName(), login); return this; } public Operation build() { return insertInto("BIDDERS") .columns(orderedValuesMap.keySet().stream().toArray(String[]::new)) .values(orderedValuesMap.values().stream().toArray(Object[]::new)).build(); } public static BidderDummyBuilder aDummyBidder() { return new BidderDummyBuilder(); } }
30.369565
91
0.707946
21ee0d088073eec6e012cf0a1e00a12575316017
5,382
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.bstek.urule.builder; import com.bstek.urule.exception.RuleException; import com.bstek.urule.model.decisiontree.ActionTreeNode; import com.bstek.urule.model.decisiontree.ConditionTreeNode; import com.bstek.urule.model.decisiontree.DecisionTree; import com.bstek.urule.model.decisiontree.TreeNode; import com.bstek.urule.model.decisiontree.VariableTreeNode; import com.bstek.urule.model.rule.Library; import com.bstek.urule.model.rule.Rhs; import com.bstek.urule.model.rule.Rule; import com.bstek.urule.model.rule.RuleSet; import com.bstek.urule.model.rule.lhs.And; import com.bstek.urule.model.rule.lhs.Criteria; import com.bstek.urule.model.rule.lhs.Lhs; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class DecisionTreeRulesBuilder { public DecisionTreeRulesBuilder() { } public RuleSet buildRules(DecisionTree var1, String var2) throws IOException { RuleSet var3 = new RuleSet(); List var4 = var1.getLibraries(); if (var4 != null) { Iterator var5 = var4.iterator(); while(var5.hasNext()) { Library var6 = (Library)var5.next(); var3.addLibrary(var6); } } ArrayList var15 = new ArrayList(); var15.add(var1.getVariableTreeNode()); ArrayList var16 = new ArrayList(); this.fetchActionTreeNodes(var15, var16); ArrayList var7 = new ArrayList(); Iterator var8 = var16.iterator(); while(var8.hasNext()) { ActionTreeNode var9 = (ActionTreeNode)var8.next(); Rule var10 = new Rule(); var10.setFile(var2); var10.setDebug(var1.getDebug()); var10.setEnabled(var1.getEnabled()); var10.setEffectiveDate(var1.getEffectiveDate()); var10.setExpiresDate(var1.getExpiresDate()); var10.setSalience(var1.getSalience()); var7.add(var10); var10.setName("tree-rule"); Rhs var11 = new Rhs(); var11.setActions(var9.getActions()); var10.setRhs(var11); Lhs var12 = new Lhs(); var10.setLhs(var12); And var13 = new And(); var12.setCriterion(var13); ConditionTreeNode var14 = (ConditionTreeNode)var9.getParentNode(); this.a(var13, var14); } var3.setRules(var7); return var3; } private void a(And var1, ConditionTreeNode var2) { if (var2 != null) { ArrayList var3 = new ArrayList(); var3.add(var2); VariableTreeNode var4 = null; TreeNode var5 = var2.getParentNode(); while(var5 != null) { if (var5 instanceof VariableTreeNode) { var4 = (VariableTreeNode)var5; this.a(var1, (ConditionTreeNode)var5.getParentNode()); break; } if (var5 instanceof ConditionTreeNode) { ConditionTreeNode var6 = (ConditionTreeNode)var5; var3.add(var6); var5 = var6.getParentNode(); } } if (var4 == null) { throw new RuleException("Decision tree is invalid."); } else { Iterator var8 = var3.iterator(); while(var8.hasNext()) { ConditionTreeNode var7 = (ConditionTreeNode)var8.next(); var1.addCriterion(this.a(var7, var4)); } } } } private Criteria a(ConditionTreeNode var1, VariableTreeNode var2) { Criteria var3 = new Criteria(); var3.setLeft(var2.getLeft()); var3.setOp(var1.getOp()); var3.setValue(var1.getValue()); return var3; } public void fetchActionTreeNodes(List<? extends TreeNode> var1, List<ActionTreeNode> var2) { Iterator var3 = var1.iterator(); while(var3.hasNext()) { TreeNode var4 = (TreeNode)var3.next(); if (var4 instanceof ActionTreeNode) { var2.add((ActionTreeNode)var4); } else { List var6; if (var4 instanceof VariableTreeNode) { VariableTreeNode var5 = (VariableTreeNode)var4; var6 = var5.getConditionTreeNodes(); if (var6 != null) { this.fetchActionTreeNodes(var6, var2); } } else if (var4 instanceof ConditionTreeNode) { ConditionTreeNode var9 = (ConditionTreeNode)var4; var6 = var9.getActionTreeNodes(); if (var6 != null) { this.fetchActionTreeNodes(var6, var2); } List var7 = var9.getConditionTreeNodes(); if (var7 != null) { this.fetchActionTreeNodes(var7, var2); } List var8 = var9.getVariableTreeNodes(); if (var8 != null) { this.fetchActionTreeNodes(var8, var2); } } } } } }
34.722581
96
0.55667
0f0babd6cdd58c8f3411b086da79477f2b3dea37
3,071
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.java.statement; import org.spongepowered.despector.ast.stmt.branch.TryCatch; import org.spongepowered.despector.ast.stmt.branch.TryCatch.CatchBlock; import org.spongepowered.despector.emitter.StatementEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; public class TryCatchEmitter implements StatementEmitter<JavaEmitterContext, TryCatch> { @Override public void emit(JavaEmitterContext ctx, TryCatch try_block, boolean semicolon) { ctx.printString("try {"); ctx.newLine(); ctx.indent(); ctx.emitBody(try_block.getTryBlock()); ctx.dedent(); ctx.newLine(); for (CatchBlock c : try_block.getCatchBlocks()) { ctx.printIndentation(); if (ctx.getFormat().insert_new_line_before_catch_in_try_statement) { ctx.printString("}"); ctx.newIndentedLine(); ctx.printString("catch ("); } else { ctx.printString("} catch ("); } for (int i = 0; i < c.getExceptions().size(); i++) { ctx.emitType(c.getExceptions().get(i)); if (i < c.getExceptions().size() - 1) { ctx.printString(" | "); } } ctx.printString(" "); if (c.getExceptionLocal() != null) { ctx.printString(c.getExceptionLocal().getName()); ctx.isDefined(c.getExceptionLocal()); } else { ctx.printString(c.getDummyName()); } ctx.printString(") {"); ctx.newLine(); ctx.indent(); ctx.emitBody(c.getBlock()); ctx.dedent(); ctx.newLine(); } ctx.printIndentation(); ctx.printString("}"); } }
40.407895
88
0.637252
1f3b438aeb9f06e8fb55d802cf12915c632e8106
641
package com.easynetcn.data.algorithms.practice.chapter01; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class DateTemperatureGroupingComparator extends WritableComparator { public DateTemperatureGroupingComparator() { super(DateTemperaturePair.class, true); } @Override public int compare(WritableComparable a, WritableComparable b) { DateTemperaturePair dateTemperaturePair1 = (DateTemperaturePair) a; DateTemperaturePair dateTemperaturePair2 = (DateTemperaturePair) b; return dateTemperaturePair1.getYearMonth().compareTo(dateTemperaturePair2.getYearMonth()); } }
32.05
92
0.829953
f70f026d9a484614109e5f1ba7847dfc1b620671
5,024
package edu.buaa.sei.datamodel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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 edu.buaa.sei.utils.StringHandle; public class Sender { private ArrayList<Message> messageList = new ArrayList<Message>(); public double getFIFOSendTime() { System.out.println("calaulating time from message list, which size is " + messageList.size()); double time = 0; for (int i = 0; i < messageList.size(); i++) { time += messageList.get(i).getTime(); } System.out.println("FIFO: time used " + time + "ms."); return time; } public ArrayList<Double> getTimeTableTime(int threads, int timeTableUnit) { ArrayList<Double> timeList = new ArrayList<Double>(); ArrayList<TimeTable> timeTableList = new ArrayList<TimeTable>(); int threads_t = threads; double neededTime = getFIFOSendTime(); for (int i = 0; i < threads; i++) { TimeTable timeTable = new TimeTable(); timeTable.setTimeUsed(0); timeTable.setNeededTime(neededTime); timeTableList.add(timeTable); } double timeNow = 0; double timePerProcess; while (threads_t > 0) { timePerProcess = (double)timeTableUnit/(double)threads_t;//ms for (int i = 0; i < timeTableList.size(); i++) { if (timeTableList.get(i).getNeededTime() <= 0) {//this process done. continue; } else if (timeTableList.get(i).getNeededTime() > timePerProcess) { timeTableList.get(i).setNeededTime(timeTableList.get(i).getNeededTime() - timePerProcess); timeNow += timePerProcess; } else { timeNow += timeTableList.get(i).getNeededTime(); timeTableList.get(i).setNeededTime(0); timeTableList.get(i).setTimeUsed(timeNow); threads_t--; } } }//while for (int i = 0; i < threads; i++) { timeList.add(timeTableList.get(i).getTimeUsed()); } return timeList; } public boolean containDumplicate(Message m) { for (int i = 0; i < messageList.size(); i++) { if (messageList.get(i).title.compareTo(m.title) == 0) return true; } return false; } private Message findTimeById(String id, NodeList list) { for (int temp = 0; temp < list.getLength(); temp++) { Node nNode = (Node) list.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String timeId = eElement.getAttribute("base_NamedElement"); if (timeId.equals(id)) { Message mes = new Message(); for (Node node = nNode.getFirstChild(); node != null; node = node .getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("execTime")) { String timeStr = node.getFirstChild() .getNodeValue(); String timeStr1 = StringHandle .delUnusedStr(timeStr); String[] str = timeStr1.split(","); if (str.length < 2) continue; mes.time = Double.valueOf(str[0]); return mes; } } } } } } return null; } public void getSender(String umlPath) throws ParserConfigurationException, SAXException, IOException { File fXmlFile = new File(umlPath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("message"); NodeList timeList = doc.getElementsByTagName("GQAM:GaStep"); // System.out.println("Sender message count : " + nList.getLength()); messageList.clear(); // scan xml and get all valid message. for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = (Node) nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String type = eElement.getAttribute("xmi:type"); if (type.equals("uml:Message")) { Message mes = new Message(); String nameStr = eElement.getAttribute("name"); String[] strList = nameStr.split(": "); if (strList.length < 2) continue; mes.title = strList[0]; mes.name = strList[1]; mes.id = eElement.getAttribute("xmi:id"); Message mes_t = findTimeById(mes.id, timeList); if (mes_t == null) continue; mes.time = mes_t.time; if (containDumplicate(mes)) continue; // System.out.println("title: " + mes.title + ", name: " // + mes.name + ", time: " + mes.time); messageList.add(mes); } } } // System.out.println("valid count : " + messageList.size()); } public ArrayList<Message> getMessageList() { return messageList; } public void setMessageList(ArrayList<Message> messageList) { this.messageList = messageList; } }
28.224719
95
0.659833
486dc4757c88d510c0f5c4f6c11711abca563016
171
package com.srp.carwash.ui.home; import com.srp.carwash.data.model.api.MatchesModel; public interface OnMatchesListener { void onMatch(MatchesModel matchesModel); }
21.375
51
0.795322
f4680d41d8b175869e314c359276005828a1c1ff
1,504
/* * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. */ package ch.sbb.perma.serializers; import com.google.common.collect.ImmutableCollection; /** * Serialize a immutable collection as value. Each item is serialized using the given item serializer. * * @author u206123 (Florian Seidl) * @since 1.0, 2017. */ public abstract class ImmutableCollectionSerializer<C extends ImmutableCollection<T>, T> implements KeyOrValueSerializer<C> { private final KeyOrValueSerializer<T> itemSerializer; public ImmutableCollectionSerializer(KeyOrValueSerializer<T> itemSerializier) { this.itemSerializer = itemSerializier; } @Override public byte[] toByteArray(C collection) { CompoundBinaryWriter writer = new CompoundBinaryWriter(); writer.writeInt(collection.size()); for (T item : collection) { writer.writeWithLength(itemSerializer.toByteArray(item)); } return writer.toByteArray(); } @SuppressWarnings("unchecked") public C fromByteArray(byte[] bytes) { CompoundBinaryReader reader = new CompoundBinaryReader(bytes); int collectionSize = reader.readInt(); ImmutableCollection.Builder<T> builder = collectionBuilder(); for (int i = 0; i < collectionSize; i++) { builder.add(itemSerializer.fromByteArray(reader.readWithLength())); } return (C) builder.build(); } protected abstract ImmutableCollection.Builder<T> collectionBuilder(); }
33.422222
125
0.700798
db24e2a39ad64d72166f6b7f0a098f5dea2c3402
1,798
package de.jofre.visual.support; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; public class UrlHelper { private static Logger logger = Logger.getLogger(UrlHelper.class.getName()); // Get the absolute URL of the FacesContext public static String getAbsoluteApplicationUrl(FacesContext context) { ExternalContext extContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) extContext .getRequest(); URL url = null; URL newUrl = null; try { url = new URL(request.getRequestURL().toString()); newUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), request.getContextPath()); } catch (MalformedURLException e) { e.printStackTrace(); } logger.log(Level.INFO, "URL for JSF context is: " + newUrl.toString()); return newUrl.toString(); } // Get content of a webpage public static String urlRequest(String url) { StringBuilder result = new StringBuilder(); logger.log(Level.INFO, "HTTP request to: "+url); URL newUrl = null; try { newUrl = new URL(url); URLConnection yc = newUrl.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result.toString(); } }
27.661538
76
0.727475
2970cf75a2b6204309714b6b93637a9f31eb87c7
8,993
/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.IllegalFieldValueException; import org.joda.time.field.SkipDateTimeField; /** * Implements a pure proleptic Julian calendar system, which defines every * fourth year as leap. This implementation follows the leap year rule * strictly, even for dates before 8 CE, where leap years were actually * irregular. In the Julian calendar, year zero does not exist: 1 BCE is * followed by 1 CE. * <p> * Although the Julian calendar did not exist before 45 BCE, this chronology * assumes it did, thus it is proleptic. This implementation also fixes the * start of the year at January 1. * <p> * JulianChronology is thread-safe and immutable. * * @see <a href="http://en.wikipedia.org/wiki/Julian_calendar">Wikipedia</a> * @see GregorianChronology * @see GJChronology * * @author Guy Allard * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class JulianChronology extends BasicGJChronology { /** Serialization lock */ private static final long serialVersionUID = -8731039522547897247L; private static final long MILLIS_PER_YEAR = (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY); private static final long MILLIS_PER_MONTH = (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY / 12); /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292269054; /** The highest year that can be fully supported. */ private static final int MAX_YEAR = 292272992; /** Singleton instance of a UTC JulianChronology */ private static final JulianChronology INSTANCE_UTC; /** Cache of zone to chronology arrays */ private static final Map<DateTimeZone, JulianChronology[]> cCache = new HashMap<DateTimeZone, JulianChronology[]>(); static { INSTANCE_UTC = getInstance(DateTimeZone.UTC); } static int adjustYearForSet(int year) { if (year <= 0) { if (year == 0) { throw new IllegalFieldValueException (DateTimeFieldType.year(), new Integer(year), null, null); } year++; } return year; } /** * Gets an instance of the JulianChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static JulianChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the JulianChronology in the default time zone. * * @return a chronology in the default time zone */ public static JulianChronology getInstance() { return getInstance(DateTimeZone.getDefault(), 4); } /** * Gets an instance of the JulianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static JulianChronology getInstance(DateTimeZone zone) { return getInstance(zone, 4); } /** * Gets an instance of the JulianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 * @return a chronology in the specified time zone */ public static JulianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } JulianChronology chrono; synchronized (cCache) { JulianChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new JulianChronology[7]; cCache.put(zone, chronos); } try { chrono = chronos[minDaysInFirstWeek - 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } if (chrono == null) { if (zone == DateTimeZone.UTC) { chrono = new JulianChronology(null, null, minDaysInFirstWeek); } else { chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); chrono = new JulianChronology (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); } chronos[minDaysInFirstWeek - 1] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor */ JulianChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } /** * Serialization singleton */ private Object readResolve() { Chronology base = getBase(); int minDays = getMinimumDaysInFirstWeek(); minDays = (minDays == 0 ? 4 : minDays); // handle rename of BaseGJChronology return base == null ? getInstance(DateTimeZone.UTC, minDays) : getInstance(base.getZone(), minDays); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) throws IllegalArgumentException { return super.getDateMidnightMillis(adjustYearForSet(year), monthOfYear, dayOfMonth); } boolean isLeapYear(int year) { return (year & 3) == 0; } long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1969-12-19 Julian. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1968; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1968 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1968-01-01 and 1969-12-19. return millis - (366L + 352) * DateTimeConstants.MILLIS_PER_DAY; } int getMinYear() { return MIN_YEAR; } int getMaxYear() { return MAX_YEAR; } long getAverageMillisPerYear() { return MILLIS_PER_YEAR; } long getAverageMillisPerYearDividedByTwo() { return MILLIS_PER_YEAR / 2; } long getAverageMillisPerMonth() { return MILLIS_PER_MONTH; } long getApproxMillisAtEpochDividedByTwo() { return (1969L * MILLIS_PER_YEAR + 352L * DateTimeConstants.MILLIS_PER_DAY) / 2; } protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); // Julian chronology has no year zero. fields.year = new SkipDateTimeField(this, fields.year); fields.weekyear = new SkipDateTimeField(this, fields.weekyear); } } }
32.821168
120
0.61748
04e751baad88f41aaf56d7bbb53ae7f589a12bbc
397
package org.ms2ms.runner; import org.expasy.mzjava.core.ms.Tolerance; /** * Created with IntelliJ IDEA. * User: wyu * Date: 7/23/14 * Time: 9:33 PM * To change this template use File | Settings | File Templates. */ public class LcMsAligner extends Aligner { public LcMsAligner(String[] cols, Tolerance[] tols) { super(tols, cols); } public void run() { } }
18.045455
77
0.642317
ea99267f9b0f1da0ca20c8835b72242b2209e526
177
package com.zou.designPattern.create.abstractFactory; import com.zou.designPattern.entity.Fruit; public interface AbstractFactory { Fruit getFruit(); Bag getBag(); }
17.7
53
0.762712
402f6611b60eb4eeb0bf363ab00935d49a3bc005
1,080
package com.project.communication.capitalization; import com.project.communication.common.LoggerFactoryV2; import com.project.communication.common.LoggerV2; import com.project.communication.obj.ProtocolConfig; import java.net.ServerSocket; import java.net.Socket; public class SingleThreadedCapitalizationServer { private final static LoggerV2 logger = LoggerFactoryV2.getLogger(SingleThreadedCapitalizationServer.class); public static void main(ProtocolConfig protocolConfig) { int port = protocolConfig.getClientPort(); int clientId = 0; try { clientId++; ServerSocket serverSocket = new ServerSocket(port); logger.info("Server is listening on port: "+port); Socket socket = serverSocket.accept(); logger.info(clientId + ": New client connected"); new ServerProgram(protocolConfig, clientId, socket).start(); } catch (Exception ex) { logger.info(clientId + ": Server exception: " + ex.getMessage()); ex.printStackTrace(); } } }
40
111
0.689815
c62f3c82bc365fb9db8481a2d201c21fd2c0cff3
7,024
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.media.router.cast; import android.net.Uri; import android.support.v7.media.MediaRouteSelector; import com.google.android.gms.cast.CastMediaControlIntent; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * Abstracts parsing the Cast application id and other parameters from the source URN. */ public class MediaSource { public static final String AUTOJOIN_CUSTOM_CONTROLLER_SCOPED = "custom_controller_scoped"; public static final String AUTOJOIN_TAB_AND_ORIGIN_SCOPED = "tab_and_origin_scoped"; public static final String AUTOJOIN_ORIGIN_SCOPED = "origin_scoped"; public static final String AUTOJOIN_PAGE_SCOPED = "page_scoped"; private static final String CAST_SOURCE_ID_SEPARATOR = "/"; private static final String CAST_SOURCE_ID_APPLICATION_ID = "__castAppId__"; private static final String CAST_SOURCE_ID_CLIENT_ID = "__castClientId__"; private static final String CAST_SOURCE_ID_AUTOJOIN_POLICY = "__castAutoJoinPolicy__"; private static final String CAST_APP_CAPABILITIES_PREFIX = "("; private static final String CAST_APP_CAPABILITIES_SUFFIX = ")"; private static final String CAST_APP_CAPABILITIES_SEPARATOR = ","; private static final String CAST_APP_CAPABILITIES[] = { "video_out", "audio_out", "video_in", "audio_in", "multizone_group" }; /** * The original presentation URL that the {@link MediaSource} object was created from. */ private final String mSourceId; /** * The Cast application id, can be invalid in which case {@link CastMediaRouteProvider} * will explicitly report no sinks available. */ private final String mApplicationId; /** * A numeric identifier for the Cast Web SDK, unique for the frame providing the * presentation URL. Can be null. */ private final String mClientId; /** * Defines Cast-specific behavior for {@link CastMediaRouteProvider#joinRoute}. Defaults to * {@link MediaSource#AUTOJOIN_TAB_AND_ORIGIN_SCOPED}. */ private final String mAutoJoinPolicy; /** * Defines the capabilities of the particular application id. Can be null. */ private final String[] mCapabilities; /** * Initializes the media source from the source id. * @param sourceId the source id for the Cast media source (a presentation url). * @return an initialized media source if the id is valid, null otherwise. */ @Nullable public static MediaSource from(String sourceId) { assert sourceId != null; Uri sourceUri = Uri.parse(sourceId); String uriFragment = sourceUri.getFragment(); if (uriFragment == null) return null; String[] parameters = uriFragment.split(CAST_SOURCE_ID_SEPARATOR); String applicationId = extractParameter(parameters, CAST_SOURCE_ID_APPLICATION_ID); if (applicationId == null) return null; String[] capabilities = null; int capabilitiesIndex = applicationId.indexOf(CAST_APP_CAPABILITIES_PREFIX); if (capabilitiesIndex != -1) { capabilities = extractCapabilities(applicationId.substring(capabilitiesIndex)); if (capabilities == null) return null; applicationId = applicationId.substring(0, capabilitiesIndex); } String clientId = extractParameter(parameters, CAST_SOURCE_ID_CLIENT_ID); String autoJoinPolicy = extractParameter(parameters, CAST_SOURCE_ID_AUTOJOIN_POLICY); return new MediaSource(sourceId, applicationId, clientId, autoJoinPolicy, capabilities); } /** * Returns a new {@link MediaRouteSelector} to use for Cast device filtering for this * particular media source or null if the application id is invalid. * * @return an initialized route selector or null. */ public MediaRouteSelector buildRouteSelector() { try { return new MediaRouteSelector.Builder() .addControlCategory(CastMediaControlIntent.categoryForCast(mApplicationId)) .build(); } catch (IllegalArgumentException e) { return null; } } /** * @return the Cast application id corresponding to the source. */ public String getApplicationId() { return mApplicationId; } /** * @return the client id if passed in the source id. Can be null. */ @Nullable public String getClientId() { return mClientId; } /** * @return the auto join policy which must be one of the AUTOJOIN constants defined above. */ public String getAutoJoinPolicy() { return mAutoJoinPolicy; } /** * @return the id identifying the media source */ public String getUrn() { return mSourceId; } /** * @return application capabilities */ public String[] getCapabilities() { return mCapabilities == null ? null : Arrays.copyOf(mCapabilities, mCapabilities.length); } private MediaSource( String sourceId, String applicationId, String clientId, String autoJoinPolicy, String[] capabilities) { mSourceId = sourceId; mApplicationId = applicationId; mClientId = clientId; mAutoJoinPolicy = autoJoinPolicy == null ? AUTOJOIN_TAB_AND_ORIGIN_SCOPED : autoJoinPolicy; mCapabilities = capabilities; } @Nullable private static String extractParameter(String[] fragments, String key) { String keyPrefix = key + "="; for (String parameter : fragments) { if (parameter.startsWith(keyPrefix)) return parameter.substring(keyPrefix.length()); } return null; } @Nullable private static String[] extractCapabilities(String capabilitiesParameter) { if (capabilitiesParameter.length() < CAST_APP_CAPABILITIES_PREFIX.length() + CAST_APP_CAPABILITIES_SUFFIX.length()) { return null; } if (!capabilitiesParameter.startsWith(CAST_APP_CAPABILITIES_PREFIX) || !capabilitiesParameter.endsWith(CAST_APP_CAPABILITIES_SUFFIX)) { return null; } List<String> supportedCapabilities = Arrays.asList(CAST_APP_CAPABILITIES); String capabilitiesList = capabilitiesParameter.substring( CAST_APP_CAPABILITIES_PREFIX.length(), capabilitiesParameter.length() - CAST_APP_CAPABILITIES_SUFFIX.length()); String[] capabilities = capabilitiesList.split(CAST_APP_CAPABILITIES_SEPARATOR); for (String capability : capabilities) { if (!supportedCapabilities.contains(capability)) return null; } return capabilities; } }
34.945274
99
0.678388
8cc7c844e7f11bae5254921f3c1c42597fa4ffa4
1,040
package com.test.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * 测试捕获线程池异常 */ public class ThreadExceptionTest { public static void main(String[] args) throws InterruptedException { Thread.setDefaultUncaughtExceptionHandler((t, e) -> { System.out.println("--------------------"); System.out.println(t.getName()); e.printStackTrace(); }); ThreadFactory threadFactory = new ThreadFactoryBuilder().setUncaughtExceptionHandler((t, e) -> { System.out.println("===================="); e.printStackTrace(); }).build(); ExecutorService executorService = Executors.newFixedThreadPool(2, threadFactory); executorService.execute(() -> { throw new RuntimeException("for test"); }); Thread.sleep(2000); executorService.shutdown(); } }
28.888889
104
0.628846
a0662cc3147baf47639dc6834ebc84f220eeb597
32,993
package org.irods.jargon.rest.commands.user; import java.net.URLEncoder; import java.util.Properties; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.irods.jargon.core.connection.IRODSAccount; import org.irods.jargon.core.protovalues.UserTypeEnum; import org.irods.jargon.core.pub.IRODSAccessObjectFactory; import org.irods.jargon.core.pub.IRODSFileSystem; import org.irods.jargon.core.pub.UserAO; import org.irods.jargon.core.pub.UserGroupAO; import org.irods.jargon.core.pub.domain.User; import org.irods.jargon.core.pub.domain.UserGroup; import org.irods.jargon.rest.auth.DefaultHttpClientAndContext; import org.irods.jargon.rest.auth.RestAuthUtils; import org.irods.jargon.rest.commands.GenericCommandResponse; import org.irods.jargon.rest.commands.user.UserGroupCommandResponse.UserGroupCommandStatus; import org.irods.jargon.rest.utils.RestTestingProperties; import org.irods.jargon.testutils.TestingPropertiesHelper; import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; import org.jboss.resteasy.plugins.spring.SpringBeanProcessor; import org.jboss.resteasy.plugins.spring.SpringResourceFactory; import org.jboss.resteasy.spi.ResteasyDeployment; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:jargon-beans.xml", "classpath:rest-servlet.xml" }) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) public class UserGroupServiceTest implements ApplicationContextAware { private static TJWSEmbeddedJaxrsServer server; private static ApplicationContext applicationContext; private static Properties testingProperties = new Properties(); private static TestingPropertiesHelper testingPropertiesHelper = new TestingPropertiesHelper(); private static IRODSFileSystem irodsFileSystem; @BeforeClass public static void setUpBeforeClass() throws Exception { TestingPropertiesHelper testingPropertiesLoader = new TestingPropertiesHelper(); testingProperties = testingPropertiesLoader.getTestProperties(); irodsFileSystem = IRODSFileSystem.instance(); } @AfterClass public static void tearDownAfterClass() throws Exception { if (server != null) { server.stop(); } irodsFileSystem.closeAndEatExceptions(); } @Before public void setUp() throws Exception { if (server != null) { return; } int port = testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY); server = new TJWSEmbeddedJaxrsServer(); server.setPort(port); ResteasyDeployment deployment = server.getDeployment(); server.start(); Dispatcher dispatcher = deployment.getDispatcher(); SpringBeanProcessor processor = new SpringBeanProcessor(dispatcher, deployment.getRegistry(), deployment.getProviderFactory()); ((ConfigurableApplicationContext) applicationContext) .addBeanFactoryPostProcessor(processor); SpringResourceFactory noDefaults = new SpringResourceFactory( "userGroupService", applicationContext, UserGroupService.class); dispatcher.getRegistry().addResourceFactory(noDefaults); } @After public void tearDown() throws Exception { } @Test public void testAddUserToGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/user"); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupMembershipRequest userAddToGroupRequest = new UserGroupMembershipRequest(); userAddToGroupRequest.setUserGroup(testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY)); userAddToGroupRequest.setZone(irodsAccount.getZone()); userAddToGroupRequest .setUserName(testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY)); String body = mapper.writeValueAsString(userAddToGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testAddUserToGroupDuplicateUser() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/user"); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); userGroupAO.addUserToGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupMembershipRequest userAddToGroupRequest = new UserGroupMembershipRequest(); userAddToGroupRequest.setUserGroup(testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY)); userAddToGroupRequest.setZone(irodsAccount.getZone()); userAddToGroupRequest .setUserName(testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY)); String body = mapper.writeValueAsString(userAddToGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.ERROR, actual.getStatus()); Assert.assertEquals( UserGroupCommandResponse.UserGroupCommandStatus.DUPLICATE_USER, actual.getUserGroupCommandStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testAddUserToGroupBogusUser() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/user"); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupMembershipRequest userAddToGroupRequest = new UserGroupMembershipRequest(); userAddToGroupRequest.setUserGroup(testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY)); userAddToGroupRequest.setZone(irodsAccount.getZone()); userAddToGroupRequest.setUserName("bogususer"); String body = mapper.writeValueAsString(userAddToGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.ERROR, actual.getStatus()); Assert.assertEquals( UserGroupCommandResponse.UserGroupCommandStatus.INVALID_USER, actual.getUserGroupCommandStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testAddUserToGroupBogusGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/user"); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupMembershipRequest userAddToGroupRequest = new UserGroupMembershipRequest(); userAddToGroupRequest.setUserGroup("bogusGroup"); userAddToGroupRequest.setZone(irodsAccount.getZone()); userAddToGroupRequest .setUserName(testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY)); String body = mapper.writeValueAsString(userAddToGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.ERROR, actual.getStatus()); Assert.assertEquals( UserGroupCommandResponse.UserGroupCommandStatus.INVALID_GROUP, actual.getUserGroupCommandStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserFromGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); userGroupAO.addUserToGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); String userGroup = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); irodsAccount.getZone(); String userName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(userGroup); sb.append("/user/"); sb.append(userName); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserFromGroupNotInGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); userGroupAO.removeUserFromGroup(userGroupName, testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY), irodsAccount.getZone()); String userGroup = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); irodsAccount.getZone(); String userName = testingProperties .getProperty(TestingPropertiesHelper.IRODS_SECONDARY_USER_KEY); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(userGroup); sb.append("/user/"); sb.append(userName); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserFromGroupNotInGroupAndNotExists() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); String userGroup = testingProperties .getProperty(TestingPropertiesHelper.IRODS_USER_GROUP_KEY); irodsAccount.getZone(); String userName = "iambogus"; StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(userGroup); sb.append("/user/"); sb.append(userName); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.ERROR, actual.getStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserFromGroupHyphenated() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String testUserGroupName = "geni-ahtest2"; String testUserName = "geni-ahelsing"; UserGroup userGroup = new UserGroup(); userGroup.setUserGroupName(testUserGroupName); userGroup.setZone(irodsAccount.getZone()); userGroupAO.removeUserGroup(testUserGroupName); userGroupAO.addUserGroup(userGroup); User testUser = new User(); testUser.setName(testUserName); testUser.setUserType(UserTypeEnum.RODS_USER); UserAO userAO = irodsFileSystem.getIRODSAccessObjectFactory() .getUserAO(irodsAccount); userAO.deleteUser(testUserName); userAO.addUser(testUser); userGroupAO.removeUserFromGroup(testUserGroupName, testUserName, irodsAccount.getZone()); userGroupAO.addUserToGroup(testUserGroupName, testUserName, irodsAccount.getZone()); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(URLEncoder.encode(testUserGroupName, userAO .getJargonProperties().getEncoding())); sb.append("/user/"); sb.append(URLEncoder.encode(testUserName, userAO.getJargonProperties() .getEncoding())); System.out.println("request url:" + sb.toString()); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); // httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testAddUserGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group"); String testUserGroup = "testAddUserGroup"; DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); userGroupAO.removeUserGroup(testUserGroup); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupRequest userGroupRequest = new UserGroupRequest(); userGroupRequest.setUserGroupName(testUserGroup); userGroupRequest.setZone(irodsAccount.getZone()); String body = mapper.writeValueAsString(userGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); userGroupAO.removeUserGroup(testUserGroup); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testAddDuplicateUserGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group"); String testUserGroup = "testAddUserGroup"; DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); userGroupAO.removeUserGroup(testUserGroup); UserGroup userGroup = new UserGroup(); userGroup.setUserGroupName(testUserGroup); userGroup.setZone(irodsAccount.getZone()); userGroupAO.addUserGroup(userGroup); try { HttpPut httpPut = new HttpPut(sb.toString()); httpPut.addHeader("accept", "application/json"); httpPut.addHeader("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); UserGroupRequest userGroupRequest = new UserGroupRequest(); userGroupRequest.setUserGroupName(testUserGroup); userGroupRequest.setZone(irodsAccount.getZone()); String body = mapper.writeValueAsString(userGroupRequest); System.out.println(body); httpPut.setEntity(new StringEntity(body)); HttpResponse response = clientAndContext.getHttpClient().execute( httpPut, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); String entityData = EntityUtils.toString(entity); System.out.println(entityData); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.ERROR, actual.getStatus()); Assert.assertEquals(UserGroupCommandStatus.DUPLICATE_GROUP, actual.getUserGroupCommandStatus()); userGroupAO.removeUserGroup(testUserGroup); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserGroup() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = "testRemoveUserGroup"; UserGroup userGroup = new UserGroup(); userGroup.setUserGroupName(userGroupName); userGroup.setZone(irodsAccount.getZone()); userGroupAO.removeUserGroup(userGroupName); userGroupAO.addUserGroup(userGroup); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(userGroupName); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); UserGroup actualUserGroup = userGroupAO.findByName(userGroupName); Assert.assertNull("did not remove user group", actualUserGroup); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Test public void testRemoveUserGroupNotExists() throws Exception { IRODSAccount irodsAccount = testingPropertiesHelper .buildIRODSAccountFromTestProperties(testingProperties); IRODSAccessObjectFactory accessObjectFactory = irodsFileSystem .getIRODSAccessObjectFactory(); DefaultHttpClientAndContext clientAndContext = RestAuthUtils .httpClientSetup(irodsAccount, testingProperties); UserGroupAO userGroupAO = accessObjectFactory .getUserGroupAO(irodsAccount); String userGroupName = "testRemoveUserGroupNotExists"; UserGroup userGroup = new UserGroup(); userGroup.setUserGroupName(userGroupName); userGroup.setZone(irodsAccount.getZone()); StringBuilder sb = new StringBuilder(); sb.append("http://localhost:"); sb.append(testingPropertiesHelper.getPropertyValueAsInt( testingProperties, RestTestingProperties.REST_PORT_PROPERTY)); sb.append("/user_group/"); sb.append(userGroupName); try { HttpDelete httpDelete = new HttpDelete(sb.toString()); httpDelete.addHeader("accept", "application/json"); httpDelete.addHeader("Content-Type", "application/json"); HttpResponse response = clientAndContext.getHttpClient().execute( httpDelete, clientAndContext.getHttpContext()); HttpEntity entity = response.getEntity(); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String entityData = EntityUtils.toString(entity); System.out.println(entityData); ObjectMapper mapper = new ObjectMapper(); UserGroupCommandResponse actual = mapper.readValue(entityData, UserGroupCommandResponse.class); Assert.assertEquals(GenericCommandResponse.Status.OK, actual.getStatus()); UserGroup actualUserGroup = userGroupAO.findByName(userGroupName); Assert.assertNull("did not remove user group", actualUserGroup); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources clientAndContext.getHttpClient().getConnectionManager().shutdown(); } } @Override public void setApplicationContext(final ApplicationContext context) throws BeansException { applicationContext = context; } }
35.476344
96
0.786894
8ca5101e4f10bfd0929ac006a175f3d12f354657
11,809
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.window; import io.crate.data.Input; import io.crate.data.Row; import io.crate.data.RowN; import io.crate.execution.engine.collect.CollectExpression; import io.crate.execution.engine.window.WindowFrameState; import io.crate.execution.engine.window.WindowFunction; import io.crate.metadata.functions.Signature; import io.crate.module.ExtraFunctionsModule; import io.crate.types.DataTypes; import javax.annotation.Nullable; import java.util.List; import static io.crate.execution.engine.window.WindowFrameState.isLowerBoundIncreasing; import static io.crate.metadata.functions.TypeVariableConstraint.typeVariable; import static io.crate.types.TypeSignature.parseTypeSignature; public class NthValueFunctions implements WindowFunction { private enum Implementation { FIRST_VALUE { @Override public Object execute(int adjustForShrinkingWindow, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, boolean ignoreNulls, Input... args) { if (ignoreNulls) { for (int i = adjustForShrinkingWindow; i < currentFrame.upperBoundExclusive(); i++) { Object[] nthRowCells = currentFrame.getRowInFrameAtIndexOrNull(i); if (nthRowCells != null) { Object value = extractValueFromRow(nthRowCells, expressions, args); if (value != null) { return value; } } } } else { return extractValueAtIndex(adjustForShrinkingWindow, currentFrame, expressions, args); } return null; } }, LAST_VALUE { @Override public Object execute(int adjustForShrinkingWindow, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, boolean ignoreNulls, Input... args) { if (ignoreNulls) { for (int i = adjustForShrinkingWindow + currentFrame.size() - 1; i >= 0; i--) { Object[] nthRowCells = currentFrame.getRowInFrameAtIndexOrNull(i); if (nthRowCells != null) { Object value = extractValueFromRow(nthRowCells, expressions, args); if (value != null) { return value; } } } } else { return extractValueAtIndex(adjustForShrinkingWindow + currentFrame.size() - 1, currentFrame, expressions, args); } return null; } }, NTH_VALUE { @Override public Object execute(int adjustForShrinkingWindow, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, boolean ignoreNulls, Input... args) { Number position = (Number) args[1].value(); if (position == null) { return null; } int iPosition = position.intValue(); if (ignoreNulls) { for (int i = adjustForShrinkingWindow, counter = 0; i < currentFrame.upperBoundExclusive(); i++) { Object[] nthRowCells = currentFrame.getRowInFrameAtIndexOrNull(i); if (nthRowCells != null) { Object value = extractValueFromRow(nthRowCells, expressions, args); if (value != null) { counter++; if (counter == iPosition) { return value; } } } } } else { return extractValueAtIndex(adjustForShrinkingWindow + iPosition - 1, currentFrame, expressions, args); } return null; } }; public abstract Object execute(int adjustForShrinkingWindow, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, boolean ignoreNulls, Input[] args); protected static Object extractValueFromRow(Object[] nthRowCells, List<? extends CollectExpression<Row, ?>> expressions, Input... args) { Row nthRowInFrame = new RowN(nthRowCells); for (CollectExpression<Row, ?> expression : expressions) { expression.setNextRow(nthRowInFrame); } return args[0].value(); } protected static Object extractValueAtIndex(int index, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, Input[] args) { Object[] nthRowCells = currentFrame.getRowInFrameAtIndexOrNull(index); if (nthRowCells == null) { return null; } return extractValueFromRow(nthRowCells, expressions, args); } } public static void register(ExtraFunctionsModule module) { module.register( Signature.window( FIRST_VALUE_NAME, parseTypeSignature("E"), parseTypeSignature("E") ).withTypeVariableConstraints(typeVariable("E")), (signature, boundSignature) -> new NthValueFunctions( signature, boundSignature, Implementation.FIRST_VALUE ) ); module.register( Signature.window( LAST_VALUE_NAME, parseTypeSignature("E"), parseTypeSignature("E") ).withTypeVariableConstraints(typeVariable("E")), (signature, boundSignature) -> new NthValueFunctions( signature, boundSignature, Implementation.LAST_VALUE ) ); module.register( Signature.window( NTH_VALUE_NAME, parseTypeSignature("E"), DataTypes.INTEGER.getTypeSignature(), parseTypeSignature("E") ).withTypeVariableConstraints(typeVariable("E")), (signature, boundSignature) -> new NthValueFunctions( signature, boundSignature, Implementation.NTH_VALUE ) ); } public static final String FIRST_VALUE_NAME = "first_value"; public static final String LAST_VALUE_NAME = "last_value"; public static final String NTH_VALUE_NAME = "nth_value"; private final Implementation implementation; private final Signature signature; private final Signature boundSignature; private int seenFrameLowerBound = -1; private int seenFrameUpperBound = -1; private Object resultForCurrentFrame = null; private NthValueFunctions(Signature signature, Signature boundSignature, Implementation implementation) { this.signature = signature; this.boundSignature = boundSignature; this.implementation = implementation; } @Override public Signature signature() { return signature; } @Override public Signature boundSignature() { return boundSignature; } @Override public Object execute(int idxInPartition, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, @Nullable Boolean ignoreNulls, Input... args) { boolean ignoreNullsOrFalse = ignoreNulls != null && ignoreNulls; boolean shrinkingWindow = isLowerBoundIncreasing(currentFrame, seenFrameLowerBound); if (idxInPartition == 0 || currentFrame.upperBoundExclusive() > seenFrameUpperBound || shrinkingWindow) { int adjustForShrinkingWindow = 0; if (shrinkingWindow) { // consecutive shrinking frames (lower bound increments) will can have the following format : // frame 1: 1 2 3 with lower bound 0 // frame 2: 2 3 with lower bound 1 // We represent the frames as a view over the rows in a partition (for frame 2 the element "1" is not // present by virtue of the frame's lower bound being 1 and "hiding"/excluding it) // If we want the 2nd value (index = 1) in every frame we have to request the index _after_ the frame's // lower bound (in our example, to get the 2nd value in the second frame, namely "3", the requested // index needs to be 2) adjustForShrinkingWindow = currentFrame.lowerBound(); } resultForCurrentFrame = implementation.execute(adjustForShrinkingWindow, currentFrame, expressions, ignoreNullsOrFalse, args); seenFrameLowerBound = currentFrame.lowerBound(); seenFrameUpperBound = currentFrame.upperBoundExclusive(); } return resultForCurrentFrame; } }
44.063433
120
0.516555
e34f93314cdbbdc36ae2d797db0b82fe72863eba
282
package com.leafCat.common.util; public class StaticStringUtil { //Login String public static String USER_NOT_EXIST = "NE"; public static String USER_LOCKED = "LO"; public static String USER_PASSWORD_ERR = "PE"; public static String USER_LOGIN_SUCCESS = "SU"; }
23.5
49
0.72695
115cd5f5b4f3671934b2f6cc26d7e28052b7e83a
516
package by.itacademi.hotel.web.command; import by.itacademi.hotel.web.command.impl.Close; import by.itacademi.hotel.web.command.impl.Guest; import by.itacademi.hotel.web.command.impl.Login; public class CommandChooser { public static Action perForAction(ActionType actionT){ Action action= null; switch(actionT){ case LOGIN: action = new Login(); break; case GUEST: action = new Guest(); break; case CLOSE: action = new Close(); } return action; } }
14.333333
55
0.674419
e6794d1a344524475330dd2f7ae70ebd45a23366
4,211
package Vinetalk; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.List; import java.util.Arrays; import com.sun.jna.Memory; import com.sun.jna.Native; public class VineBuffer extends Structure { public Pointer user_buffer; public long user_buffer_size; public Pointer vine_data; private Object juser_buffer; private Class juser_class; protected List<String> getFieldOrder() { return Arrays.asList(new String[] {"user_buffer","user_buffer_size","vine_data"}); } public VineBuffer() {} public VineBuffer(Structure struct) { this(struct,1,true); // Synchronize by default } public VineBuffer(Structure struct, boolean sync) { this(struct,1,sync); // Synchronize by default } public VineBuffer(Structure struct, int elementNo) { this(struct,elementNo,true); // Synchronize by default } public VineBuffer(Structure struct, int elementNo, boolean sync) { user_buffer = struct.getPointer(); user_buffer_size = struct.size()*elementNo; // juser_buffer = null; juser_buffer = struct; juser_class = Structure.class; if(sync) write(); } public VineBuffer(byte [] data) { this(data,true); // Synchronize by default } public VineBuffer(byte [] data, boolean sync) { Pointer mem = new Memory(data.length); mem.write(0,data,0,data.length); user_buffer = mem; user_buffer_size = data.length; juser_buffer = data; juser_class = Byte.class; if(sync) write(); } public VineBuffer(float [] data) { this(data,true); // Synchronize by default } public VineBuffer(float [] data, boolean sync) { int bytes = data.length*Native.getNativeSize(Float.class); Pointer mem = new Memory(bytes); mem.write(0, data, 0, data.length); user_buffer = mem; user_buffer_size = bytes; juser_buffer = data; juser_class = Float.class; if(sync) write(); } public VineBuffer(long [] data) { this(data,true); // Synchronize by default } public VineBuffer(long [] data, boolean sync) { int bytes = data.length*Native.getNativeSize(Long.class); Pointer mem = new Memory(bytes); mem.write(0, data, 0, data.length); user_buffer = mem; user_buffer_size = bytes; juser_buffer = data; juser_class = Long.class; if(sync) write(); } public VineBuffer(int [] data) { this(data,true); // Synchronize by default } public VineBuffer(int [] data, boolean sync) { int bytes = data.length*Native.getNativeSize(Integer.class); Pointer mem = new Memory(bytes); mem.write(0, data, 0, data.length); user_buffer = mem; user_buffer_size = bytes; juser_buffer = data; juser_class = Integer.class; if(sync) write(); } public void copyFrom(VineBuffer source) { user_buffer = source.user_buffer; user_buffer_size = source.user_buffer_size; vine_data = source.vine_data; juser_buffer = source.juser_buffer; juser_class = source.juser_class; } public void read() { super.read(); if(user_buffer == null) return; if(juser_class == Byte.class) { byte [] data = user_buffer.getByteArray(0,(int)user_buffer_size); if(juser_buffer != null) System.arraycopy(data,0,juser_buffer,0,(int)user_buffer_size); } else if(juser_class == Float.class) { int elements = (int)user_buffer_size/Native.getNativeSize(Float.class); float [] data = user_buffer.getFloatArray(0,elements); if(juser_buffer != null) { System.arraycopy(data,0,juser_buffer,0,elements); } } else if(juser_class == Long.class) { int elements = (int)user_buffer_size/Native.getNativeSize(Long.class); long [] data = user_buffer.getLongArray(0,elements); if(juser_buffer != null) System.arraycopy(data,0,juser_buffer,0,elements); } else if(juser_class == Integer.class) { int elements = (int)user_buffer_size/Native.getNativeSize(Integer.class); int [] data = user_buffer.getIntArray(0,elements); if(juser_buffer != null) System.arraycopy(data,0,juser_buffer,0,elements); } else if(juser_class == Structure.class) { if(juser_buffer != null) { Structure data = (Structure) juser_buffer; data.read(); } } else { assert null!="Invalid juser_class!"; } } }
23.137363
84
0.692235
cb4fb871ae204ef30da2bf571849df825a375f1e
869
package org.bukkit.event.vehicle; import org.bukkit.Location; import org.bukkit.entity.Vehicle; import org.bukkit.event.HandlerList; /** * Raised when a vehicle moves. */ public class VehicleMoveEvent extends VehicleEvent { private static final HandlerList handlers = new HandlerList(); private final Location from; private final Location to; public VehicleMoveEvent(final Vehicle vehicle, final Location from, final Location to) { super(vehicle); this.from = from; this.to = to; } /** * Get the previous position. * * @return Old position. */ public Location getFrom() { return from; } /** * Get the next position. * * @return New position. */ public Location getTo() { return to; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
18.104167
89
0.706559
4f45b91576e462324a0eb675671dfc9208abe2d3
1,178
package com.power.doc.model.postman.request.header; /** * @author xingzi */ public class HeaderBean { private String key; private String value; private String type; private boolean disabled; private String name; private String description; public HeaderBean() { this.type = "text"; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
17.58209
52
0.588285
6a05f17f6d35764a8a8af4ab3a134871ec124bbc
3,012
/******************************************************************************* * Copyright (c) 2017 James Mover Zhou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.tinystruct.data.component; import org.tinystruct.ApplicationException; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.logging.Logger; public class Builders extends ArrayList<Object> implements Serializable { private static final long serialVersionUID = 1L; private boolean log = false; private static final Logger logger = Logger.getLogger(Builders.class.getName()); public Builders() { } public String toString() { StringBuilder buffer = new StringBuilder(); Iterator<Object> iterator = this.iterator(); while (iterator.hasNext()) { buffer.append(iterator.next()); buffer.append(','); } if (buffer.length() > 0) buffer.setLength(buffer.length() - 1); return "[" + buffer.toString() + "]"; } public void parse(String value) throws ApplicationException { if (value.indexOf("{") == 0) { if (log) logger.info("分析实体:" + value); Builder builder = new Builder(); builder.parse(value); this.add(builder); int p = builder.getClosedPosition(); if (p < value.length()) { if (value.charAt(p) == ',') { value = value.substring(p + 1); this.parse(value); } } } if (value.indexOf('[') == 0) { logger.info("分析体组:" + value); int end = this.seekPosition(value); logger.info("结束位:" + end + " 长度:" + value.length()); this.parse(value.substring(1, end - 1)); int len = value.length(); if (end < len - 1) { this.parse(value.substring(end + 1)); } } } private int seekPosition(String value) { char[] charray = value.toCharArray(); int i = 0, n = 0, position = charray.length; while (i < position) { char c = charray[i++]; if (c == '[') { n++; } else if (c == ']') { n--; } if (n == 0) position = i; } return position; } }
29.529412
84
0.52656
c9217d250aac14955011167cddf33a9b2635668b
294
package com.rainng.massproxy.models.constant; /** * 快速测试状态 */ public class FastTestStatus { /** * 可用 */ public static final int OK = 1; /** * 需要进一步校验 */ public static final int NEXT = 2; /** * 不可用 */ public static final int BAD = 3; }
13.363636
45
0.52381
7b366942b67901450b2c0fbdfbea3d78f21a72cd
1,138
/** * @ServerInit.java * @author sodaChen E-mail:asframe@qq.com * @version 1.0 * <br>Copyright (C) * <br>This program is protected by copyright laws. * <br>Program Name:KeepArea * <br>Date:2020/2/22 */ package com.asframe.mvc; import com.asframe.server.IServerContext; import com.asframe.mvc.cmd.HttpJsonCmdProcessor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * mvc服务初始化机制 * @author sodaChen * @version 1.0 * <br>Date:2020/10/7 */ public class MvcInit { private static Logger logger = LogManager.getLogger(MvcInit.class); /** * 基于返回json结果的cmd指令处理器 */ private HttpJsonCmdProcessor httpJsonCmdProcessor; /** * 获取到http处理的解析器 * @return */ public HttpJsonCmdProcessor getHttpJsonCmdProcessor() { return this.httpJsonCmdProcessor; } /** * mvc框架的基础初始化 * @param serverContext */ public void init(IServerContext serverContext) { httpJsonCmdProcessor = new HttpJsonCmdProcessor(); httpJsonCmdProcessor.setServerContext(serverContext); logger.info("MvcInit初始化完毕"); } }
22.313725
71
0.681019
b8d5c80f8f5e125c607eb72cfa51f8e57db734df
3,267
package com.github.tadukoo.database.mysql.syntax.statement; /** * SQL Statement is a class used to create a MySQL Statement * * @author Logan Ferree (Tadukoo) * @version Alpha v.0.3 */ public class SQLStatement{ /** * A builder class used to start building a SQL Statement. The following options are available: * * <table> * <caption>SQL Statement Types</caption> * <tr> * <th>Type</th> * <th>Class</th> * </tr> * <tr> * <td>select</td> * <td>{@link SQLSelectStatement}</td> * </tr> * <tr> * <td>insert</td> * <td>{@link SQLInsertStatement}</td> * </tr> * <tr> * <td>update</td> * <td>{@link SQLUpdateStatement}</td> * </tr> * <tr> * <td>delete</td> * <td>{@link SQLDeleteStatement}</td> * </tr> * <tr> * <td>create</td> * <td>{@link SQLCreateStatement}</td> * </tr> * <tr> * <td>drop</td> * <td>{@link SQLDropStatement}</td> * </tr> * <tr> * <td>alter</td> * <td>{@link SQLAlterStatement}</td> * </tr> * </table> * * @author Logan Ferree (Tadukoo) * @version Alpha v.0.3 */ public static class SQLStatementBuilder{ /** Not allowed to instantiate outside {@link SQLStatement} */ private SQLStatementBuilder(){ } /** * @return A {@link SQLSelectStatement.SQLSelectStatementBuilder builder} to use to make a * {@link SQLSelectStatement} */ public SQLSelectStatement.DistinctOrColumnsOrTables select(){ return SQLSelectStatement.builder(); } /** * @return A {@link SQLInsertStatement.SQLInsertStatementBuilder builder} to use to make a * {@link SQLInsertStatement} */ public SQLInsertStatement.Table insert(){ return SQLInsertStatement.builder(); } /** * @return A {@link SQLUpdateStatement.SQLUpdateStatementBuilder builder} to use to make a * {@link SQLUpdateStatement} */ public SQLUpdateStatement.Table update(){ return SQLUpdateStatement.builder(); } /** * @return A {@link SQLDeleteStatement.SQLDeleteStatementBuilder builder} to use to make a * {@link SQLDeleteStatement} */ public SQLDeleteStatement.Table delete(){ return SQLDeleteStatement.builder(); } /** * @return A {@link SQLCreateStatement.SQLCreateStatementBuilder builder} to use to create a * {@link SQLCreateStatement} */ public SQLCreateStatement.Type create(){ return SQLCreateStatement.builder(); } /** * @return A {@link SQLDropStatement.SQLDropStatementBuilder builder} to use to create a * {@link SQLDropStatement} */ public SQLDropStatement.Type drop(){ return SQLDropStatement.builder(); } /** * @return A {@link SQLAlterStatement.SQLAlterStatementBuilder builder} to use to create a * {@link SQLAlterStatement} */ public SQLAlterStatement.Type alter(){ return SQLAlterStatement.builder(); } } /** Not allowed to actually instantiate */ private SQLStatement(){ } /** * @return A {@link SQLStatementBuilder builder} to start building a SQL Statement */ public static SQLStatementBuilder builder(){ return new SQLStatementBuilder(); } }
26.136
96
0.621977
60e2c6b2e8b18c0b349e15ce3f1f34fd7dfee512
331
package com.ashik.moviemela; import com.squareup.moshi.Json; import java.util.List; public class VideoWrapper { @Json(name = "results") private List<Video> videos; public List<Video> getVideos() { return videos; } public void setVideos(List<Video> videos) { this.videos = videos; } }
15.761905
47
0.646526
af85b7fb69b1598243aa3b9f584751d7ac1210c9
3,430
package psidev.psi.mi.jami.utils.comparator.participant; import psidev.psi.mi.jami.model.CausalRelationship; import psidev.psi.mi.jami.model.CvTerm; import psidev.psi.mi.jami.model.Entity; import java.util.Comparator; /** * Basic comparator for CausalRelationship * * It will first compare the relationType using AbstractCvTermComparator. If both relationTypes are identical, it will compare the * target using ParticipantBaseComparator * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>22/05/13</pre> */ public class CausalRelationshipComparator implements Comparator<CausalRelationship>{ private Comparator<CvTerm> cvTermComparator; private EntityComparator participantComparator; /** * <p>Constructor for CausalRelationshipComparator.</p> * * @param cvTermComparator a {@link java.util.Comparator} object. * @param participantComparator a {@link psidev.psi.mi.jami.utils.comparator.participant.EntityComparator} object. */ public CausalRelationshipComparator(Comparator<CvTerm> cvTermComparator, EntityComparator participantComparator){ if (cvTermComparator == null){ throw new IllegalArgumentException("The cvTermComparator cannot be null in a CausalRelationshipComparator"); } this.cvTermComparator = cvTermComparator; if (participantComparator == null){ throw new IllegalArgumentException("The entityBaseComparator cannot be null in a CausalRelationshipComparator"); } this.participantComparator = participantComparator; } /** * <p>Getter for the field <code>cvTermComparator</code>.</p> * * @return a {@link java.util.Comparator} object. */ public Comparator<CvTerm> getCvTermComparator() { return cvTermComparator; } /** * <p>Getter for the field <code>participantComparator</code>.</p> * * @return a {@link psidev.psi.mi.jami.utils.comparator.participant.EntityComparator} object. */ public EntityComparator getParticipantComparator() { return participantComparator; } /** * It will first compare the relationType using AbstractCvTermComparator. If both relationTypes are identical, it will compare the * target using ParticipantBaseComparator * * @param causalRelationship1 : first causal relationship * @param causalRelationship2 : second causal relationship * @return the comparison value */ public int compare(CausalRelationship causalRelationship1, CausalRelationship causalRelationship2) { int EQUAL = 0; int BEFORE = -1; int AFTER = 1; if (causalRelationship1 == causalRelationship2){ return EQUAL; } else if (causalRelationship1 == null){ return AFTER; } else if (causalRelationship2 == null){ return BEFORE; } else { CvTerm relationType1 = causalRelationship1.getRelationType(); CvTerm relationType2 = causalRelationship2.getRelationType(); int comp = cvTermComparator.compare(relationType1, relationType2); if (comp != 0){ return comp; } Entity p1 = causalRelationship1.getTarget(); Entity p2 = causalRelationship2.getTarget(); return participantComparator.compare(p1, p2); } } }
35
134
0.681924
1e53b9214e89bb75bc7b644cab2ed449b943ea88
1,619
package org.swtk.common.framework.type; public enum Alpha { A("a", 'a'), B("b", 'b'), C("c", 'c'), D("d", 'd'), E("e", 'e'), F("f", 'f'), G("g", 'g'), H("h", 'h'), I("i", 'i'), J("j", 'j'), K("k", 'k'), L("l", 'l'), M("m", 'm'), N("n", 'n'), O("o", 'o'), P("p", 'p'), Q("q", 'q'), R("r", 'r'), S("s", 's'), T("t", 't'), U("u", 'u'), V("v", 'v'), W("w", 'w'), X("x", 'x'), Y("y", 'y'), Z("z", 'z'); public static Alpha find(char token) { for (Alpha alpha : Alpha.values()) if (token == alpha.getCh()) return alpha; return null; } public static Alpha find(String token) { for (Alpha alpha : Alpha.values()) if (alpha.lower().equalsIgnoreCase(token)) return alpha; return null; } public static String[] lower(Alpha... alphas) { String[] arr = new String[alphas.length]; for (int i = 0; i < alphas.length; i++) arr[i] = alphas[i].lower(); return arr; } public static String[] upper(Alpha... alphas) { String[] arr = new String[alphas.length]; for (int i = 0; i < alphas.length; i++) arr[i] = alphas[i].upper(); return arr; } private char ch; private String token; private Alpha(String token, char ch) { setToken(token); setCh(ch); } public char ch() { return getCh(); } private char getCh() { return ch; } private String getToken() { return token; } public String lower() { return getToken().toLowerCase(); } private void setCh(char ch) { this.ch = ch; } private void setToken(String token) { this.token = token; } public String upper() { return getToken().toUpperCase(); } }
13.056452
59
0.535516
e880afd03cdcb335c977ccc099ff6edd0b34b7ef
1,592
package Accounts; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import Database.Database; public class Konti { ArrayList<KreditaKonts> kd = new ArrayList<KreditaKonts>(); ArrayList<AlgasKonts> ak = new ArrayList<AlgasKonts>(); ArrayList<NoguldijumaKonts> nk = new ArrayList<NoguldijumaKonts>(); public Konti() { } public void addAccount(AccountTemplate acc) { if (acc.getAccountType() == AccountTemplate.ALGAS_KONTS) { //Make it so that it adds to a array list later ak.add((AlgasKonts)acc.returnSelf()); } if (acc.getAccountType() == AccountTemplate.KREDITA_KONTS) { kd.add((KreditaKonts)acc.returnSelf()); } if (acc.getAccountType() == AccountTemplate.NOGULDIJUMA_KONTS) { nk.add((NoguldijumaKonts)acc.returnSelf()); } } //Not the best ieda using result set here. public void addAccounts(ResultSet rs) { AccountTemplate acc; try { while(rs.next()) { acc = Database.createAccountBasedOnType(rs.getInt("Type")); //Default will be EUR for now because no currency conversion acc.setAll(rs.getFloat("Value"),rs.getString("Currency"),rs.getInt("Type"),rs.getInt("Number")); addAccount(acc); } } catch (SQLException e) { e.printStackTrace(); } } public Konti getAccounts() { return this; } public ArrayList<AlgasKonts> getAlgasKonti() { return ak; } public ArrayList<KreditaKonts> getKreditaKonti() { return kd; } public ArrayList<NoguldijumaKonts> getNoguldijumaKonti() { return nk; } }
24.492308
100
0.67902
5a9c3d2fe61ace64001d05ff991b4a20616f2b39
5,486
package mooklabs.nausicaamod.inventorytab; import java.lang.ref.WeakReference; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mooklabs.laputamod.LapMain; import net.minecraft.entity.Entity; import net.minecraft.entity.Entity.EnumEntitySize; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.PlayerDropsEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import cpw.mods.fml.relauncher.Side; /** * I would like to keep this reserved for tinkers stuff * @author mooklabs * */ public class NPlayerHandler { public ConcurrentHashMap<UUID, NPlayerStats> playerStats = new ConcurrentHashMap<UUID, NPlayerStats>(); @SubscribeEvent public void PlayerLoggedInEvent (PlayerLoggedInEvent event) { onPlayerLogin(event.player); } @SubscribeEvent public void onPlayerRespawn (PlayerRespawnEvent event) { onPlayerRespawn(event.player); } @SubscribeEvent public void onEntityConstructing (EntityEvent.EntityConstructing event) { if (event.entity instanceof EntityPlayer && NPlayerStats.get((EntityPlayer) event.entity) == null) { NPlayerStats.register((EntityPlayer) event.entity); } } public void onPlayerLogin (EntityPlayer entityplayer) { NPlayerStats playerData = playerStats.remove(entityplayer.getPersistentID()); if (playerData != null) { playerData.saveNBTData(entityplayer.getEntityData()); } // Lookup player NPlayerStats stats = NPlayerStats.get(entityplayer); if( entityplayer.getDisplayName().toLowerCase().equals("space_geek")){ entityplayer.inventory.addItemStackToInventory(new ItemStack(Blocks.obsidian, 64)); } if( entityplayer.getDisplayName().toLowerCase().equals("mookie1097")){ } } public void onPlayerRespawn (EntityPlayer entityplayer) { // Boom! NPlayerStats playerData = playerStats.remove(entityplayer.getPersistentID()); NPlayerStats stats = NPlayerStats.get(entityplayer); if (playerData != null) { stats.copyFrom(playerData, false); } stats.player = new WeakReference<EntityPlayer>(entityplayer); stats.armor.recalculateHealth(entityplayer, stats); Side side = FMLCommonHandler.instance().getEffectiveSide(); } @SubscribeEvent public void livingFall (LivingFallEvent evt) // Only for negating fall damage { if (evt.entityLiving instanceof EntityPlayer) { if(((EntityPlayer)evt.entityLiving).inventory.hasItemStack(new ItemStack(LapMain.volucite))) evt.distance = 0; } } /* * @SubscribeEvent public void livingUpdate (LivingUpdateEvent evt) { Side * side = FMLCommonHandler.instance().getEffectiveSide(); if (side == * Side.CLIENT && evt.entityLiving instanceof EntityPlayer) { EntityPlayer * player = (EntityPlayer) evt.entityLiving; NPlayerStats stats = * playerStats.get(player.getDisplayName()); if (player.onGround != * stats.prevOnGround) { if (player.onGround)// && -stats.prevMotionY > 0.1) * //player.motionY = 0.5; player.motionY = -stats.prevMotionY * 0.8; * //player.motionY *= -1.2; stats.prevOnGround = player.onGround; //if () * * //TConstruct.logger.info("Fall: "+player.fallDistance); } } } */ @SubscribeEvent public void playerDeath (LivingDeathEvent event) { if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer) { NPlayerStats properties = (NPlayerStats) event.entity.getExtendedProperties(NPlayerStats.PROP_NAME); playerStats.put(((EntityPlayer) event.entity).getPersistentID(), properties); } } @SubscribeEvent public void playerDrops (PlayerDropsEvent evt) { // After playerDeath event. Modifying saved data. NPlayerStats stats = playerStats.get(evt.entityPlayer.getPersistentID()); stats.armor.dropItems(evt.drops); playerStats.put(evt.entityPlayer.getPersistentID(), stats); } /* Modify Player */ public void updateSize (String user, float offset) { /* * EntityPlayer player = getEntityPlayer(user); setEntitySize(0.6F, * offset, player); player.yOffset = offset - 0.18f; */ } public static void setEntitySize (float width, float height, Entity entity) { // TConstruct.logger.info("Size: " + height); if (width != entity.width || height != entity.height) { entity.width = width; entity.height = height; entity.boundingBox.maxX = entity.boundingBox.minX + entity.width; entity.boundingBox.maxZ = entity.boundingBox.minZ + entity.width; entity.boundingBox.maxY = entity.boundingBox.minY + entity.height; } float que = width % 2.0F; if (que < 0.375D) { entity.myEntitySize = EnumEntitySize.SIZE_1; } else if (que < 0.75D) { entity.myEntitySize = EnumEntitySize.SIZE_2; } else if (que < 1.0D) { entity.myEntitySize = EnumEntitySize.SIZE_3; } else if (que < 1.375D) { entity.myEntitySize = EnumEntitySize.SIZE_4; } else if (que < 1.75D) { entity.myEntitySize = EnumEntitySize.SIZE_5; } else { entity.myEntitySize = EnumEntitySize.SIZE_6; } // entity.yOffset = height; } Random rand = new Random(); }
28.133333
104
0.743347
e1d6a915acf9e6198a67918d4347fcd502e190c9
9,527
package com.curtisnewbie.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Types; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import com.curtisnewbie.model.Student; import com.curtisnewbie.util.LoggerProducer; import com.curtisnewbie.util.LoggerWrapper; /** * ------------------------------------ * * Author: Yongjie Zhuang * * ------------------------------------ * <p> * Implementation of {@link com.curtisnewbie.dao.StudentDao} for * {@link com.curtisnewbie.model.Student} table. * </p> */ public class StudentRepository implements StudentDao { private final String SELECT_ALL = "SELECT * FROM student"; private final String SELECT_BY_FNAME = "SELECT * FROM student WHERE firstname LIKE ?"; private final String SELECT_BY_LNAME = "SELECT * FROM student WHERE lastname LIKE ?"; private final String SELECT_BY_REG_DATE = "SELECT * FROM student WHERE reg_date = ?"; private final String DELETE_BY_ID = "DELETE FROM student WHERE id = ?"; private final String SELECT_BY_ID = "SELECT * FROM student WHERE id = ?"; private final String UPDATE_FIRSTNAME = "UPDATE student SET firstname = ? WHERE id = ?"; private final String UPDATE_LASTNAME = "UPDATE student SET lastname = ? WHERE id = ?"; private final String UPDATE_REG_DATE = "UPDATE student SET reg_date = ? WHERE id = ?"; private final String CREATE_STUDENT_WITH_ID = "INSERT INTO student VALUES(?, ?, ?, ?, ?)"; private final String CREATE_STUDENT_WITHOUT_ID = "INSERT INTO student (firstname, lastname, reg_date, cou_fk) VALUES(?, ?, ?, ?)"; private final String UPDATE_STUDENT = "UPDATE student SET firstname = ?, lastname = ?, reg_date = ?, cou_fk = ? WHERE id = ?"; private final Connection conn = DBManager.getDBManager().getConnection(); private final LoggerWrapper logger = LoggerProducer.getLogger(this); @Override public List<Student> getAll() { logger.info("Get all students"); List<Student> list = new ArrayList<>(); try { var stmt = conn.createStatement(); ResultSet set = stmt.executeQuery(SELECT_ALL); while (set.next()) { var stu = new Student(set.getInt(1), set.getString(2), set.getString(3), LocalDate.parse(set.getString(4)), set.getInt(5)); list.add(stu); } } catch (Exception e) { logger.severe(e.getMessage()); } return list; } @Override public boolean deleteById(int id) { logger.info(String.format("Delete id: '%d'", id)); try { var stmt = conn.prepareStatement(DELETE_BY_ID); stmt.setInt(1, id); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } } @Override public Student findById(int id) { logger.info(String.format("Find id: '%d'", id)); try { var stmt = conn.prepareStatement(SELECT_BY_ID); stmt.setInt(1, id); ResultSet set = stmt.executeQuery(); Student stu = null; if (set.next()) { stu = new Student(set.getInt(1), set.getString(2), set.getString(3), LocalDate.parse(set.getString(4)), set.getInt(5)); } return stu; } catch (Exception e) { logger.severe(e.getMessage()); } return null; } @Override public boolean update(Student stu) { if (stu == null) { logger.severe("The student to be updated is null!"); return false; } return update(stu.getFirstname(), stu.getLastname(), stu.getDateOfRegi(), stu.getId(), stu.getCourseFk()); } @Override public boolean update(String firstname, String lastname, LocalDate date, int id, int courseId) { logger.info(String.format("Update student to: 'id: %d, firstname: %s, lastname: %s, date: %s, courseFk: %d'", id, firstname, lastname, date.toString(), courseId)); try { PreparedStatement stmt = conn.prepareStatement(UPDATE_STUDENT); stmt.setString(1, firstname); stmt.setString(2, lastname); stmt.setString(3, date.toString()); if (courseId != UnitDao.NULL_INT) stmt.setInt(4, courseId); else stmt.setNull(4, Types.INTEGER); stmt.setInt(5, id); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); } return false; } @Override public boolean create(Student stu) { logger.info("Create student: '" + stu.toString() + "'"); boolean withId = true; if (stu.getId() == UnitDao.GENERATED_ID) withId = false; try { PreparedStatement stmt; int i = 1; if (withId) { stmt = conn.prepareStatement(CREATE_STUDENT_WITH_ID); stmt.setInt(i++, stu.getId()); } else { stmt = conn.prepareStatement(CREATE_STUDENT_WITHOUT_ID); } stmt.setString(i++, stu.getFirstname()); stmt.setString(i++, stu.getLastname()); stmt.setString(i++, stu.getDateOfRegi().toString()); if (stu.getCourseFk() != UnitDao.NULL_INT) stmt.setInt(i++, stu.getCourseFk()); else stmt.setNull(i++, Types.INTEGER); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); } return false; } @Override public boolean updateFirstname(int id, String fname) { logger.info(String.format("Update id: '%d', firstname updated to '%s'", id, fname)); try { var stmt = conn.prepareStatement(UPDATE_FIRSTNAME); stmt.setString(1, fname); stmt.setInt(2, id); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); } return false; } @Override public boolean updateLastname(int id, String lname) { logger.info(String.format("Update id: '%d', lastname updated to '%s'", id, lname)); try { var stmt = conn.prepareStatement(UPDATE_LASTNAME); stmt.setString(1, lname); stmt.setInt(2, id); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); } return false; } @Override public boolean updateDateOfReg(int id, LocalDate date) { logger.info(String.format("Update id: '%d', date updated to: '%s'", id, date.toString())); try { PreparedStatement stmt = conn.prepareStatement(UPDATE_REG_DATE); stmt.setDate(1, java.sql.Date.valueOf(date)); stmt.setInt(2, id); stmt.executeUpdate(); return true; } catch (Exception e) { logger.severe(e.getMessage()); } return false; } @Override public List<Student> findStusByFirstname(String fname) { logger.info(String.format("Find firstname: '%s'", fname)); List<Student> list = new ArrayList<>(); try { var stmt = conn.prepareStatement(SELECT_BY_FNAME); stmt.setString(1, "%" + fname + "%"); ResultSet set = stmt.executeQuery(); while (set.next()) { var stu = new Student(set.getInt(1), set.getString(2), set.getString(3), LocalDate.parse(set.getString(4)), set.getInt(5)); list.add(stu); } } catch (Exception e) { logger.severe(e.getMessage()); } return list; } @Override public List<Student> findStusByLastname(String lname) { logger.info(String.format("Find lastname: '%s'", lname)); List<Student> list = new ArrayList<>(); try { var stmt = conn.prepareStatement(SELECT_BY_LNAME); stmt.setString(1, "%" + lname + "%"); ResultSet set = stmt.executeQuery(); while (set.next()) { var stu = new Student(set.getInt(1), set.getString(2), set.getString(3), LocalDate.parse(set.getString(4)), set.getInt(5)); list.add(stu); } } catch (Exception e) { logger.severe(e.getMessage()); } return list; } @Override public List<Student> findStusByDateOfReg(LocalDate date) { logger.info(String.format("Find date of registration: '%s'", date.toString())); List<Student> list = new ArrayList<>(); try { var stmt = conn.prepareStatement(SELECT_BY_REG_DATE); stmt.setString(1, date.toString()); ResultSet set = stmt.executeQuery(); while (set.next()) { var stu = new Student(set.getInt(1), set.getString(2), set.getString(3), LocalDate.parse(set.getString(4)), set.getInt(5)); list.add(stu); } } catch (Exception e) { logger.severe(e.getMessage()); } return list; } }
36.783784
134
0.561352
5d2f6c26c78f9518b4ffba5b1af35e01fbead26c
5,215
package com.hubspot.singularity.runner.base.shared; import com.google.common.collect.Sets; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ProcessBuilder.Redirect; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import org.slf4j.Logger; public class SimpleProcessManager extends SafeProcessManager { public SimpleProcessManager(Logger log) { super(log); } public void runCommand( final List<String> command, final Set<Integer> acceptableExitCodes ) throws InterruptedException, ProcessFailedException { runCommand(command, Redirect.INHERIT, acceptableExitCodes); } public void runCommand(final List<String> command) throws InterruptedException, ProcessFailedException { runCommand(command, Redirect.INHERIT, Sets.newHashSet(0)); } public List<String> runCommandWithOutput( final List<String> command, final Set<Integer> acceptableExitCodes ) throws InterruptedException, ProcessFailedException { return runCommand(command, Redirect.PIPE, acceptableExitCodes); } public List<String> runCommandWithOutput(final List<String> command) throws InterruptedException, ProcessFailedException { return runCommand(command, Redirect.PIPE, Sets.newHashSet(0)); } public List<String> runCommand( final List<String> command, final Redirect redirectOutput ) throws InterruptedException, ProcessFailedException { return runCommand(command, redirectOutput, Sets.newHashSet(0)); } public int getExitCode(final List<String> command, long timeoutMillis) { final ProcessBuilder processBuilder = new ProcessBuilder(command); Optional<Integer> exitCode = Optional.empty(); try { final Process process = startProcess(processBuilder); boolean exited = process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS); if (exited) { exitCode = Optional.of(process.exitValue()); return process.exitValue(); } else { throw new TimeoutException( String.format( "Waited %d ms for an exit code from `%s`, but it didn't terminate in time.", timeoutMillis, command.stream().collect(Collectors.joining(" ")) ) ); } } catch (Throwable t) { signalKillToProcessIfActive(); throw new RuntimeException(t); } finally { processFinished(exitCode); } } public List<String> runCommand( final List<String> command, final Redirect redirectOutput, final Set<Integer> acceptableExitCodes ) throws InterruptedException, ProcessFailedException { final ProcessBuilder processBuilder = new ProcessBuilder(command); Optional<Integer> exitCode = Optional.empty(); Optional<OutputReader> reader = Optional.empty(); String processToString = getCurrentProcessToString(); try { processBuilder.redirectError(Redirect.INHERIT); processBuilder.redirectOutput(redirectOutput); final Process process = startProcess(processBuilder); processToString = getCurrentProcessToString(); if (redirectOutput == Redirect.PIPE) { reader = Optional.of(new OutputReader(process.getInputStream())); reader.get().start(); } exitCode = Optional.of(process.waitFor()); if (reader.isPresent()) { reader.get().join(); if (reader.get().error.isPresent()) { throw reader.get().error.get(); } } } catch (InterruptedException ie) { signalKillToProcessIfActive(); throw ie; } catch (Throwable t) { getLog().error("Unexpected exception while running {}", processToString, t); signalKillToProcessIfActive(); throw new RuntimeException(t); } finally { processFinished(exitCode); } if (exitCode.isPresent() && !acceptableExitCodes.contains(exitCode.get())) { throw new ProcessFailedException( String.format( "Got unacceptable exit code %s while running %s", exitCode, processToString ) ); } if (!reader.isPresent()) { return Collections.emptyList(); } return reader.get().output; } private static class OutputReader extends Thread { private final List<String> output; private final InputStream inputStream; private Optional<Throwable> error; public OutputReader(InputStream inputStream) { this.output = new ArrayList<>(); this.inputStream = inputStream; this.error = Optional.empty(); } @Override public void run() { try ( BufferedReader br = new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8) ) ) { String line = br.readLine(); while (line != null) { output.add(line); line = br.readLine(); } } catch (Throwable t) { this.error = Optional.of(t); } } } }
28.653846
88
0.680537
c66b4647f88d4bb81f4ef366b3c208670f5d7685
5,136
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dataproc.model; /** * GKE node pools that Dataproc workloads run on. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Dataproc API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GkeNodePoolTarget extends com.google.api.client.json.GenericJson { /** * Required. The target GKE node pool. Format: * 'projects/{project}/locations/{location}/clusters/{cluster}/nodePools/{node_pool}' * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nodePool; /** * Input only. The configuration for the GKE node pool.If specified, Dataproc attempts to create a * node pool with the specified shape. If one with the same name already exists, it is verified * against all specified fields. If a field differs, the virtual cluster creation will fail.If * omitted, any node pool with the specified name is used. If a node pool with the specified name * does not exist, Dataproc create a node pool with default values.This is an input only field. It * will not be returned by the API. * The value may be {@code null}. */ @com.google.api.client.util.Key private GkeNodePoolConfig nodePoolConfig; /** * Required. The roles associated with the GKE node pool. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> roles; /** * Required. The target GKE node pool. Format: * 'projects/{project}/locations/{location}/clusters/{cluster}/nodePools/{node_pool}' * @return value or {@code null} for none */ public java.lang.String getNodePool() { return nodePool; } /** * Required. The target GKE node pool. Format: * 'projects/{project}/locations/{location}/clusters/{cluster}/nodePools/{node_pool}' * @param nodePool nodePool or {@code null} for none */ public GkeNodePoolTarget setNodePool(java.lang.String nodePool) { this.nodePool = nodePool; return this; } /** * Input only. The configuration for the GKE node pool.If specified, Dataproc attempts to create a * node pool with the specified shape. If one with the same name already exists, it is verified * against all specified fields. If a field differs, the virtual cluster creation will fail.If * omitted, any node pool with the specified name is used. If a node pool with the specified name * does not exist, Dataproc create a node pool with default values.This is an input only field. It * will not be returned by the API. * @return value or {@code null} for none */ public GkeNodePoolConfig getNodePoolConfig() { return nodePoolConfig; } /** * Input only. The configuration for the GKE node pool.If specified, Dataproc attempts to create a * node pool with the specified shape. If one with the same name already exists, it is verified * against all specified fields. If a field differs, the virtual cluster creation will fail.If * omitted, any node pool with the specified name is used. If a node pool with the specified name * does not exist, Dataproc create a node pool with default values.This is an input only field. It * will not be returned by the API. * @param nodePoolConfig nodePoolConfig or {@code null} for none */ public GkeNodePoolTarget setNodePoolConfig(GkeNodePoolConfig nodePoolConfig) { this.nodePoolConfig = nodePoolConfig; return this; } /** * Required. The roles associated with the GKE node pool. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getRoles() { return roles; } /** * Required. The roles associated with the GKE node pool. * @param roles roles or {@code null} for none */ public GkeNodePoolTarget setRoles(java.util.List<java.lang.String> roles) { this.roles = roles; return this; } @Override public GkeNodePoolTarget set(String fieldName, Object value) { return (GkeNodePoolTarget) super.set(fieldName, value); } @Override public GkeNodePoolTarget clone() { return (GkeNodePoolTarget) super.clone(); } }
38.616541
182
0.719626
11f4675a875f808e536dd5487d06830d9743da67
160
package com.example.javalib; /** * log工具类 * @author chenjianyu */ public class Logger { void log(String msg){ System.out.println(msg); } }
12.307692
32
0.6125
e18caf2ce55f530c3e795a8ea40b27fefac88d6c
295
package rpc; public class RpcException extends RuntimeException{ private static final long serialVersionUID = 6238589897120159526L; public RpcException(){ super(); } public RpcException(String message){ super(message); } public RpcException(Throwable thr){ super(thr); } }
14.75
67
0.738983
c1b86a6ba59d6ee4c4a9d57cc2841c52f8031d0f
2,598
package com.example.xyzreader.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.xyzreader.R; import com.example.xyzreader.data.ArticleLoader; import com.example.xyzreader.data.ItemsContract; /** * Created by royarzun on 02-08-16. */ public class ArticlesAdapter extends RecyclerView.Adapter<ArticlesViewHolder> { private Cursor mCursor; private Context mContext; private LayoutInflater mInflater; public ArticlesAdapter(Cursor cursor, Context context) { mCursor = cursor; mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public long getItemId(int position) { mCursor.moveToPosition(position); return mCursor.getLong(ArticleLoader.Query._ID); } @Override public ArticlesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.list_item_article, parent, false); final ArticlesViewHolder vh = new ArticlesViewHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation((Activity) mContext, view, "itemTransition"); mContext.startActivity(new Intent(Intent.ACTION_VIEW, ItemsContract.Items.buildItemUri(getItemId(vh.getAdapterPosition()))), options.toBundle()); } }); return vh; } @Override public void onBindViewHolder(ArticlesViewHolder holder, int position) { mCursor.moveToPosition(position); holder.titleView.setText(mCursor.getString(ArticleLoader.Query.TITLE)); holder.subtitleView.setText(" by " + mCursor.getString(ArticleLoader.Query.AUTHOR)); holder.thumbnailView.setImageUrl( mCursor.getString(ArticleLoader.Query.THUMB_URL), ImageLoaderHelper.getInstance(mContext).getImageLoader()); holder.thumbnailView.setAspectRatio(mCursor.getFloat(ArticleLoader.Query.ASPECT_RATIO)); holder.thumbnailView.setTransitionName("itemTransition"); } @Override public int getItemCount() { return mCursor.getCount(); } }
35.108108
98
0.700539
a481c0652d4da67442e9a1fa9b0de33ed25133d1
853
package org.zerozill.muldijson.parser; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonValue; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class MinimalJsonParser extends AbstractJsonParser { public MinimalJsonParser() { this.parserType = Parsers.MINIMAL_JSON; } @Deprecated @Override public <T> T deserialize(String json, Class<T> clazz) { throw new NotImplementedException(); } @Deprecated @Override public <T> String serialize(T bean) { throw new NotImplementedException(); } @Override public <T> T parse(String json) { return (T) Json.parse(json); } @Override public <T> String write(T jsonObject) { assert jsonObject instanceof JsonValue; return jsonObject.toString(); } }
23.694444
70
0.68347
4d59a66b070fc6ed1cbd30c47f3fffeecaeff620
562
package foundation.omni.rpc; import org.bitcoinj.core.Address; import org.bitcoinj.core.Sha256Hash; import org.consensusj.jsonrpc.JsonRpcException; import java.io.IOException; /** * Methods needed to support {@link foundation.omni.rpc.test.OmniTestClientMethods} interface. */ public interface OmniClientRawTxSupport { Sha256Hash omniSendRawTx(Address fromAddress, String rawTxHex) throws JsonRpcException, IOException; Sha256Hash omniSendRawTx(Address fromAddress, String rawTxHex, Address referenceAddress) throws JsonRpcException, IOException; }
35.125
130
0.820285
7f62b1811c07a93d02391fc24564834d96f737fd
1,591
package com.xh.demo.controller; import java.util.List; import com.xh.demo.domain.vo.ApiResult; import lombok.extern.slf4j.Slf4j; import com.xh.demo.domain.po.Oauth2UserInfo; import com.xh.demo.service.Oauth2UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("oauth2UserInfo") public class Oauth2UserInfoController { @Autowired private Oauth2UserInfoService oauth2UserInfoService; /** * @Name get * @Description 通过id获取数据 * @param id */ @GetMapping("{id}") public ApiResult<Oauth2UserInfo> get(@PathVariable("id") Long id) { return ApiResult.success(oauth2UserInfoService.getById(id)); } /** * @Name add * @Description 保存操作 * @param oauth2UserInfo */ @PostMapping("save") public ApiResult save(@RequestBody Oauth2UserInfo oauth2UserInfo) { //添加操作 return ApiResult.res(oauth2UserInfoService.add(oauth2UserInfo)); } /** * @Name update * @Description 修改操作 * @param oauth2UserInfo */ @PostMapping("update") public ApiResult update(@RequestBody Oauth2UserInfo oauth2UserInfo) { //修改操作 return ApiResult.res(oauth2UserInfoService.update(oauth2UserInfo)); } /** * @Name delete * @Description 删除操作 * @param id */ @GetMapping("delete/{id}") public ApiResult<Oauth2UserInfo> delete(@PathVariable("id") Long id) { oauth2UserInfoService.deleteById(id); return ApiResult.success(); } }
25.66129
75
0.683218
6c7a3fbbd5c61a47415b63a935f99719c507f745
2,132
/*- * Copyright (C) 2011, 2017 Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package oracle.kv.impl.security.login; import java.util.concurrent.atomic.AtomicReference; import oracle.kv.impl.security.SessionAccessException; import oracle.kv.impl.topo.ResourceId.ResourceType; /** * LoginHandle defines the interface by which RMI interface APIs acquire * LoginTokens for called methods. */ public abstract class LoginHandle { private final AtomicReference<LoginToken> loginToken; protected LoginHandle(LoginToken loginToken) { this.loginToken = new AtomicReference<LoginToken>(loginToken); } /** * Get the current LoginToken value. */ public LoginToken getLoginToken() { return loginToken.get(); } /** * Attempt to update the LoginToken to be a new value. * If the current token is not the same identity as the old token, * the update is not performed. * @return true if the update was performed. */ protected boolean updateLoginToken(LoginToken oldToken, LoginToken newToken) { return loginToken.compareAndSet(oldToken, newToken); } /** * Attempt to renew the token to a later expiration time. * Returns null if unable to renew. */ public abstract LoginToken renewToken(LoginToken currToken) throws SessionAccessException; /** * Logout the session associated with the login token. */ public abstract void logoutToken() throws SessionAccessException; /** * Report whether this login handle supports authentication to the * specified resouce type. */ public abstract boolean isUsable(ResourceType rtype); }
31.352941
96
0.70122
b5948a1f41bc8d4a56d4c482c8fee33215d8d3b9
3,005
package com.didichuxing.daedalus.service.dispatcher; import com.didichuxing.daedalus.common.ErrorCode; import com.didichuxing.daedalus.common.enums.ClusterEnum; import com.didichuxing.daedalus.common.enums.ExecTypeEnum; import com.didichuxing.daedalus.dal.LogDal; import com.didichuxing.daedalus.dal.PipelineDal; import com.didichuxing.daedalus.entity.log.LogEntity; import com.didichuxing.daedalus.entity.pipeline.PipelineEntity; import com.didichuxing.daedalus.handler.LogConverter; import com.didichuxing.daedalus.pojo.Constants; import com.didichuxing.daedalus.pojo.ExecuteException; import com.didichuxing.daedalus.pojo.request.ExecuteRequest; import com.didichuxing.daedalus.util.Validator; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author : jiangxinyu * @date : 2021/1/20 */ @Component @Slf4j public class ResumeDispatchExecutor extends AbstractDispatcherExecutor { @Autowired private LogDal logDal; @Autowired private PipelineDal pipelineDal; @Override protected PipelineEntity getPipeline(ExecuteRequest request) { LogEntity logEntity = getLogEntity(request); Validator.assertTrue(logEntity.getCluster() != null, "历史运行记录不支持恢复运行!"); String pipelineId = logEntity.getPipelineId(); PipelineEntity pipelineEntity = pipelineDal.queryById(pipelineId); Validator.notNull(pipelineEntity, ErrorCode.PIPELINE_NOT_FOUND); return pipelineEntity; } @Override protected ExecuteRequest buildRequest(ExecuteRequest request, PipelineEntity pipeline, ClusterEnum cluster) { //从logid中构建request String resumeLogId = request.getResumeLogId(); LogEntity logEntity = getLogEntity(request); ExecuteRequest executeRequest = new ExecuteRequest(); executeRequest.setPipelineId(logEntity.getPipelineId()); executeRequest.setInputs(logEntity.getRuntimeVars()); executeRequest.setExecType(ExecTypeEnum.RESUME); executeRequest.setResumeLogId(resumeLogId); executeRequest.setEnv(logEntity.getRuntimeVars().get(Constants.ENV)); if (cluster == ClusterEnum.OFFLINE) { //补充log信息 executeRequest.setLog(LogConverter.entityToDto(logEntity)); buildOfflineRequest(executeRequest, pipeline); } return executeRequest; } private LogEntity getLogEntity(ExecuteRequest request) { String logId = request.getResumeLogId(); log.info("继续运行历史记录:{}", logId); return logDal.findById(logId).orElseThrow(() -> new ExecuteException("运行记录不存在!")); } @Override protected ClusterEnum determineCluster(ExecuteRequest request, PipelineEntity pipelineEntity) { LogEntity logEntity = getLogEntity(request); if (logEntity.getCluster() == null) { throw new ExecuteException("历史运行记录不支持失败重新运行!"); } return logEntity.getCluster(); } }
39.025974
113
0.742762
6142e728fcfdf2b3bb60f455cb4ee655c99526d8
6,726
package bo.user.jdbc; import java.sql.SQLException; import java.text.MessageFormat; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.github.ddth.commons.utils.DPathUtils; import com.github.ddth.dao.jdbc.BaseJdbcDao; import bo.user.IUserDao; import bo.user.UserBo; /** * Jdbc-implement of {@link IUserDao}. * * @author Thanh Nguyen <btnguyen2k@gmail.com> * @since 0.1.0 */ public class JdbcUserDao extends BaseJdbcDao implements IUserDao { private String tableNameUser = "djs_user"; private String cacheNameUser = "DJS_USER"; protected String getTableNameUser() { return tableNameUser; } public JdbcUserDao setTableNameUser(String tableNameUser) { this.tableNameUser = tableNameUser; return this; } protected String getCacheNameUser() { return cacheNameUser; } public JdbcUserDao setCacheNameUser(String cacheNameUser) { this.cacheNameUser = cacheNameUser; return this; } /*----------------------------------------------------------------------*/ private static String cacheKeyUserId(String id) { return "ID_" + id; } private static String cacheKeyUserName(String username) { return "UN_" + username; } private static String cacheKey(UserBo user) { return cacheKeyUserId(user.getId()); } private void invalidate(UserBo user, boolean update) { if (update) { putToCache(cacheNameUser, cacheKey(user), user); } else { removeFromCache(cacheNameUser, cacheKeyUserId(user.getId())); removeFromCache(cacheNameUser, cacheKeyUserName(user.getUsername())); } } /*----------------------------------------------------------------------*/ /** * {@inheritDoc} */ @Override public JdbcUserDao init() { super.init(); SQL_CREATE_USER = MessageFormat.format(SQL_CREATE_USER, tableNameUser); SQL_DELETE_USER = MessageFormat.format(SQL_DELETE_USER, tableNameUser); SQL_GET_USER = MessageFormat.format(SQL_GET_USER, tableNameUser); SQL_GET_USERID_BY_USERNAME = MessageFormat.format(SQL_GET_USERID_BY_USERNAME, tableNameUser); SQL_UPDATE_USER = MessageFormat.format(SQL_UPDATE_USER, tableNameUser); return this; } /*----------------------------------------------------------------------*/ private final static String[] COLS_USER_ALL = { UserBoMapper.COL_ID, UserBoMapper.COL_GROUP_ID, UserBoMapper.COL_USERNAME, UserBoMapper.COL_PASSWORD, UserBoMapper.COL_EMAIL }; private final static String[] COLS_USER_CREATE = COLS_USER_ALL; private String SQL_CREATE_USER = "INSERT INTO {0} (" + StringUtils.join(COLS_USER_CREATE, ',') + ") VALUES (" + StringUtils.repeat("?", ",", COLS_USER_CREATE.length) + ")"; private String SQL_DELETE_USER = "DELETE FROM {0} WHERE " + UserBoMapper.COL_ID + "=?"; private String SQL_GET_USER = "SELECT " + StringUtils.join(COLS_USER_ALL, ',') + " FROM {0} WHERE " + UserBoMapper.COL_ID + "=?"; private String SQL_GET_USERID_BY_USERNAME = "SELECT " + UserBoMapper.COL_ID + " FROM {0} WHERE " + UserBoMapper.COL_USERNAME + "=?"; private String SQL_UPDATE_USER = "UPDATE {0} SET " + StringUtils.join(new String[] { UserBoMapper.COL_GROUP_ID + "=?", UserBoMapper.COL_PASSWORD + "=?", UserBoMapper.COL_EMAIL + "=?" }, ',') + " WHERE " + UserBoMapper.COL_ID + "=?"; /** * {@inheritDoc} */ @Override public boolean create(UserBo user) { final Object[] VALUES = new Object[] { user.getId(), user.getGroupId(), user.getUsername(), user.getPassword(), user.getEmail() }; try { int numRows = execute(SQL_CREATE_USER, VALUES); invalidate(user, true); return numRows > 0; } catch (SQLException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} */ @Override public boolean delete(UserBo user) { final Object[] VALUES = new Object[] { user.getId() }; try { int numRows = execute(SQL_DELETE_USER, VALUES); invalidate(user, false); return numRows > 0; } catch (SQLException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} */ @Override public boolean update(UserBo user) { final Object[] PARAM_VALUES = new Object[] { user.getGroupId(), user.getPassword(), user.getEmail(), user.getId() }; try { int nunRows = execute(SQL_UPDATE_USER, PARAM_VALUES); invalidate(user, true); return nunRows > 0; } catch (SQLException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} */ @Override public UserBo getUser(String id) { if (StringUtils.isBlank(id)) { return null; } final String cacheKey = cacheKeyUserId(id); UserBo result = getFromCache(cacheNameUser, cacheKey, UserBo.class); if (result == null) { final Object[] WHERE_VALUES = new Object[] { id }; try { List<UserBo> dbRows = executeSelect(UserBoMapper.instance, SQL_GET_USER, WHERE_VALUES); result = dbRows != null && dbRows.size() > 0 ? dbRows.get(0) : null; putToCache(cacheNameUser, cacheKey, result); } catch (SQLException e) { throw new RuntimeException(e); } } return result; } /** * {@inheritDoc} */ @Override public UserBo getUserByUsername(String username) { if (StringUtils.isBlank(username)) { return null; } final String cacheKey = cacheKeyUserName(username); String id = getFromCache(cacheNameUser, cacheKey, String.class); if (id == null) { final Object[] WHERE_VALUES = new Object[] { username }; try { List<Map<String, Object>> dbRows = executeSelect(SQL_GET_USERID_BY_USERNAME, WHERE_VALUES); Map<String, Object> dbRow = dbRows != null && dbRows.size() > 0 ? dbRows.get(0) : null; id = DPathUtils.getValue(dbRow, UserBoMapper.COL_ID, String.class); putToCache(cacheNameUser, cacheKey, id); } catch (SQLException e) { throw new RuntimeException(e); } } return getUser(id); } }
33.63
100
0.576123
61e3b55c6b660a8ecdd285b2ceda0cb2a25833ac
565
package dav.mod.objects.blocks.tree; import java.util.Random; import net.minecraft.block.trees.Tree; import net.minecraft.world.gen.feature.BaseTreeFeatureConfig; import net.minecraft.world.gen.feature.ConfiguredFeature; public class CustomTree extends Tree{ private ConfiguredFeature<BaseTreeFeatureConfig, ?> Tree; public CustomTree(ConfiguredFeature<BaseTreeFeatureConfig, ?> Type) { this.Tree = Type; } @Override protected ConfiguredFeature<BaseTreeFeatureConfig, ?> getTreeFeature(Random randomIn, boolean largeHive) { return this.Tree; } }
25.681818
107
0.79646
8fce23fc31c5b4545bca4f60b1143b89797ca2b1
779
import java.util.HashMap; import java.util.Map; public class MarathonUsingHashMap implements Marathon { @Override public String findPersonWhoCantFinish(String[] participant, String[] completion) { Map<String, Integer> map = new HashMap<>(); for (String name : participant) { if (!map.containsKey(name)) { map.put(name, 1); continue; } map.replace(name, (map.get(name) + 1)); } for (String name : completion) { if(map.get(name) == 1) { map.remove(name); continue; } map.replace(name, map.get(name) - 1); } return map.keySet().iterator().next(); } }
25.129032
86
0.499358
4da818141334cab88c12f227f1a96fab624484a3
9,816
package com.linkedin.util; import com.linkedin.util.clock.Clock; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.Marker; /** * Simple logger wrapper to provide rate limiting of log messages. The rate is controlled by the duration, * ie how often (in millisecond) the message should be logged. After one message logged, the rest of the * messages within that duration will be ignored. */ public class RateLimitedLogger implements Logger { private static final long INIT_TIME = -1; private final Logger _loggerImpl; private final long _logRate; private final Clock _clock; private final AtomicLong _lastLog = new AtomicLong(INIT_TIME); public RateLimitedLogger(Logger loggerImpl, long logRate, Clock clock) { _loggerImpl = loggerImpl; _logRate = logRate; _clock = clock; } @Override public String getName() { return _loggerImpl.getName(); } @Override public boolean isTraceEnabled() { return _loggerImpl.isTraceEnabled(); } @Override public void trace(String msg) { if (logAllowed()) { _loggerImpl.trace(msg); } } @Override public void trace(String format, Object... arguments) { if (logAllowed()) { _loggerImpl.trace(format, arguments); } } @Override public void trace(String msg, Throwable t) { if (logAllowed()) { _loggerImpl.trace(msg, t); } } @Override public void trace(String format, Object obj) { if (logAllowed()) { _loggerImpl.trace(format, obj); } } @Override public void trace(String format, Object obj1, Object obj2) { if (logAllowed()) { _loggerImpl.trace(format, obj1, obj2); } } @Override public boolean isTraceEnabled(Marker marker) { return _loggerImpl.isTraceEnabled(marker); } @Override public void trace(Marker marker, String msg) { if (logAllowed()) { _loggerImpl.trace(marker, msg); } } @Override public void trace(Marker marker, String format, Object arg) { if (logAllowed()) { _loggerImpl.trace(marker, format, arg); } } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { if (logAllowed()) { _loggerImpl.trace(marker, format, arg1, arg2); } } @Override public void trace(Marker marker, String format, Object... arguments) { if (logAllowed()) { _loggerImpl.trace(marker, format, arguments); } } @Override public void trace(Marker marker, String msg, Throwable t) { if (logAllowed()) { _loggerImpl.trace(marker, msg, t); } } @Override public boolean isDebugEnabled() { return _loggerImpl.isDebugEnabled(); } @Override public void debug(String msg) { if (logAllowed()) { _loggerImpl.debug(msg); } } @Override public void debug(String format, Object... arguments) { if (logAllowed()) { _loggerImpl.debug(format, arguments); } } @Override public void debug(String msg, Throwable t) { if (logAllowed()) { _loggerImpl.debug(msg, t); } } @Override public void debug(String format, Object obj) { if (logAllowed()) { _loggerImpl.debug(format, obj); } } @Override public void debug(String format, Object obj1, Object obj2) { if (logAllowed()) { _loggerImpl.debug(format, obj1, obj2); } } @Override public boolean isDebugEnabled(Marker marker) { return _loggerImpl.isDebugEnabled(marker); } @Override public void debug(Marker marker, String msg) { if (logAllowed()) { _loggerImpl.debug(marker, msg); } } @Override public void debug(Marker marker, String format, Object arg) { if (logAllowed()) { _loggerImpl.debug(marker, format, arg); } } @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { if (logAllowed()) { _loggerImpl.debug(marker, format, arg1, arg2); } } @Override public void debug(Marker marker, String format, Object... arguments) { if (logAllowed()) { _loggerImpl.debug(marker, format, arguments); } } @Override public void debug(Marker marker, String msg, Throwable t) { if (logAllowed()) { _loggerImpl.debug(marker, msg, t); } } @Override public boolean isInfoEnabled() { return _loggerImpl.isInfoEnabled(); } @Override public void info(String msg) { if (logAllowed()) { _loggerImpl.info(msg); } } @Override public void info(String format, Object... arguments) { if (logAllowed()) { _loggerImpl.info(format, arguments); } } @Override public void info(String msg, Throwable t) { if (logAllowed()) { _loggerImpl.info(msg, t); } } @Override public void info(String format, Object obj) { if (logAllowed()) { _loggerImpl.info(format, obj); } } @Override public void info(String format, Object obj1, Object obj2) { if (logAllowed()) { _loggerImpl.info(format, obj1, obj2); } } @Override public boolean isInfoEnabled(Marker marker) { return _loggerImpl.isInfoEnabled(marker); } @Override public void info(Marker marker, String msg) { if (logAllowed()) { _loggerImpl.info(marker, msg); } } @Override public void info(Marker marker, String format, Object arg) { if (logAllowed()) { _loggerImpl.info(marker, format, arg); } } @Override public void info(Marker marker, String format, Object arg1, Object arg2) { if (logAllowed()) { _loggerImpl.info(marker, format, arg1, arg2); } } @Override public void info(Marker marker, String format, Object... arguments) { if (logAllowed()) { _loggerImpl.info(marker, format, arguments); } } @Override public void info(Marker marker, String msg, Throwable t) { if (logAllowed()) { _loggerImpl.info(marker, msg, t); } } @Override public boolean isWarnEnabled() { return _loggerImpl.isWarnEnabled(); } @Override public void warn(String msg) { if (logAllowed()) { _loggerImpl.warn(msg); } } @Override public void warn(String format, Object... arguments) { if (logAllowed()) { _loggerImpl.warn(format, arguments); } } @Override public void warn(String msg, Throwable t) { if (logAllowed()) { _loggerImpl.warn(msg, t); } } @Override public void warn(String format, Object obj) { if (logAllowed()) { _loggerImpl.warn(format, obj); } } @Override public void warn(String format, Object obj1, Object obj2) { if (logAllowed()) { _loggerImpl.warn(format, obj1, obj2); } } @Override public boolean isWarnEnabled(Marker marker) { return _loggerImpl.isWarnEnabled(marker); } @Override public void warn(Marker marker, String msg) { if (logAllowed()) { _loggerImpl.warn(marker, msg); } } @Override public void warn(Marker marker, String format, Object arg) { if (logAllowed()) { _loggerImpl.warn(marker, format, arg); } } @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { if (logAllowed()) { _loggerImpl.warn(marker, format, arg1, arg2); } } @Override public void warn(Marker marker, String format, Object... arguments) { if (logAllowed()) { _loggerImpl.warn(marker, format, arguments); } } @Override public void warn(Marker marker, String msg, Throwable t) { if (logAllowed()) { _loggerImpl.warn(marker, msg, t); } } @Override public boolean isErrorEnabled() { return _loggerImpl.isErrorEnabled(); } @Override public void error(String msg) { if (logAllowed()) { _loggerImpl.error(msg); } } @Override public void error(String format, Object... arguments) { if (logAllowed()) { _loggerImpl.error(format, arguments); } } @Override public void error(String msg, Throwable t) { if (logAllowed()) { _loggerImpl.error(msg, t); } } @Override public void error(String format, Object obj) { if (logAllowed()) { _loggerImpl.error(format, obj); } } @Override public void error(String format, Object obj1, Object obj2) { if (logAllowed()) { _loggerImpl.error(format, obj1, obj2); } } @Override public boolean isErrorEnabled(Marker marker) { return _loggerImpl.isErrorEnabled(marker); } @Override public void error(Marker marker, String msg) { if (logAllowed()) { _loggerImpl.error(marker, msg); } } @Override public void error(Marker marker, String format, Object arg) { if (logAllowed()) { _loggerImpl.error(marker, format, arg); } } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { if (logAllowed()) { _loggerImpl.error(marker, format, arg1, arg2); } } @Override public void error(Marker marker, String format, Object... arguments) { if (logAllowed()) { _loggerImpl.error(marker, format, arguments); } } @Override public void error(Marker marker, String msg, Throwable t) { if (logAllowed()) { _loggerImpl.error(marker, msg, t); } } private boolean logAllowed() { final long now = _clock.currentTimeMillis(); final long lastLog = _lastLog.get(); return (lastLog == INIT_TIME || now - lastLog >= _logRate) && _lastLog.compareAndSet(lastLog, now); } }
17.497326
106
0.620212
82f3217ea1651d8fdd9ed9f53a537997cee3c89f
446
package org.example.employee_performance_review_api.domain.model.employee.enums; public enum Team { MIDMANAGE("Middle Management"), PUBLICREL("Public Relationships"), QUALASSUR("Quality Assurance"), SALESFLOR("Sales Floor"), SENMANAGE("Senior Management"), TECHSUPPT("Technical Support"); private final String name; Team(String name) { this.name = name; } @Override public String toString() { return name; } }
20.272727
80
0.715247
ccf9ee650a77565bb29d6ccbcad71aea1a30f4a6
3,359
package nl.hinttech.hsleiden.pi.util; import nl.hinttech.hsleiden.pi.beans.ContentDocument; import nl.hinttech.hsleiden.pi.beans.ImageGalleryDocument; import nl.hinttech.hsleiden.pi.beans.Minor; import nl.hinttech.hsleiden.pi.beans.MinutesDocument; import org.hippoecm.hst.content.beans.standard.HippoAsset; import org.hippoecm.hst.content.beans.standard.HippoBean; import org.hippoecm.hst.core.component.HstRequest; import org.hippoecm.hst.core.sitemenu.HstSiteMenu; import org.hippoecm.hst.core.sitemenu.HstSiteMenuItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("unchecked") public class HSLeiden { public static final Logger log = LoggerFactory.getLogger(HSLeiden.class); public static final String NAMESPACE = "intranet"; public static final String NAMESPACE_PREFIX = NAMESPACE + ":"; public static final String TYPE_STUDENT = "student"; public static final String TYPE_EMPLOYEE = "medewerker"; public static final String TYPE_SERVICE = "service"; public static final String METADATA_LABEL_INFO_FOR = "Informatie voor"; public static final String METADATA_LABEL_TRAINING = "Opleiding"; public static final String METADATA_LABEL_DEPARTMENT = "Afdeling"; public static final String VALUELIST_DEPARTMENTS = "afdelingen"; public static final String VALUELIST_TRAININGS = "opleidingen"; public static final String PAGE_NOT_FOUND = "/pagenotfound"; public static final String KEY_HOME_WELCOME = "home.welkom"; public static final String PATH_WEBSITE_TEXTS_DOCUMENT = "admin/website-teksten-en-labels"; public static final String PATH_WEBSITE_SETTINGS_DOCUMENT = "admin/instellingen"; public static final String KEY_GOOGLE_ANALYTICS_ACCOUNTID = "google.analytics.accountid"; public static final String KEY_CMS_URL = "cms.url"; private static Class<? extends HippoBean>[] searchableClasses; private static Class<? extends HippoBean>[] browsableClasses; static { searchableClasses = new Class[5]; searchableClasses[0] = ContentDocument.class; searchableClasses[1] = MinutesDocument.class; searchableClasses[2] = ImageGalleryDocument.class; searchableClasses[3] = HippoAsset.class; searchableClasses[4] = Minor.class; browsableClasses = new Class[3]; browsableClasses[0] = ContentDocument.class; browsableClasses[1] = MinutesDocument.class; browsableClasses[2] = ImageGalleryDocument.class; } public static Class<? extends HippoBean>[] getSearchableClasses() { return searchableClasses; } public static Class<? extends HippoBean>[] getBrowsableClasses() { return browsableClasses; } public static void rememberActiveMenu(final HstRequest request) { request.getSession().setAttribute("activeMenu", getActiveMenu(request)); } public static HstSiteMenuItem getActiveMenu(final HstRequest request) { HstSiteMenu mainMenu = request.getRequestContext().getHstSiteMenus().getSiteMenu("main"); return mainMenu.getSelectSiteMenuItem(); } public static HstSiteMenuItem getRememberedActiveMenu(final HstRequest request) { return (HstSiteMenuItem) request.getSession().getAttribute("activeMenu"); } }
37.741573
97
0.736231
1de1aa4cbbb1a4eedc13df7c1dff454d239b5f0b
2,815
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class VisualPresentacio { private JTextArea compressorDescompressorPROP2019TextArea; private JTextArea escullLaFuncionalitatQueTextArea; private JButton descomprimirButton; private JButton sortirButton; private JButton comprimirButton; private JPanel Panel; private JTextArea sergiCurtoEfrenCarlesTextArea; private JButton mostrarEstadístiquesButton; private JButton obrirComprimitButton; private static JFrame frame; public static void main(String[] args) { frame = new JFrame("VisualPresentacio"); frame.setContentPane(new VisualPresentacio().Panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void CloseScreen() { //frame.setVisible(false); frame.dispose(); } public VisualPresentacio() { comprimirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { System.out.println("Comprimir"); //Va cap a ComprimirVisual //this.setVisible(false); ComprimirVisual cv = new ComprimirVisual(); cv.NewScreen(0); CloseScreen(); } }); descomprimirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { System.out.println("Descomprimir"); ComprimirVisual cv = new ComprimirVisual(); cv.NewScreen(1); CloseScreen(); } }); sortirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { System.out.println("Sortir"); System.exit(0); } }); mostrarEstadístiquesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { System.out.println("Mostra Estadístiques"); MostrarEstadistiquesVisual m = new MostrarEstadistiquesVisual(); m.NewScreen(); CloseScreen(); } }); obrirComprimitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { ObrirVisual o = new ObrirVisual(); o.NewScreen(); CloseScreen(); } }); } }
34.753086
81
0.588277
b46b8e36cc8c9e82dc8f69be35e93a0d49bd4c07
1,215
/* * Copyright 2002-2016 Jalal Kiswani. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jk.web.faces.components.layouts; import javax.faces.component.FacesComponent; import com.jk.util.annotations.Author; // TODO: Auto-generated Javadoc /** * <B>UIFields</B> is a UIRegion that manages the layout of its child fields * components. * <P/> * * @author Jalal H. Kiswani * @version 1.0 * @see UIAbstractRegion */ @Author(name = "Jalal Kiswani", date = "26/8/2014", version = "1.0") @FacesComponent(value = UIFields.COMPONENT_TYPE) public class UIFields extends UIAbstractRegion { /** The Constant COMPONENT_TYPE. */ public static final String COMPONENT_TYPE = "jk.layout.fields"; }
31.153846
76
0.734979
e1be541aedef59141ac18d2fcebf42762e77b317
1,138
package app.sctp.targeting.viewmodels; import android.app.Application; import androidx.annotation.NonNull; import java.util.List; import app.sctp.persistence.BaseViewModel; import app.sctp.persistence.ObservableDatabaseCall; import app.sctp.targeting.models.GeoLocation; import app.sctp.targeting.models.LocationType; import app.sctp.targeting.repositories.LocationRepository; import io.reactivex.Flowable; public class LocationViewModel extends BaseViewModel { private final LocationRepository locationRepository; public LocationViewModel(@NonNull Application application) { super(application); locationRepository = getRepository(LocationRepository.class); } public Flowable<List<GeoLocation>> getSubLocationsByParentCode(Long parentCode){ return locationRepository.getLocationsByParentCode(parentCode); } public void save(List<GeoLocation> locations){ locationRepository.save(locations); } public ObservableDatabaseCall<List<GeoLocation>> getLocationsByType(LocationType locationType) { return locationRepository.getLocationsByType(locationType); } }
31.611111
100
0.792619
724a49c31e1499420d570470931e4204ad88076b
1,176
/** * * Class TransitionFactory$Class.java * * Generated by KMFStudio at 09 March 2004 11:42:36 * Visit http://www.cs.ukc.ac.uk/kmf * */ package edoc.ECA.CCA; public class TransitionFactory$Class extends edoc.EdocFactory$Class implements TransitionFactory { /** Default factory constructor */ public TransitionFactory$Class() { } public TransitionFactory$Class(edoc.repository.EdocRepository repository) { this.repository = repository; } /** Default build method */ public Object build() { Transition obj = new Transition$Class(); obj.setId(edoc.EdocFactory$Class.newId()); repository.addElement("edoc.ECA.CCA.Transition", obj); return obj; } /** Specialized build method */ public Object build(edoc.ECA.CCA.Status precondition) { Transition obj = new Transition$Class(precondition); obj.setId(edoc.EdocFactory$Class.newId()); repository.addElement("edoc.ECA.CCA.Transition", obj); return obj; } /** Override toString method */ public String toString() { return "TransitionFactory"; } /** Accept 'edoc.ECA.CCA.TransitionVisitor' */ public Object accept(edoc.EdocVisitor v, Object data) { return v.visit(this, data); } }
24.5
76
0.721939
80c36b73c958963e14ec56f53916840c5b199e73
2,547
package org.camunda.platform.runtime.example; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.camunda.bpm.client.spring.annotation.ExternalTaskSubscription; import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskHandler; import org.camunda.bpm.client.task.ExternalTaskService; import org.springframework.stereotype.Component; @Component @ExternalTaskSubscription("Start-Instance-Message") // create a subscription for this topic name public class NewInstanceMessage implements ExternalTaskHandler { @Override public void execute(ExternalTask externalTask, ExternalTaskService externalTaskService) { String messageName = "AutomateOptimize"; String userName = externalTask.getVariable("username"); String password = externalTask.getVariable("password"); String processDef= externalTask.getVariable("processDef"); Long requiredInstanceCount = externalTask.getVariable("requiredInstanceCount"); Unirest.setTimeouts(0, 0); try { String body = "{\r\n \"messageName\":\"" + messageName + "\"\r\n ,\r\n " + " \"processVariables\": {\r\n \"username\": {\r\n \"value\": \"" + userName + "\",\r\n \"type\": \"String\"\r\n },\r\n " + " \"password\": {\r\n \"value\": \""+ password +"\",\r\n \"type\": \"String\"\r\n " + "}," + "\r\n " + " \"requiredInstanceCount\": {\r\n \"value\": \""+requiredInstanceCount +"\",\r\n " + "\"type\": \"Long\"\r\n " + " " + "}," + "\r\n " + " \"processDef\": {\r\n \"value\": \""+processDef +"\",\r\n \"type\": \"String\"\r\n " + " " + "}\r\n }\r\n}"; System.out.println("Request body: "+ body); HttpResponse<String> response = Unirest.post("http://localhost:8080/engine-rest/message") .header("Content-Type", "application/json") .body(body) .asString(); } catch (UnirestException e) { e.printStackTrace(); } externalTaskService.complete(externalTask); } }
40.428571
159
0.571653
59a49cbc8beea5cca9f75f72d1f6faa3ca00c2e5
173
package promise.model.function; import promise.model.List; /** * Created on 7/5/18 by yoctopus. */ public interface ReduceFunction<K, T> { K reduce(List<T> list); }
15.727273
39
0.687861
d5f99030851a03b6b23449f92c86274ded3db3a3
711
package book.chapter05.$5_4_2; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CountDownLatch; public class Recipes_NoLock { public static void main(String[] args) throws Exception { final CountDownLatch down = new CountDownLatch(1); for(int i = 0; i < 10; i++){ new Thread(new Runnable() { public void run() { try { System.out.println("================"); down.await(); } catch ( Exception e ) { } SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS"); String orderNo = sdf.format(new Date()); System.err.println("生成的订单号是 : "+orderNo); } }).start(); } down.countDown(); } }
27.346154
66
0.610408
8001c41afa3482f5f25be9bf77411b1eb95490d7
2,976
package com.nitya.accounter.web.client.core.reports; import java.io.Serializable; import com.google.gwt.user.client.rpc.IsSerializable; import com.nitya.accounter.web.client.core.ClientFinanceDate; public class ReverseChargeListDetail extends BaseReport implements IsSerializable, Serializable { /** * */ private static final long serialVersionUID = 1L; long transactionId; String customerName; int transactionType; ClientFinanceDate date; String number; String name; String memo; double amount; double salesPrice; boolean isPercentage; public ReverseChargeListDetail() { } /** * @return the transactionId */ public long getTransactionId() { return transactionId; } /** * @param transactionId * the transactionId to set */ public void setTransactionId(long transactionId) { this.transactionId = transactionId; } /** * @return the customerName */ public String getCustomerName() { return customerName; } /** * @param customerName * the customerName to set */ public void setCustomerName(String customerName) { this.customerName = customerName; } /** * @return the transactionType */ public int getTransactionType() { return transactionType; } /** * @param transactionType * the transactionType to set */ public void setTransactionType(int transactionType) { this.transactionType = transactionType; } /** * @return the date */ public ClientFinanceDate getDate() { return date; } /** * @param date * the date to set */ public void setDate(ClientFinanceDate date) { this.date = date; } /** * @return the number */ public String getNumber() { return number; } /** * @param number * the number to set */ public void setNumber(String number) { this.number = number; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the memo */ public String getMemo() { return memo; } /** * @param memo * the memo to set */ public void setMemo(String memo) { this.memo = memo; } /** * @return the amount */ public double getAmount() { return amount; } /** * @param amount * the amount to set */ public void setAmount(double amount) { this.amount = amount; } /** * @return the salesPrice */ public double getSalesPrice() { return salesPrice; } /** * @param salesPrice * the salesPrice to set */ public void setSalesPrice(double salesPrice) { this.salesPrice = salesPrice; } /** * @return the isPercentage */ public boolean isPercentage() { return isPercentage; } /** * @param isPercentage * the isPercentage to set */ public void setPercentage(boolean isPercentage) { this.isPercentage = isPercentage; } }
15.663158
66
0.644489
7d9171a2de79976642a16c7090ec23bba7b9d3ad
516
package io.seata.samples.integration.storage; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement public class StorageExampleApplication { public static void main(String[] args) { SpringApplication.run(StorageExampleApplication.class, args); } }
27.157895
78
0.829457
daabd0694086304bc70075c38951525603a7f1f8
9,372
package bin; import bin.BattleElements.Attacks.*; import bin.BattleElements.Enemy; import bin.BattleElements.Item; import bin.BattleElements.Weapon; import bin.Events.*; import bin.OverWorldElements.WorldMap; import javax.swing.*; import java.awt.*; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Loads all the basic Maps, Weapons, Items, Events, and enemies, so that they may be accessed from * anywhere in the program. */ public final class Load { // Stored in hashmaps, so that objects can be retrieves with just their name (easier with file IO) private static HashMap<String, WorldMap> maps; private static HashMap<String, Weapon> weapons; private static HashMap<String, Item> items; private static HashMap<String, EventState> events; private static HashMap<String, Enemy> enemies; public static HashMap<String, Attack> possibleAttacks; public static int wizardsKilled = 0; // called in the beginning to populate maps public static void init(Player player){ loadAttacks(); loadItems(); loadEnemies(player); loadMaps(player); loadWeapons(); loadEvents(player); } //The map loads its own components with just its name public static void loadMaps(Player player){ maps = new HashMap<String, WorldMap>(); try { Scanner mapReader = new Scanner(new BufferedReader(new FileReader("src\\resources\\Backgrounds\\Maps.txt"))); for(int i = mapReader.nextInt(); i > 0; i--){ String name = mapReader.next(); maps.put(name, new WorldMap(name, player)); } } catch(IOException e){ System.out.println(e.toString()); } } //Events are manually loaded and assigned to a map public static void loadEvents(Player player){ events = new HashMap<>(); events.put("Forest", new E1_Knight_Attack(player)); events.put("Town2", new E2_Enter_House_Warning(player)); events.put("House24", new E3_Knight_Bullied(player)); events.put("OutsideCastle", new E4_Beast_Attack(player)); events.put("Castle", new E5_Royal_Attack(player)); events.put("Boss", new E6_Final_Boss(player)); for(String map:events.keySet()){ maps.get(map).setMapEvent(events.get(map)); } } //Items are loaded from a TextFile, containing all the critical Info public static void loadItems(){ items = new HashMap<>(); try { Scanner itemReader = new Scanner(new BufferedReader(new FileReader("src\\resources\\TextFiles\\Items.txt"))); int numItems = Integer.valueOf(itemReader.nextLine()); for(int i = 0; i < numItems; i++){ String[] properties = itemReader.nextLine().split(","); String name = properties[0]; int hpRestoration = Integer.valueOf(properties[1]); int cost = Integer.valueOf(properties[2]); String description = properties[3]; items.put(name, (new Item(name,hpRestoration,cost,description))); } } catch(IOException e){ System.out.println(e.toString()); } } //Weapons are loaded from a TextFile, containing all the critical Info public static void loadWeapons(){ weapons = new HashMap<>(); try { Scanner weaponReader = new Scanner(new BufferedReader(new FileReader("src\\resources\\TextFiles\\Weapons.txt"))); int numWeapons = Integer.valueOf(weaponReader.nextLine()); for(int i = 0; i < numWeapons; i++){ String[] properties = weaponReader.nextLine().split(","); String name = properties[0]; String description = properties[1]; int cost = Integer.valueOf(properties[2]); int strength = Integer.valueOf(properties[3]); int numHits = Integer.valueOf(properties[4]); int speed = Integer.valueOf(properties[5]); int hitInterval = Integer.valueOf(properties[6]); int type = Integer.valueOf(properties[7]); int spriteType = Integer.valueOf(properties[8]); weapons.put(name, (new Weapon(name,description,cost,strength,numHits,speed,hitInterval,type,spriteType))); } } catch(IOException e){ System.out.println(e.toString()); } } public static void loadAttacks(){ possibleAttacks = new HashMap<>(); String[] attackNames = new String[]{"Big Bounce","Blizzard","Bounce","Breaking Ice","Easy Feather Fall", "Easy Slime Bounce", "Easy Slime Rain", "Easy Wing Slash", "Hard Feather Fall", "Hard Slime Bounce", "Hard Slime Rain", "Hard Wing Slash", "Juggling Balls", "Lava Evade", "Quick Slash", "Rotating Pillars", "Shield Bash", "Shoot Player", "Sinusoidal Fire", "Smooth Fire Attack", "Swirling Agony", "Sword Rain","Shooting Star"}; Attack[] attacks = new Attack[]{new BigBounce(), new Blizzard(), new Bounce(), new BreakingIce(), new EasyFeatherFall(), new EasySlimeBounce(), new EasySlimeRain(), new EasyWingSlash(), new HardFeatherFall(), new HardSlimeBounce(), new HardSlimeRain(), new HardWingSlash(), new JugglingBalls(), new LavaEvade(), new QuickSlash(), new RotatingPillars(), new SheildBash(), new ShootPlayer(), new SinusoidalFire(), new SmoothFireAttack(), new SwirlingAgony(), new SwordRain(),new ShootingStar()}; for(int i = 0; i < attackNames.length; i++){ possibleAttacks.put(attackNames[i],attacks[i]); } } //Enemies are loaded manually, and they load their own sprites/attack sprites. public static void loadEnemies(Player player){ enemies = new HashMap<>(); String[] allEnemyNames = new String[]{"Bird", "Boss", "Corrupted Knight", "Dinosaur", "Fire Wizard", "Guard Knight", "Ice Wizard", "King", "Knight", "Slime"}; /** Text File Format Goes * Name * Hp * Boss or not * Attack # * Name of Attacks * Dialogue Lines * Actual Dialogue */ try { for (String enemyName : allEnemyNames) { Scanner enemyReader = new Scanner(new BufferedReader(new FileReader( "src\\resources\\Enemies\\" + enemyName + "\\data.txt"))); int types = Integer.parseInt(enemyReader.nextLine()); for(int type = 0; type < types;type++) { String name = enemyReader.nextLine(); int hp = Integer.parseInt(enemyReader.nextLine()); boolean isBoss = enemyReader.nextLine().equals("BOSS"); ArrayList<Attack> enemyAttacks = new ArrayList<>(); int numAttacks = Integer.parseInt(enemyReader.nextLine()); for (int i = 0; i < numAttacks; i++) { String attackname = enemyReader.nextLine(); enemyAttacks.add(possibleAttacks.get(attackname)); } int dialogueNum = Integer.parseInt(enemyReader.nextLine()); String[] dialogue = new String[dialogueNum]; for (int j = 0; j < dialogueNum; j++) { dialogue[j] = enemyReader.nextLine(); } TextBoxState enemyDialogue = new TextBoxState(player, StateType.TextBox, dialogue, Color.white, Color.black, Color.white, 25, 400, 550, 80, 22); Image sprite = new ImageIcon("src\\resources\\Enemies\\" + enemyName + "\\sprite.png").getImage(); enemies.put(name, new Enemy(name, hp, isBoss, enemyAttacks, enemyDialogue, sprite)); } } } catch (FileNotFoundException e){ System.out.println(e.getLocalizedMessage()); } } public static WorldMap getMap(String mapName){ return maps.get(mapName); } public static Item getItem(String itemName) { return items.get(itemName); } public static Weapon getWeapon(String weaponName) { return weapons.get(weaponName); } public static EventState getEvent(String mapName){ return events.get(mapName); } public static ArrayList<Item> getBuyableItems(){ ArrayList<Item>itemsList = new ArrayList<>(); itemsList.addAll(items.values()); return itemsList; } public static ArrayList<Weapon> getBuyableWeapons(){ ArrayList<Weapon>itemsList = new ArrayList<>(); itemsList.addAll(weapons.values()); itemsList.remove(weapons.get("???")); //Special Item given later on return itemsList; } public static Enemy getEnemy(String enemyName){ return enemies.get(enemyName); } }
43.18894
143
0.580666
2f01b44b678f5b3ee6fcc319bfefaaa0bf8d9dee
2,918
/* * Copyright 2019 Insurance Australia Group Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mark59.datahunter.data.beans; import java.sql.Timestamp; /** * @author Philip Webb * Written: Australian Winter 2019 */ public class Policies { String application; String identifier; String lifecycle; String useability; String otherdata; Timestamp created; Timestamp updated; Long epochtime; public Policies() { } /** * convenience constructor mainly intended for use during internal testing. */ public Policies( String application, String identifier, String lifecycle, String useability, String otherdata, Long epochtime ) { this.application = application; this.identifier = identifier; this.lifecycle = lifecycle; this.useability = useability; this.otherdata = otherdata; this.epochtime = epochtime; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getLifecycle() { return lifecycle; } public void setLifecycle(String lifecycle) { this.lifecycle = lifecycle; } public String getUseability() { return useability; } public void setUseability(String useability) { this.useability = useability; } public String getOtherdata() { return otherdata; } public void setOtherdata(String otherdata) { this.otherdata = otherdata; } public Timestamp getCreated() { return created; } public void setCreated(Timestamp created) { this.created = created; } public Timestamp getUpdated() { return updated; } public void setUpdated(Timestamp updated) { this.updated = updated; } public Long getEpochtime() { return epochtime; } public void setEpochtime(Long epochtime) { this.epochtime = epochtime; } @Override public String toString() { return "[application="+ application + ", identifier="+ identifier + ", lifecycle="+ lifecycle + ", useability="+ useability + ", otherdata="+ otherdata + ", created="+ created + ", updated="+ updated + ", epochtime="+ epochtime + "]"; } }
20.124138
132
0.683687
3d211bdba2746c325bf4e429a4157981cbb663f3
834
/** * */ package hu.hw.cloud.client.fro.config.hotel; import com.gwtplatform.mvp.client.gin.AbstractPresenterModule; import hu.hw.cloud.client.fro.browser.hotel.HotelBrowserModule; import hu.hw.cloud.client.fro.browser.marketgroup.MarketGroupBrowserModule; import hu.hw.cloud.client.fro.browser.room.RoomBrowserModule; import hu.hw.cloud.client.fro.browser.roomtype.RoomTypeBrowserModule; /** * @author robi * */ public class HotelConfigModule extends AbstractPresenterModule { @Override protected void configure() { install(new HotelBrowserModule()); install(new RoomTypeBrowserModule()); install(new RoomBrowserModule()); install(new MarketGroupBrowserModule()); bindPresenter(HotelConfigPresenter.class, HotelConfigPresenter.MyView.class, HotelConfigView.class, HotelConfigPresenter.MyProxy.class); } }
27.8
101
0.793765
5ed31c6125ef13f16b139e917b2f97273405ac5d
2,696
package br.com.negocieweb.dashboard.operation; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import br.com.negocieweb.dashboard.PortfolioService; import br.com.negocieweb.dashboard.UserModel; import br.com.negocieweb.dashboard.UserService; @Controller public class OperationController { private static final String OPERATIONS_URL = "/acoes"; private static final String OPERATIONS_TPL = "/acoes"; private static final String OPERATION_TPL = "/acao"; @Autowired private UserService userService; @Autowired private PortfolioService portfolioService; @Autowired private OperationService operationService; @RequestMapping(value = { OPERATIONS_URL }, method = RequestMethod.GET) public ModelAndView operations(Principal principal, @RequestParam(value = "dei", defaultValue = "") String uploadDateStart, @RequestParam(value = "def", defaultValue = "") String uploadDateEnd, @RequestParam(value = "dvi", defaultValue = "") String expiryDateStart, @RequestParam(value = "dvf", defaultValue = "") String expiryDateEnd, @RequestParam(value = "car", defaultValue = "0") Integer portfolioId) { ModelAndView mv = new ModelAndView(OPERATIONS_TPL); UserModel user = userService.getUserDetails(principal.getName()); Integer clientId = user.getClientId(); mv.addObject("user", user); mv.addObject("portfolios", portfolioService.getPortfolios(clientId)); mv.addObject("operations", operationService.getOperations(clientId, uploadDateStart, uploadDateEnd, expiryDateStart, expiryDateEnd, portfolioId)); return mv; } @RequestMapping(value = { OPERATIONS_URL + "/{operationId}" }) public ModelAndView operation(Principal principal, @PathVariable Integer operationId) { ModelAndView mv = new ModelAndView(OPERATION_TPL); UserModel user = userService.getUserDetails(principal.getName()); Integer clientId = user.getClientId(); mv.addObject("user", user); mv.addObject("operationId", operationId); mv.addObject("operation", operationService.getOperationDetails(operationId, clientId)); return mv; } }
43.483871
108
0.715875
f39ae1cffef4573e9bd2d513fb4f2e4ebba3e69a
1,448
package io.searchbox.core; import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode; import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner; import io.searchbox.Action; import io.searchbox.client.JestResult; import io.searchbox.common.AbstractIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import static junit.framework.Assert.*; /** * @author Dogukan Sonmez */ @RunWith(ElasticsearchRunner.class) @ElasticsearchNode public class MoreLikeThisIntegrationTest extends AbstractIntegrationTest { @Test public void moreLikeThis() { try { executeTestCase(new MoreLikeThis.Builder("1").index("twitter").type("tweet").build()); } catch (Exception e) { fail("Failed during the MoreLikeThis with valid parameters. Exception:" + e.getMessage()); } } @Test public void moreLikeThisWithoutQuery() { try { executeTestCase(new MoreLikeThis.Builder("1").index("twitter").type("tweet").build()); } catch (Exception e) { fail("Failed during the MoreLikeThis with valid parameters. Exception:" + e.getMessage()); } } private void executeTestCase(Action action) throws RuntimeException, IOException { JestResult result = client.execute(action); assertNotNull(result); assertFalse(result.isSucceeded()); } }
30.166667
102
0.703039
6d2fd8379713939e5ab3e8513a572636965bccff
13,077
package com.lorengie.Interface; /* * 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. */ /** * * @author ASUS_ */ public class IntDeliveryRegister extends javax.swing.JFrame { /** * Creates new form Interfaz5 */ public IntDeliveryRegister() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnlDeliveryRegister = new javax.swing.JPanel(); lblDelReg = new javax.swing.JLabel(); lblDateTime = new javax.swing.JLabel(); lblDelAdd = new javax.swing.JLabel(); lblNameRec = new javax.swing.JLabel(); btnRegDel = new javax.swing.JButton(); txtDateTime = new javax.swing.JTextField(); txtDelAdd = new javax.swing.JTextField(); txtNameRec = new javax.swing.JTextField(); pnlDelivery = new javax.swing.JPanel(); jspDelReg = new javax.swing.JScrollPane(); tblDelReg = new javax.swing.JTable(); lblNameRec1 = new javax.swing.JLabel(); txtNameRec1 = new javax.swing.JTextField(); btnHome = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); pnlDeliveryRegister.setBackground(new java.awt.Color(204, 204, 255)); lblDelReg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cooltext165385488635741.png"))); // NOI18N lblDateTime.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblDateTime.setText("Date and Time"); lblDelAdd.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblDelAdd.setText("Delivery address"); lblNameRec.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblNameRec.setText("Name of the recipient"); btnRegDel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btnRegDel.setText("Register delivery"); tblDelReg.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Date and Time", "Delivery address", "Name of the recipient", "Cel" } )); jspDelReg.setViewportView(tblDelReg); javax.swing.GroupLayout pnlDeliveryLayout = new javax.swing.GroupLayout(pnlDelivery); pnlDelivery.setLayout(pnlDeliveryLayout); pnlDeliveryLayout.setHorizontalGroup( pnlDeliveryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryLayout.createSequentialGroup() .addContainerGap() .addComponent(jspDelReg, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); pnlDeliveryLayout.setVerticalGroup( pnlDeliveryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryLayout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jspDelReg, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(43, Short.MAX_VALUE)) ); lblNameRec1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblNameRec1.setText("Telephone number"); txtNameRec1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameRec1ActionPerformed(evt); } }); btnHome.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btnHome.setText("Home"); javax.swing.GroupLayout pnlDeliveryRegisterLayout = new javax.swing.GroupLayout(pnlDeliveryRegister); pnlDeliveryRegister.setLayout(pnlDeliveryRegisterLayout); pnlDeliveryRegisterLayout.setHorizontalGroup( pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblNameRec) .addComponent(lblDelAdd) .addComponent(lblDateTime) .addComponent(lblNameRec1)) .addGap(18, 18, 18) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtNameRec, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE) .addComponent(txtDelAdd, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtDateTime, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtNameRec1)) .addGap(39, 39, 39) .addComponent(pnlDelivery, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addGap(100, 100, 100) .addComponent(btnRegDel) .addGap(0, 548, Short.MAX_VALUE))) .addContainerGap()) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addContainerGap() .addComponent(btnHome) .addGap(41, 41, 41) .addComponent(lblDelReg) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnlDeliveryRegisterLayout.setVerticalGroup( pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDelReg) .addComponent(btnHome)) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDateTime) .addComponent(txtDateTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDelAdd) .addComponent(txtDelAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNameRec) .addComponent(txtNameRec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(pnlDeliveryRegisterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNameRec1) .addComponent(txtNameRec1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(pnlDeliveryRegisterLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(pnlDelivery, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE) .addComponent(btnRegDel) .addGap(63, 63, 63)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(pnlDeliveryRegister, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(pnlDeliveryRegister, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtNameRec1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameRec1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNameRec1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(IntDeliveryRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IntDeliveryRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IntDeliveryRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IntDeliveryRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new IntDeliveryRegister().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnHome; private javax.swing.JButton btnRegDel; private javax.swing.JScrollPane jspDelReg; private javax.swing.JLabel lblDateTime; private javax.swing.JLabel lblDelAdd; private javax.swing.JLabel lblDelReg; private javax.swing.JLabel lblNameRec; private javax.swing.JLabel lblNameRec1; private javax.swing.JPanel pnlDelivery; private javax.swing.JPanel pnlDeliveryRegister; private javax.swing.JTable tblDelReg; private javax.swing.JTextField txtDateTime; private javax.swing.JTextField txtDelAdd; private javax.swing.JTextField txtNameRec; private javax.swing.JTextField txtNameRec1; // End of variables declaration//GEN-END:variables }
52.308
174
0.644261
3f6f7519655462eade2e8aca0926a88e06a3f7bc
643
package com.jfixby.scarabei.red.desktop.test; import com.jfixby.scarabei.api.log.L; import com.jfixby.scarabei.api.sys.Sys; import com.jfixby.scarabei.red.desktop.ScarabeiDesktop; public class ThreadJoinTest { public static void main (final String[] args) { ScarabeiDesktop.deploy(); final Object lock = new Object(); for (int i = 0; i < 5; i++) { final long k = i; final Thread t = new Thread() { @Override public void run () { Sys.sleep(1000 * k); L.d("lock.done", k); } }; t.start(); } { Sys.wait(lock); L.d("wait", Sys.SystemTime()); } } }
17.861111
56
0.586314
e44c515689040e9d5d5fd804dd5b0b42e45cb51d
1,271
package io.wizzie.normalizer.base.utils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class ConversionUtilsUnitTest { @Test public void conversionFromStringToLongObjectIsCorrectTest() { String number = "1234567890"; assertEquals(new Long(1234567890L), ConversionUtils.toLong(number)); } @Test public void conversionFromIntegerToLongObjectIsCorrectTest() { int number = 1234567890; assertEquals(new Long(1234567890L), ConversionUtils.toLong(number)); } @Test public void conversionFromLongToLongObjectIsCorrectTest() { long number = 1234567890L; assertEquals(new Long(number), ConversionUtils.toLong(number)); } @Test public void conversionFromDoubleToLongObjectIsCorrectTest() { double number = 1234567890.9; assertEquals(new Long(1234567890L), ConversionUtils.toLong(number)); } @Test public void conversionFromFloatToLongObjectIsCorrectTest() { float number = 123.8f; assertEquals(new Long(123L), ConversionUtils.toLong(number)); } @Test public void notANumberException() { assertNull(ConversionUtils.toLong("ABC")); } }
24.921569
76
0.703383