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
c97c96bb033b483d40af39fce6960a451bbf8c46
7,675
package com.lfgj.task; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.lfgj.product.model.DateAdjust; import com.lfgj.product.model.Product; import com.lfgj.product.util.AdjustCacheUtil; import com.lfgj.product.util.ProductCacheUtil; import com.lfgj.product.util.ProductListCacheUtil; import com.lfgj.util.CommKit; import com.lfgj.util.LfConstant; import com.rrgy.core.constant.ConstConfig; import com.rrgy.core.plugins.dao.Blade; import com.rrgy.core.toolbox.Func; import com.rrgy.core.toolbox.kit.*; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; /** * * @author Administrator * */ public class ProductTask implements Runnable { @Override public void run() { CommKit.display("================ProductTask==============="); try{ init(); }catch(Exception ex){ ex.printStackTrace(); } } public void init(){ Map<String,Product> products = ProductListCacheUtil.init().get(); if(products==null){ Product p = new Product(); p.setStatus(1); List<Product> ps = Blade.create(Product.class).findByTemplate(p); if(ps!=null&&ps.size()>0){ ProductListCacheUtil.init().putList(ps); products = ProductListCacheUtil.init().get(); }else{ return; } CommKit.display("查询数据库-商品数:"+products.size()); } CommKit.display("商品数:"+products.size()); if(products.size()==0){ return; } String dateTime = DateKit.getTime(); long difftime = diffTime(dateTime,"5"); if(difftime>300000){ System.out.println(DateKit.getTime()+" 刷新5分钟线"); initTime(products,"3","5"); CacheKit.put(LfConstant.CACHE_NAME, "5_last_time", dateTime); } long difftime2 = diffTime(dateTime,"30"); if(difftime2>1800000){ System.out.println(DateKit.getTime()+" 刷新30分钟线"); initTime(products,"3","30"); CacheKit.put(LfConstant.CACHE_NAME, "30_last_time", dateTime); } long difftime3 = diffTime(dateTime,"60"); if(difftime3>3600000){ System.out.println(DateKit.getTime()+" 刷新60分钟线"); initTime(products,"3","60"); CacheKit.put(LfConstant.CACHE_NAME, "60_last_time", dateTime); } String url = getUrl(products); if(Func.isEmpty(url)){ return; } CommKit.display("请求URL:"+url); String json = HttpKit.post(url); CommKit.display("返回:"+json); processNew(json,products,url); } private void initTime(Map<String,Product> products,String type,String time){ for(Product p:products.values()){ boolean isTask = CommKit.isTask(p.getCode()); if(isTask){ ProductCacheUtil.init(p.getCode()+"_"+type+"_"+time).clear(); CommKit.fillList(p.getCode(),type,time,0); try { Thread.sleep(LfConstant.time); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void processNew(String json,Map<String,Product> products,String url){ JSONArray jsarr=null; try{ jsarr=JsonKit.parseArray(json); }catch(JSONException ex){ System.out.println(ex.getLocalizedMessage()+":"+json); System.out.println("异常请求:"+url); JSONObject jo = JsonKit.parse(json); String err = jo.getString("errcode"); String msg = jo.getString("errmsg"); if("4009".equals(err)){ String code = msg.split(" ")[0]; ProductListCacheUtil.init().remove(code); } } if(jsarr==null){ return; } CommKit.display("返回商品数:"+jsarr.size()); for(int x =0;x<jsarr.size();x++){ JSONObject jsonobj = (JSONObject) jsarr.get(x); String date = jsonobj.getString("Date"); if(null != date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = sdf.format(new Date(Long.valueOf(date)*1000L)); jsonobj.put("Date", date); } String code = jsonobj.getString("Symbol"); BigDecimal NewPrice = jsonobj.getBigDecimal("NewPrice"); if(NewPrice.floatValue()<=0){ continue; } Product product = products.get(code); if(product.getDiancs()==null){ product.setDiancs(BigDecimal.ZERO); } CommKit.initBei(product.getBei(),jsonobj); initAdjust(product,jsonobj); CommKit.initDecmail(product.getDiancs(),jsonobj); ProductCacheUtil.init(code).putString(date, jsonobj); } } private void initAdjust(Product product,JSONObject jsonobj){ if(product.getAdjust()!=null){ DateAdjust da = AdjustCacheUtil.init(product.getCode()+"_date").getToday(); BigDecimal NewPrice = jsonobj.getBigDecimal("NewPrice"); BigDecimal nNewPrice = NewPrice.add(product.getAdjust()); String price = MathKit.clearZero(nNewPrice); jsonobj.put("NewPrice", price); if(da!=null){ BigDecimal high = jsonobj.getBigDecimal("High"); BigDecimal nHigh = high.add(da.getHigh()); jsonobj.put("High", MathKit.clearZero(nHigh)); BigDecimal low = jsonobj.getBigDecimal("Low"); if(low.floatValue()==0){ JSONObject obj = ProductCacheUtil.init(product.getCode() + "_3").getLine(); low = obj.getBigDecimal("Low"); } if(low.floatValue()!=0){ BigDecimal nLow = low.add(da.getLow()); jsonobj.put("Low", MathKit.clearZero(nLow)); } BigDecimal open = jsonobj.getBigDecimal("Open"); BigDecimal nOpen = open.add(da.getFirst()); jsonobj.put("Open", MathKit.clearZero(nOpen)); BigDecimal lastClose = jsonobj.getBigDecimal("LastClose"); if(lastClose.floatValue()!=0){ BigDecimal nLastClose = lastClose.add(da.getFirst()); jsonobj.put("LastClose", MathKit.clearZero(nLastClose)); } }else{ if(product.getAdjust().floatValue()>0){ BigDecimal high = jsonobj.getBigDecimal("High"); BigDecimal nHigh = high.add(product.getAdjust()); jsonobj.put("High", MathKit.clearZero(nHigh)); } if(product.getAdjust().floatValue()<0){ BigDecimal low = jsonobj.getBigDecimal("Low"); if(low.floatValue()==0){ JSONObject obj = ProductCacheUtil.init(product.getCode() + "_3_5").get(); low = obj.getBigDecimal("Low"); } if(low.floatValue()!=0){ BigDecimal nLow = low.add(product.getAdjust()); jsonobj.put("Low", MathKit.clearZero(nLow)); } } } CommKit.display("调整后:" + product.getCode() + ":" + jsonobj); } } public long diffTime(String dateTime,String fix){ String lastTime = CacheKit.get(LfConstant.CACHE_NAME, fix+"_last_time"); if(Func.isEmpty(lastTime)){ CacheKit.put(LfConstant.CACHE_NAME, fix+"_last_time", dateTime); return -1; } Long stime = DateKit.parseTime(dateTime).getTime(); Long etime = DateKit.parseTime(lastTime).getTime(); long v = stime - etime; return v; } private String getUrl(Map<String,Product> products){ String symbol = ""; for(Product product:products.values()){ if(Func.isEmpty(product.getCode())){ continue; } boolean isTask = CommKit.isTask(product.getCode()); if(!isTask){ continue; } symbol +="," + product.getCode(); } if(!Func.isEmpty(symbol)){ symbol = symbol.substring(1); } if(Func.isEmpty(symbol)){ return null; } String stock = ConstConfig.pool.get("url"); String user = ConstConfig.pool.get("user"); String password = ConstConfig.pool.get("password"); String query = "Date,Symbol,Name,LastClose,Open,High,Low,NewPrice"; // String url = stock+"/stock.php?u="+user+"&p="+password+"&r_type=2&symbol="+symbol+"&query="+query; String url = stock+ "/stock.php?u=" + user + "&p=" + password + "&market=BS&type=stock&symbol=" + symbol + "&column=Date,Symbol,Name,LastClose,Open,High,Low,NewPrice"; return url; } }
29.863813
169
0.661629
bee6f4cbae99420655ae514ac555ace3f95a80db
17,229
package io.bdrc.audit.shell; import io.bdrc.audit.iaudit.*; import io.bdrc.audit.iaudit.message.TestMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; /** * main class for shell. See usage. Must have a -DtestJar='path to jar containing tests' * <p> * The test jar must contain a class named in the /shell.resources file with the key * testDictionaryClassName. * ex: * testDictionaryClassName = TestDictionary * The test dictionary class must expose a public method named getTestDictionary() * which returns a Hashset<String, Class>. * <p> * The tests in the Hashset's values must implement the io.bdrc.am.audit.iaudit.IAudit interface. */ @SuppressWarnings("PlaceholderCountMatchesArgumentCount") public class shell { /* Call with an implementation of audit test library in the classpath or with the -DtestJar:<pathToTestJar> @param args See usage */ /** * Property key to find class name of test dictionary */ private static final String TEST_DICT_PROPERTY_NAME = "testDictionaryClassName"; private static final String TEST_LOGGER_HEADER = "id,test_name,outcome,error_number,error_test,detail_path\n"; // should get thing2 whose name is io.bdrc.am.audit.shell.shell private final static Logger sysLogger = LoggerFactory.getLogger("sys"); // shellLogger.name=shellLogger //("root"); private final static Logger detailLogger = LoggerFactory.getLogger("detailLogger"); //("root"); private final static Logger testResultLogger = LoggerFactory.getLogger("testResultLogger"); private final static int SYS_OK = 0; private final static int SYS_ERR = 1; private static AuditTestLogController testLogController; private final static String defaultPropertyFileName = "shell.properties"; public static void main(String[] args) { List<Integer> allResults = new ArrayList<>(); try { sysLogger.trace("Entering main"); sysLogger.trace("Parsing args"); ArgParser argParser = new ArgParser(args); sysLogger.trace("Resolving properties"); Path resourceFile = resolveResourceFile(defaultPropertyFileName); // TODO: try /shell.properties class // Property loading: // First, /shell.properties // Second, the user properties (defined in the /shell.properties property UserConfigPath) // Third, the command line properties (defined by the -Dprop=value. // If the command line properties contains the UserConfigPath, such as // -DUserConfigPath=someother/path the properties in that path are reloaded. // PropertyManager.PropertyManagerBuilder(). // .toString()) // PropertyManager shellProperties = // PropertyManager.PropertyManagerBuilder().MergeClassResource(defaultPropertyFileName, // shell.class.getClass()) // PropertyManager shellProperties = PropertyManager.PropertyManagerBuilder().MergeResourceFile(resourceFile.toAbsolutePath().toString()) .MergeUserConfig() .MergeProperties(System.getProperties()); // Replaced with class TestJarLoader testJarLoader = new TestJarLoader(); String tdClassName = shellProperties.getPropertyString(TEST_DICT_PROPERTY_NAME); sysLogger.debug("{} value of property :{}:", TEST_DICT_PROPERTY_NAME, tdClassName); Hashtable<String, AuditTestConfig> td = testJarLoader.LoadDictionaryFromProperty("testJar", tdClassName); assert td != null; testLogController = BuildTestLog(argParser); if (argParser.has_Dirlist()) { for (String aTestDir : ResolvePaths(argParser.getDirs())) { sysLogger.debug("arg = {} ", aTestDir); allResults.addAll(RunTestsOnDir(shellProperties, td, aTestDir)); } } // dont force mutually exclusive. Why not do both? if (argParser.getReadStdIn()) { String curLine; try (BufferedReader f = new BufferedReader(new InputStreamReader(System.in))) { while (null != (curLine = f.readLine())) { sysLogger.debug("readLoop got line {} ", curLine); allResults.addAll(RunTestsOnDir(shellProperties, td, curLine)); } } } } catch (Exception e) { System.out.println("Exiting on exception " + e.getMessage()); sysLogger.error(e.toString(), e, "Exiting on Exception", "Fail"); System.exit(SYS_ERR); } Stream<Integer> rs = allResults.stream(); boolean anyFailed = rs.anyMatch(x -> x.equals(Outcome.FAIL)); sysLogger.trace("Exiting any failed {}", anyFailed); System.exit(anyFailed ? SYS_ERR : SYS_OK ); } private static AuditTestLogController BuildTestLog(final ArgParser ap) { AuditTestLogController tlc; String logDir = ap.getLogDirectory(); tlc = new AuditTestLogController(); tlc.setCsvHeader(shell.TEST_LOGGER_HEADER); tlc.setTestResultLogger(shell.testResultLogger.getName()); tlc.setAppenderDirectory(logDir); return tlc; } /** * Set up, run all tests against a folder. * * @param shellProperties environment, used for resolving test arguments * @param testSet dictionary of tests * @param aTestDir test subject * @return If all the tests passed or not */ private static List<Integer> RunTestsOnDir(final PropertyManager shellProperties, final Hashtable<String, AuditTestConfig> testSet, final String aTestDir) throws IOException { // testLogController ctor sets test log folder testLogController.ChangeAppender(BuildTestLogFileName(aTestDir)); List<TestResult> results = new ArrayList<>(); for (String testName : testSet.keySet()) { AuditTestConfig testConfig = testSet.get(testName); // Do we have a value at all? if (testConfig == null) { // sysLogger goes to a csv and a log file, so add the extra parameters. // log4j wont care. String errstr = String.format("No test config found for %s. Contact library provider.", testName); sysLogger.error(errstr, errstr, "Failed"); results.add(new TestResult(Outcome.FAIL,errstr)); continue; } // Is this test an IAuditTest? Class<?> testClass = testConfig.getTestClass(); if (!IAuditTest.class.isAssignableFrom(testClass)) { String errstr = String.format("Test found for %s does not implement IAudit", testName); sysLogger.error(errstr,errstr, "Failed"); results.add(new TestResult(Outcome.FAIL,errstr)); continue; } // sysLogger always runs logger to console, this logs it to file Logger testLogger = LoggerFactory.getLogger(testClass); // descriptive String testDesc = testConfig.getFullName(); // extract the property values the test needs Hashtable<String, String> propertyArgs = ResolveArgNames(testConfig.getArgNames(), shellProperties); results.add(TestOnDirPassed((Class<IAuditTest>) testClass, testLogger, testName, testDesc, propertyArgs, aTestDir)); } if (results.stream().allMatch(TestResult::Passed)) testLogController.RenameLogPass(); else if (results.stream().anyMatch(TestResult::Failed)) testLogController.RenameLogFail(); else if (results.stream().anyMatch(TestResult::Skipped)) testLogController.RenameLogWarn(); // return the outcomes. Don't distinct, someone may want to do stats return results.stream().map(TestResult::getOutcome) .collect(Collectors.toList()); } /** * Create the file out of a parameter and the date, formatted yyyy-mm-dd-hh-mm * Date time pattern should match the formats in log4j2.properties * * @param aTestDir full name of folder */ private static String BuildTestLogFileName(final String aTestDir) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("-yyyy-MM-dd-kk-mm") .withLocale(Locale.getDefault()) .withZone(ZoneId.systemDefault()); String fileDate = dtf.format(Instant.now()); return Paths.get(aTestDir).getFileName().toString() + fileDate + ".csv"; } private static TestResult TestOnDirPassed(final Class<IAuditTest> testClass, final Logger testLogger, final String testName, final String testDesc, final Hashtable<String, String> propertyArgs, final String testDir) { sysLogger.debug("Invoking {}. Params :{}:", testDesc, testDir); TestResult tr = null; try { tr = RunTest(testLogger, testName, testClass, testDir, propertyArgs); // String resultLogFormat = "Result:%10s\tFolder:%20s\tTest:%30s"; String resultLogFormat = "{}\t{}\t\t{}"; String workName = Paths.get(testDir).getFileName().toString(); String testResultLabel ; Integer outcome = tr.getOutcome(); if (outcome.equals(Outcome.SYS_EXC) || outcome.equals(Outcome.FAIL)) { testResultLabel = "Failed"; sysLogger.error(resultLogFormat, testResultLabel, testDir, testDesc); } else if (outcome.equals(Outcome.PASS)) { testResultLabel = "Passed"; sysLogger.info(resultLogFormat, testResultLabel, testDir, testDesc); } else if (outcome.equals(Outcome.NOT_RUN)) { testResultLabel = "Not Run"; sysLogger.warn(resultLogFormat, testResultLabel, testDir, testDesc); } else { testResultLabel = String.format("Unknown result status %d", tr.getOutcome()); sysLogger.error(resultLogFormat, testResultLabel , testDir, testDesc); } // Test result logger doesn't have levels // See testLogController.setSVCFormat above. Provide params for all // headings. In CSV format, first arg is ignored. //"id,test_name,outcome,detail_path,error_number,error_test" testResultLogger.info("ignoredCSV", workName, testDesc, testResultLabel, null, null, testDir); String errorFormat = "{}:{}:{}"; for (TestMessage tm : tr.getErrors()) { if (outcome.equals(Outcome.NOT_RUN) ) { detailLogger.warn(errorFormat, tm.getOutcome().toString(), tm.getMessage(), testDir); } else if (outcome.equals(Outcome.PASS)) { detailLogger.info(errorFormat, tm.getOutcome().toString(), tm.getMessage(), testDir); } else { detailLogger.error(errorFormat, tm.getOutcome().toString(), tm.getMessage(), testDir); } // We don't repeat the first few columns for detailed errors // testResultLogger also has no level. testResultLogger.info("ignoredCSV", null, null, null, tm.getOutcome().toString(), tm.getMessage(), testDir); } } catch (Exception e) { System.out.println(String.format("%s %s", testDir, testClass.getCanonicalName())); e.printStackTrace(); } return tr; } /** * build dictionary of property arguments, pass to each test * * @param argNames collection of properties to find * @param pm property lookup * @return copy of argNames with found values added: argNames[x]+property value */ private static Hashtable<String, String> ResolveArgNames(final List<String> argNames, PropertyManager pm) { Hashtable<String, String> argValues = new Hashtable<>(); argNames.forEach((String t) -> argValues.put(t, pm.getPropertyString(t))); // Add global parameters String errorsAsWarning = pm.getPropertyString("ErrorsAsWarning"); if ((errorsAsWarning != null) && !errorsAsWarning.isEmpty()) { argValues.put("ErrorsAsWarning", errorsAsWarning); } return argValues; } /** * In place replacement of paths with their resolved value * * @param resolveDirs list of paths to resolve * @return entries fully qualified */ private static List<String> ResolvePaths(List<String> resolveDirs) { List<String> outList = new ArrayList<>(); resolveDirs.forEach(z -> outList.add(Paths.get(z).toAbsolutePath().toString())); return outList; } /** * RunTest * Shell to run a test instance, given its class * * @param testLogger Logger for the test. Not the same as the shell logger * @param params array of additional parameters. Caller has to prepare it for each test. (Needs more structure) */ private static TestResult RunTest(Logger testLogger, final String testName, Class<IAuditTest> testClass, Object... params) { String className = testClass.getCanonicalName(); TestResult tr = new TestResult(); try { // All instances are required to have a Logger, String constructor for the shell // Unit tests don't always use it. Constructor<IAuditTest> ctor = testClass.getConstructor(Logger.class, String.class); IAuditTest inst = ctor.newInstance(testLogger,testName); inst.setParams( params); inst.LaunchTest(); tr = inst.getTestResult(); } catch (Exception eek) { testLogger.error(" Exception {} when running test {}", eek, className); tr.setOutcome(Outcome.FAIL); tr.AddError(Outcome.SYS_EXC, eek.toString()); } return tr; } /** * Gets the working directory of the executable * invoke with -DatHome="someDirectorySpec" * if -DatHome not given, looks up environment variable ATHOME * if that's empty, uses "user.dir" */ private static Path resolveResourceFile(String defaultFileName) { String resHome = System.getProperty("atHome"); if ((resHome == null) || resHome.isEmpty()) { sysLogger.debug("resolveResourceFile: atHome empty."); resHome = System.getenv("ATHOME"); sysLogger.debug("resolveResourceFile: getenv ATHOME {}", resHome); } if ((resHome == null) || resHome.isEmpty()) { resHome = System.getProperty("user.dir"); sysLogger.debug("resolveResourceFile: getenv user.dir {}", resHome); } sysLogger.debug("Reshome is {} ", resHome, " is resource home path"); return Paths.get(resHome, defaultFileName); } // /** // * Extract the parameter values from the shell property // * // * @param shellProperties Properties object // * @param testConfig Holds lists os parameters we need // * @return The test's parameters, if they exist in the properties // */ // private static Hashtable<String, String> getTestArgs(final FilePropertyManager shellProperties, final AuditTestConfig testConfig) { // // extract the property values the test needs // Hashtable<String, String> propertyArgs = ResolveArgNames(testConfig.getArgNames(), shellProperties); // // // Add global parameters // String errorsAsWarning = shellProperties.getPropertyString("ErrorsAsWarning"); // if ((errorsAsWarning != null) && !errorsAsWarning.isEmpty()) // { // propertyArgs.put("ErrorsAsWarning", errorsAsWarning); // } // return propertyArgs; // } }
40.160839
137
0.607638
0ab4dbf15980dc2dbfaaabe1ab7279248674f22f
1,211
package com.redescooter.ses.mobile.rps.service.base.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.redescooter.ses.mobile.rps.dao.base.OpeOutWhCombinBMapper; import com.redescooter.ses.mobile.rps.dm.OpeOutWhCombinB; import com.redescooter.ses.mobile.rps.service.base.OpeOutWhCombinBService; import org.springframework.stereotype.Service; import java.util.List; @Service public class OpeOutWhCombinBServiceImpl extends ServiceImpl<OpeOutWhCombinBMapper, OpeOutWhCombinB> implements OpeOutWhCombinBService { @Override public int updateBatch(List<OpeOutWhCombinB> list) { return baseMapper.updateBatch(list); } @Override public int batchInsert(List<OpeOutWhCombinB> list) { return baseMapper.batchInsert(list); } @Override public int insertOrUpdate(OpeOutWhCombinB record) { return baseMapper.insertOrUpdate(record); } @Override public int insertOrUpdateSelective(OpeOutWhCombinB record) { return baseMapper.insertOrUpdateSelective(record); } @Override public int updateBatchSelective(List<OpeOutWhCombinB> list) { return baseMapper.updateBatchSelective(list); } }
28.833333
135
0.766309
c57d6c1a96c2ec5db4259ee61e8742c3ddc5024c
11,800
/* * Copyright (C) 2016 R&D Solutions Ltd. * * 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 io.hawkcd.services.filters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.hawkcd.utilities.deserializers.MaterialDefinitionAdapter; import io.hawkcd.utilities.deserializers.TaskDefinitionAdapter; import io.hawkcd.utilities.deserializers.WsContractDeserializer; import io.hawkcd.model.Entity; import io.hawkcd.model.MaterialDefinition; import io.hawkcd.model.Pipeline; import io.hawkcd.model.PipelineDefinition; import io.hawkcd.model.dto.WsContractDto; import io.hawkcd.model.enums.PermissionScope; import io.hawkcd.model.enums.PermissionType; import io.hawkcd.model.payload.Permission; import io.hawkcd.services.PipelineDefinitionService; import io.hawkcd.services.PipelineService; import io.hawkcd.services.filters.interfaces.IAuthorizationService; import io.hawkcd.services.interfaces.IPipelineDefinitionService; import io.hawkcd.services.interfaces.IPipelineService; import java.util.ArrayList; import java.util.List; import io.hawkcd.model.TaskDefinition; public class PipelineAuthorizationService implements IAuthorizationService { private IPipelineDefinitionService pipelineDefinitionService; private IPipelineService pipelineService; private Gson jsonConverter; private EntityPermissionTypeService entityPermissionTypeService; public PipelineAuthorizationService() { this.pipelineDefinitionService = new PipelineDefinitionService(); this.pipelineService = new PipelineService(); this.jsonConverter = new GsonBuilder() .registerTypeAdapter(WsContractDto.class, new WsContractDeserializer()) .registerTypeAdapter(TaskDefinition.class, new TaskDefinitionAdapter()) .registerTypeAdapter(MaterialDefinition.class, new MaterialDefinitionAdapter()) .create(); this.entityPermissionTypeService = new EntityPermissionTypeService(); } public PipelineAuthorizationService(IPipelineService pipelineService, IPipelineDefinitionService pipelineDefinitionService) { this.pipelineService = pipelineService; this.pipelineDefinitionService = pipelineDefinitionService; this.jsonConverter = new GsonBuilder() .registerTypeAdapter(WsContractDto.class, new WsContractDeserializer()) .registerTypeAdapter(TaskDefinition.class, new TaskDefinitionAdapter()) .registerTypeAdapter(MaterialDefinition.class, new MaterialDefinitionAdapter()) .create(); this.entityPermissionTypeService = new EntityPermissionTypeService(this.pipelineDefinitionService); } @Override public List getAll(List permissions, List pipelines) { List<Entity> result = new ArrayList<>(); for (Pipeline pipeline : (List<Pipeline>) pipelines) { if (this.hasPermissionToRead(permissions, pipeline)) { // PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getObject(); pipeline = this.entityPermissionTypeService.setPermissionTypeToObject(permissions, pipeline); result.add(pipeline); } } return result; } @Override public boolean getById(String entityId, List permissions) { Pipeline pipeline = (Pipeline) this.pipelineService.getById(entityId).getEntity(); // PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getObject(); pipeline = this.entityPermissionTypeService.setPermissionTypeToObject(permissions, pipeline); return this.hasPermissionToRead(permissions, pipeline); } @Override public boolean add(String entity, List permissions) { Pipeline pipeline = this.jsonConverter.fromJson(entity, Pipeline.class); // PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getObject(); pipeline = this.entityPermissionTypeService.setPermissionTypeToObject(permissions, pipeline); return this.hasPermissionToAdd(permissions, pipeline); } @Override public boolean update(String entity, List permissions) { Pipeline pipeline = this.jsonConverter.fromJson(entity, Pipeline.class); // PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getObject(); pipeline = this.entityPermissionTypeService.setPermissionTypeToObject(permissions, pipeline); return this.hasPermissionToUpdateAndDelete(permissions, pipeline); } @Override public boolean delete(String entityId, List permissions) { Pipeline pipeline = (Pipeline) this.pipelineService.getById(entityId).getEntity(); return this.hasPermissionToUpdateAndDelete(permissions, pipeline); } public boolean hasPermissionToRead(List<Permission> permissions, Pipeline pipeline) { PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getEntity(); boolean hasPermission = false; for (Permission permission : permissions) { if ((permission.getPermissionScope() == PermissionScope.SERVER) && (permission.getPermissionType() != PermissionType.NONE)) { hasPermission = true; } else if (permission.getPermittedEntityId().equals(PermissionScope.PIPELINE.toString()) || permission.getPermittedEntityId().equals(PermissionScope.PIPELINE_GROUP.toString())) { if (permission.getPermissionType() == PermissionType.NONE) { hasPermission = false; } else { hasPermission = true; } } else if (pipelineDefinition.getPipelineGroupId() != null) { if (permission.getPermittedEntityId().equals(pipelineDefinition.getPipelineGroupId())) { if (permission.getPermissionType() == PermissionType.NONE) { hasPermission = false; } else { hasPermission = true; } } } if (permission.getPermittedEntityId().equals(pipelineDefinition.getId())) { if (permission.getPermissionType() == PermissionType.NONE) { hasPermission = false; } else { hasPermission = true; return hasPermission; } } } return hasPermission; } public boolean hasPermissionToAdd(List<Permission> permissions, Pipeline pipeline) { PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getEntity(); boolean hasPermission = false; for (Permission permission : permissions) { if ((permission.getPermissionScope() == PermissionScope.SERVER) && ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR))) { hasPermission = true; } else if (permission.getPermittedEntityId().equals(PermissionScope.PIPELINE.toString())) { if ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR)) { hasPermission = true; } else { hasPermission = false; } } else if (permission.getPermittedEntityId().equals(PermissionScope.PIPELINE_GROUP.toString())) { if ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR)) { hasPermission = true; } else { hasPermission = false; } } else if (pipelineDefinition.getPipelineGroupId() != null) { if (permission.getPermittedEntityId().equals(pipelineDefinition.getPipelineGroupId())) { if ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR)) { hasPermission = true; } else { hasPermission = false; } } } if (permission.getPermittedEntityId().equals(pipelineDefinition.getId())) { if ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR)) { hasPermission = true; return hasPermission; } else { hasPermission = false; } } } return hasPermission; } public boolean hasPermissionToUpdateAndDelete(List<Permission> permissions, Pipeline pipeline) { PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(pipeline.getPipelineDefinitionId()).getEntity(); boolean hasPermission = false; for (Permission permission : permissions) { if ((permission.getPermissionScope() == PermissionScope.SERVER) && (permission.getPermissionType() == PermissionType.ADMIN)) { hasPermission = true; } if ((permission.getPermissionScope() == PermissionScope.SERVER) || (permission.getPermissionScope() == PermissionScope.PIPELINE) || (permission.getPermissionScope() == PermissionScope.PIPELINE_GROUP)) { if (permission.getPermissionType() == PermissionType.OPERATOR) { hasPermission = true; } } else if (permission.getPermittedEntityId().equals(PermissionScope.PIPELINE.toString()) || permission.getPermittedEntityId().equals(PermissionScope.PIPELINE_GROUP.toString())) { if (permission.getPermissionType() == PermissionType.ADMIN) { hasPermission = true; } else { hasPermission = false; } } else if (pipelineDefinition.getPipelineGroupId() != null) { if (permission.getPermittedEntityId().equals(pipelineDefinition.getPipelineGroupId())) { if (permission.getPermissionType() == PermissionType.ADMIN) { hasPermission = true; } else { hasPermission = false; } } } if (permission.getPermittedEntityId().equals(pipelineDefinition.getId())) { if ((permission.getPermissionType() == PermissionType.ADMIN) || (permission.getPermissionType() == PermissionType.OPERATOR)) { hasPermission = true; return hasPermission; } else { hasPermission = false; } } } return hasPermission; } }
51.528384
214
0.665508
550f64dee8b96de84e15d2b1bd65f50459406427
466
package noppes.npcs.constants; public enum EnumAnimation { NONE, SITTING, LYING, SNEAKING, DANCING, AIMING, CRAWLING, HUG, CRY, WAVING, BOW; public int getWalkingAnimation() { if (this == SNEAKING) return 1; if (this == AIMING) return 2; if (this == DANCING) return 3; if (this == CRAWLING) return 4; if (this == HUG) return 5; return 0; } }
21.181818
85
0.517167
d7981606518e00757ba59289d6ec52b3b0986942
977
/** * */ package com.automic.docker.exceptions; /** * Exception class thrown to indicate that error has occurred while processing request. It could * either be * <li> * <ul>Business exception for invalid inputs to Actions</ul> * <ul>Technical exception to denote errors while communicating with Docker API</ul> * </li> * */ public class DockerException extends Exception { private static final long serialVersionUID = -3274150618150755200L; /** * No-args constructor */ public DockerException() { super(); } /** * Constructor to create an instance to wrap an instance of Throwable implementation * @param message * @param cause */ public DockerException(String message, Throwable cause) { super(message, cause); } /** * Constructor that takes an error message * @param message */ public DockerException(String message) { super(message); } }
20.354167
96
0.643808
55952f98c6567864890f77991413e6f6ac92f81e
2,869
package com.mysql.cj.jdbc.jmx; import com.mysql.cj.Messages; import com.mysql.cj.jdbc.ConnectionGroupManager; import com.mysql.cj.jdbc.exceptions.SQLError; import java.lang.management.ManagementFactory; import java.sql.SQLException; import javax.management.MBeanServer; import javax.management.ObjectName; public class LoadBalanceConnectionGroupManager implements LoadBalanceConnectionGroupManagerMBean { private boolean isJmxRegistered = false; public synchronized void registerJmx() throws SQLException { if (this.isJmxRegistered) return; MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = new ObjectName("com.mysql.cj.jdbc.jmx:type=LoadBalanceConnectionGroupManager"); mbs.registerMBean(this, name); this.isJmxRegistered = true; } catch (Exception e) { throw SQLError.createSQLException(Messages.getString("LoadBalanceConnectionGroupManager.0"), null, e, null); } } public void addHost(String group, String host, boolean forExisting) { try { ConnectionGroupManager.addHost(group, host, forExisting); } catch (Exception e) { e.printStackTrace(); } } public int getActiveHostCount(String group) { return ConnectionGroupManager.getActiveHostCount(group); } public long getActiveLogicalConnectionCount(String group) { return ConnectionGroupManager.getActiveLogicalConnectionCount(group); } public long getActivePhysicalConnectionCount(String group) { return ConnectionGroupManager.getActivePhysicalConnectionCount(group); } public int getTotalHostCount(String group) { return ConnectionGroupManager.getTotalHostCount(group); } public long getTotalLogicalConnectionCount(String group) { return ConnectionGroupManager.getTotalLogicalConnectionCount(group); } public long getTotalPhysicalConnectionCount(String group) { return ConnectionGroupManager.getTotalPhysicalConnectionCount(group); } public long getTotalTransactionCount(String group) { return ConnectionGroupManager.getTotalTransactionCount(group); } public void removeHost(String group, String host) throws SQLException { ConnectionGroupManager.removeHost(group, host); } public String getActiveHostsList(String group) { return ConnectionGroupManager.getActiveHostLists(group); } public String getRegisteredConnectionGroups() { return ConnectionGroupManager.getRegisteredConnectionGroups(); } public void stopNewConnectionsToHost(String group, String host) throws SQLException { ConnectionGroupManager.removeHost(group, host); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\jmx\LoadBalanceConnectionGroupManager.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
34.154762
158
0.765075
9027866b8d4c6cef3f6033b215541d3794169f8a
1,711
/* * Copyright 2015-2017 Real Logic Ltd. * * 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 uk.co.real_logic.artio.validation; import uk.co.real_logic.artio.Constants; import uk.co.real_logic.artio.decoder.HeaderDecoder; import uk.co.real_logic.artio.dictionary.CharArraySet; import java.util.Collection; import static uk.co.real_logic.artio.fields.RejectReason.COMPID_PROBLEM; /** * A message validation strategy that checks the sender comp id of each message. */ class SenderCompIdValidationStrategy implements MessageValidationStrategy { private final CharArraySet validSenderIds; SenderCompIdValidationStrategy(final Collection<String> validSenderIds) { this.validSenderIds = new CharArraySet(validSenderIds); } public boolean validate(final HeaderDecoder header) { final char[] senderCompID = header.senderCompID(); final int senderCompIDLength = header.senderCompIDLength(); return validSenderIds.contains(senderCompID, senderCompIDLength); } public int invalidTagId() { return Constants.SENDER_COMP_ID; } public int rejectReason() { return COMPID_PROBLEM.representation(); } }
30.553571
80
0.745178
88795bf772b365316d87cc572d24e56b240e9273
195
// "Annotate property with @JvmField" "true" import a.A; class B { void bar() { A a = A.pro<caret>perty; A a2 = A.Companion.getProperty(); A a3 = A.property; } }
17.727273
44
0.538462
697fc7a5f18670717de6cc853fc12e7fb69abf43
870
package top.nololiyt.yueyinqiu.commandchain.commands.chains; import top.nololiyt.yueyinqiu.commandchain.commands.CommandLayer; import top.nololiyt.yueyinqiu.commandchain.commands.Router; import java.util.LinkedHashMap; import java.util.Map; public class ChainsRouter extends Router { protected final static String layerName = "chains"; @Override public String permissionName() { return layerName; } @Override public String messageKey() { return layerName; } private Map<String, CommandLayer> commandLayers = new LinkedHashMap<String, CommandLayer>() { { put("execute", new ExecuteExecutor()); put("print", new PrintExecutor()); } }; @Override protected Map<String, CommandLayer> nextLayers() { return commandLayers; } }
22.894737
95
0.657471
dd07d53a08a7c9ec82eb9a050a1d8049aea1c77b
1,567
// Copyright 2021 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.commerce; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.chrome.test.ChromeBrowserTestRule; /** * Test for {@link PriceUtils}. */ @RunWith(BaseJUnit4ClassRunner.class) public class PriceUtilsTest { private static final int MICROS_TO_UNITS = 1000000; @Rule public ChromeBrowserTestRule mActivityTestRule = new ChromeBrowserTestRule(); @Test @SmallTest public void testPriceFormatting_lessThanTenUnits() { Assert.assertEquals("$0.50", PriceUtils.formatPrice("USD", MICROS_TO_UNITS / 2)); Assert.assertEquals("$1.00", PriceUtils.formatPrice("USD", MICROS_TO_UNITS)); } @Test @SmallTest public void testPriceFormatting_ZeroUnit() { Assert.assertEquals("$0.00", PriceUtils.formatPrice("USD", 0)); } @Test @SmallTest public void testPriceFormatting_GreaterOrEqualThanTenUnit() { Assert.assertEquals("$10", PriceUtils.formatPrice("USD", 10 * MICROS_TO_UNITS)); Assert.assertEquals("$10", PriceUtils.formatPrice("USD", (long) (10.4 * MICROS_TO_UNITS))); Assert.assertEquals("Should round up.", "$11", PriceUtils.formatPrice("USD", (long) (10.5 * MICROS_TO_UNITS))); } }
32.645833
99
0.714742
5885856a1441e8fed5a6ec51f2681b9da3f171b6
2,354
package com.realscores.mvc.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.util.UriComponentsBuilder; import com.realscores.obj.Round; import com.realscores.service.round.IRoundService; @Controller @RequestMapping("/rounds") public class RoundController { @Autowired IRoundService roundService; @GetMapping() public ResponseEntity<List<Round>> getRounds(){ List<Round> rounds = roundService.getAllRounds(); return new ResponseEntity<List<Round>>(rounds, HttpStatus.OK); } @GetMapping("/{id}") public ResponseEntity<Round> getRoundById( @PathVariable("id") int roundId){ Round round = roundService.getRoundById(roundId); return new ResponseEntity<Round>(round, HttpStatus.OK); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Void> createRound(@RequestBody Round round, UriComponentsBuilder builder){ boolean flag = roundService.addRound(round); if (flag == false) { return new ResponseEntity<Void>(HttpStatus.CONFLICT); } HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/rounds/{id}").buildAndExpand(round.getRoundId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } @PutMapping() public ResponseEntity<Round> updateRound(@RequestBody Round round) { roundService.updateRound(round); return new ResponseEntity<Round>(round, HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteRound(@PathVariable("id") Integer id) { roundService.deleteRound(id); return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } }
35.134328
101
0.784197
850642c94f8436fe3efc7eb42dece279a018139a
316
package com.mwiacek.com.booksapiexample; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Books { // This is in every request. We could save some memory after saving it once public int totalItems; public Book[] items; }
26.333333
80
0.743671
5d3e00eb4ff0895fab4aade43ea03762fb6d7771
6,522
package test.scripts.collectionMetadata; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import spot.pages.CollectionEntryPage; import spot.pages.LoginPage; import spot.pages.StartPage; import spot.pages.admin.AdminHomepage; import spot.pages.admin.CollectionsConfigurationPage; import spot.pages.registered.EditCollectionPage; import spot.pages.registered.Homepage; import spot.pages.registered.NewCollectionPage; import spot.util.TimeStamp; import test.base.BaseSelenium; /** * Test for CRUD metadata (former: additional information) of a collection. * * @author helk * */ public class CollectionMetadataTest extends BaseSelenium{ private AdminHomepage adminHomepage; private Homepage homepage; private CollectionEntryPage currentOpenedCollection; private CollectionsConfigurationPage collectionsConfigurationPage; private String studyType1 = "Test Study Type 1"; private String studyType2 = "Test Study Type 2"; private String studyType3 = "Test Study Type 3"; private String metadataField1 = "Test Metadata Field 1"; private String metadataField2 = "Test Metadata Field 2"; private String metadataAutosuggest1 = "Test Metadata Autosuggest 1"; private String metadataAutosuggest2 = "Test Metadata Autosuggest 2"; private String metadataFieldValue1 = "Test Metadata Field value 1"; private String metadataAutosuggestValue1 = "Test Metadata Autosuggest value 1"; private String collectionTitle = TimeStamp.getTimeStamp() + " Collection with Collection Metadata"; private String collectionDescription = "default description 123 äüö ? (ß) μ å"; @Test(priority = 1) public void loginAdmin() { LoginPage loginPage = new StartPage(driver).openLoginForm(); adminHomepage = loginPage.loginAsAdmin(getPropertyAttribute(adminUsername), getPropertyAttribute(adminPassword)); } @Test(priority = 2) public void configureCollectionMetadata() { collectionsConfigurationPage = adminHomepage.goToAdminPage().goToCollectionsConfigurationPage(); collectionsConfigurationPage.setStudyTypes(studyType1 + "\n" + studyType2 + "\n"+ studyType3); collectionsConfigurationPage.setMetadataFields(metadataField1 + "\n" + metadataField2); collectionsConfigurationPage.setMetadataAutosuggests(metadataAutosuggest1 + "\n" + metadataAutosuggest2); } @Test(priority = 3) public void logoutAdmin() { collectionsConfigurationPage.logout(); } /** * IMJ-1, IMJ-112 */ @Test(priority = 4) public void loginUser() { StartPage startPage = new StartPage(driver); LoginPage loginPage = startPage.openLoginForm(); homepage = loginPage.loginAsNotAdmin(getPropertyAttribute(ruUsername), getPropertyAttribute(ruPassword)); } /** * IMJ-112, IMJ-113, IMJ-83 */ @Test(priority = 5) public void createCollectionWithStudyTypes() { NewCollectionPage newCollectionPage = homepage.goToCreateNewCollectionPage(); currentOpenedCollection = newCollectionPage.createCollection(collectionTitle, collectionDescription, getPropertyAttribute(ruGivenName), getPropertyAttribute(ruFamilyName), getPropertyAttribute(ruOrganizationName), Arrays.asList(studyType1, studyType2)); } /** * IMJ-56 */ @Test(priority = 6) public void uploadItems() { uploadItem("SamplePPTXFile.pptx"); uploadItem("SamplePNGFile.png"); uploadItem("SampleTIFFile.tif"); } //IMJ-131, IMJ-56 private void uploadItem(String title) { currentOpenedCollection = currentOpenedCollection.uploadFile(getFilepath(title)); boolean uploadSuccessful = currentOpenedCollection.findItem(title); Assert.assertTrue(uploadSuccessful, "Item not among uploads."); } @Test(priority = 7) public void addStudyType() { EditCollectionPage editCollection = currentOpenedCollection.editInformation(); editCollection.selectStudyType(studyType3); currentOpenedCollection = editCollection.submitChanges(); } @Test(priority = 8) public void addCollectionMetadata() { EditCollectionPage editCollection = currentOpenedCollection.editInformation(); editCollection.editCollectionMetadata(metadataField1, metadataFieldValue1); currentOpenedCollection = editCollection.submitChanges(); } @Test(priority = 9) public void addStudyContext() { EditCollectionPage editCollection = currentOpenedCollection.editInformation(); editCollection.addAutoSuggestedStudyContext(metadataAutosuggest1, metadataAutosuggestValue1); currentOpenedCollection = editCollection.submitChanges(); } @Test(priority = 10) public void checkMoreInformationsForChanges() { currentOpenedCollection = currentOpenedCollection.openMoreInformation(); boolean studyTypesPresent = currentOpenedCollection.areStudyTypesPresent(Arrays.asList(studyType1, studyType2, studyType3)); boolean collectionMetadataPresent = currentOpenedCollection.isCollectionMetadataPresent(metadataField1, metadataFieldValue1); boolean studyContextPresent = currentOpenedCollection.isCollectionMetadataPresent(metadataAutosuggest1, metadataAutosuggestValue1); Assert.assertTrue(studyTypesPresent, "The study types are not displayed."); Assert.assertTrue(collectionMetadataPresent, "The collection metadata are not displayed."); Assert.assertTrue(studyContextPresent, "The study contexts are not displayed."); } @Test(priority = 11) public void deleteCollection() { currentOpenedCollection = homepage.goToCollectionPage().openCollectionByTitle(collectionTitle); currentOpenedCollection.deleteCollection(); } @Test(priority = 12) public void logoutUser() { StartPage startpage = new StartPage(driver).goToStartPage(); startpage.logout(); } @Test(priority = 13) public void loginAdminAgain() { LoginPage loginPage = new StartPage(driver).openLoginForm(); adminHomepage = loginPage.loginAsAdmin(getPropertyAttribute(adminUsername), getPropertyAttribute(adminPassword)); } @Test(priority = 14) public void clearCollectionMetadata() { collectionsConfigurationPage = adminHomepage.goToAdminPage().goToCollectionsConfigurationPage(); collectionsConfigurationPage.clearStudyTypes(); collectionsConfigurationPage.clearMetadataFields(); collectionsConfigurationPage.clearMetadataAutosuggests(); } /** * IMJ-2 */ @AfterClass public void afterClass() { StartPage startpage = new StartPage(driver).goToStartPage(); startpage.logout(); } }
37.056818
139
0.774149
6f3b9e2339ec753ddc4e1f23a4891dae2fae9ecb
232
package br.com.vandersonsampaio.model.exceptions; public class AgendaNotFoundException extends Exception { public AgendaNotFoundException(String idAgenda) { super("Agenda not found. Agenda code: " + idAgenda); } }
25.777778
60
0.74569
2d09b1c61d36d0c8f62bcfeac9b54927ec46599e
1,526
package com.liquidlabs.log.fields; import com.liquidlabs.common.file.FileUtil; import com.liquidlabs.log.fields.field.LiteralField; import java.io.IOException; import java.util.List; /** * Created by neil on 14/07/2015. */ public class EnhancerCSV { public static void enhance(FieldSet fieldSet) { // open the file to get the first couple of lines out of it to build fields. // set the pattern extractor to "," so it splits the lines. String type = ((LiteralField)fieldSet.getField(FieldSet.DEF_FIELDS._type.name())).getValue(); String filename = ((LiteralField)fieldSet.getField(FieldSet.DEF_FIELDS._path.name())).getValue(); try { List<String> strings = FileUtil.readLines(filename, 10); createIt(fieldSet, filename, strings); } catch (IOException e) { e.printStackTrace(); } } static FieldSet createIt(FieldSet fieldSet, String filename, List<String> strings) { String fieldsString = strings.get(0); String [] fields = null; // if (fieldsString.startsWith("#")) { fields = fieldsString.split(","); // } fieldSet.expression = "split(,)"; fieldSet.fields.remove(0); int group = 1; for (String field : fields) { fieldSet.addField(field.replace("#", "").replace(" ","-").replace("\"","").trim(), "count()", true, group++, true, "","", "", false); } fieldSet.buildFieldNameCache(); return fieldSet; } }
36.333333
145
0.61599
e4b0b9bbbf7d744798262a5034b21ca3bee41bf0
1,018
package org.apache.ibatis.demo.util; import ognl.Ognl; import ognl.OgnlException; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.demo.mapper.MailMapper; import org.apache.ibatis.demo.pojo.Mail; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.StringTokenizer; /** * Created by QDHL on 2018/10/19. * * @author mingqiang ji */ public class Main { public static void main(String[] args) throws NoSuchMethodException { Method paramTest = MailMapper.class.getMethod("paramTest", new Class[]{Integer.class,Integer.class,String.class}); Annotation[][] parameterAnnotations = paramTest.getParameterAnnotations(); System.out.println(parameterAnnotations.length); int count = parameterAnnotations.length; for (int i = 0; i < count; i++) { for (Annotation annotation : parameterAnnotations[i]) { if (annotation instanceof Param) { } } } } }
26.789474
122
0.682711
1c346e9ad92621b58c41441035b563ba38aca7df
1,340
package org.jlab.mya; import org.jlab.mya.event.FloatEvent; import org.jlab.mya.nexus.DataNexus; import org.jlab.mya.nexus.OnDemandNexus; import org.jlab.mya.stream.EventStream; import java.io.IOException; import java.sql.SQLException; import java.time.Instant; /** * * @author slominskir */ public class HelloWorld { /** * Entry point of the application. * * @param args the command line arguments * @throws SQLException If unable to query the SQL database * @throws IOException If unable to stream data */ public static void main(String[] args) throws SQLException, IOException { DataNexus nexus = new OnDemandNexus("history"); for (String name : DataNexus.getDeploymentNames()) { System.out.println(name); } String pv = "R123PMES"; Instant begin = TimeUtil.toLocalDT("2017-01-01T00:00:00.123456"); Instant end = TimeUtil.toLocalDT("2017-01-01T00:01:00.123456"); Metadata<FloatEvent> metadata = nexus.findMetadata(pv, FloatEvent.class); try (EventStream<FloatEvent> stream = nexus.openEventStream(metadata, begin, end)) { FloatEvent event; while ((event = stream.read()) != null) { System.out.println(event.toString(6)); } } } }
26.8
92
0.640299
5fc3e417b01e179a7cc56dc9cbc322a766d04911
132
package resumeonline.commons.si.enums; public interface TypeSymbolByteMultiple { String getSymbol(); String getName(); }
14.666667
41
0.742424
4b54b7cda19f290b4155b99023f4ff813734f97d
677
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package io.github.mmm.property.number; import io.github.mmm.property.WritableProperty; import io.github.mmm.property.object.WritableSimpleProperty; import io.github.mmm.value.observable.number.WritableNumberValue; /** * {@link WritableProperty} with {@link Number} {@link #get() value}. * * @param <N> type of the numeric {@link #get() value}. * * @since 1.0.0 */ public interface WritableNumberProperty<N extends Number & Comparable<? super N>> extends ReadableNumberProperty<N>, WritableSimpleProperty<N>, WritableNumberValue<N> { }
33.85
90
0.741507
b6be72dbd2a816aa3056fd00bf4deefe08a3a88b
2,635
package ru.com.melt.repository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import ru.com.melt.model.Genre; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @DataJpaTest @DirtiesContext public class GenreRepositoryTest { @Autowired private GenreRepository genreRepository; @Autowired private TestEntityManager manager; @Test(expected = NullPointerException.class) public void whenAddGenreNull_thenThrowExc() { // given Genre genre1 = addGenre(null); } @Test public void whenAddTwoGenre_thenReturnList() { // given Genre genre1 = addGenre("genre1"); Genre genre2 = addGenre("genre2"); // when List<Genre> genres = genreRepository.findAll(); // then assertEquals(2, genres.size()); assertEquals("comment text1, comment text2", genres.toString()); } @Test public void whenFindGenreByName_thenNoOk() { // given Genre genre1 = addGenre("genre1"); Genre genre2 = addGenre("genre2"); // when Optional<Genre> optionalGenre = genreRepository.findGenreByGenreName("genre"); // then assertFalse(optionalGenre.isPresent()); } @Test(expected = NoSuchElementException.class) public void whenFindGenreNameIsNull_thenThrowExc() { // given Genre genre1 = addGenre("genre1"); Genre genre2 = addGenre("genre2"); // when Optional<Genre> optionalGenre = genreRepository.findGenreByGenreName(null); // then assertEquals(2, optionalGenre.get()); } @Test public void whenFindGenreByName_thenOk() { // given Genre genre1 = addGenre("genre1"); Genre genre2 = addGenre("genre2"); // when Optional<Genre> optionalGenre = genreRepository.findGenreByGenreName("genre1"); // then assertTrue(optionalGenre.isPresent()); assertEquals("Genre(genreName=genre1)", optionalGenre.get().toString()); } private Genre addGenre(String testName) { Genre genre = new Genre(); genre.setGenreName(testName); return manager.persist(genre); } }
26.616162
87
0.675522
68f982adfe4a20267ba5a482bbd6413559533d32
1,136
package com.banking.svkbanking.entity; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "accountTypes") public class AccountTypes { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "typeId", nullable=false) private Integer typeId; @Column(name = "typeName", nullable=false) private String typeName; public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } @Override public int hashCode() { return Objects.hash(typeId); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AccountTypes other = (AccountTypes) obj; return Objects.equals(typeId, other.typeId); } }
18.933333
52
0.727993
cff7d3570c973c1d8923631cb7d8959e10ab7400
1,203
package com.aek56.atm.material.MYY5_YYTJZCZGGXX; import org.jfpc.framework.helper.EmptyHelper; import org.jfpc.framework.helper.StringHelper; import org.jfpc.framework.support.MyDataBaseObjectSupport; import org.jfpc.framework.support.MyServiceSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; /** 医院添加商品规格信息*/ @Service public class MYY5_YYTJZCZGGXXService extends MyServiceSupport { protected static final Logger logger = LoggerFactory.getLogger(MYY5_YYTJZCZGGXXService.class); public MYY5_YYTJZCZGGXXDao getDao(){ return getMySqlSession().getMapper(MYY5_YYTJZCZGGXXDao.class); } /** * 数据库分表 * @param data */ public void changeTable(MyDataBaseObjectSupport data) { MYY5_YYTJZCZGGXXDBO md = (MYY5_YYTJZCZGGXXDBO)data; if(EmptyHelper.isEmpty(md.getN02_ggjp())){ md.setN02_ggjp(StringHelper.getPinYinSample(md.getN01_ggjc())); } // String companyType = ((XXXXXDBO)data).getT01(); // // 分表处理 // if (ZERO.equals(companyType)) { // data.setTablename("0"); // } else if (ONE.equals(companyType)) { // data.setTablename("1"); // } } }
31.657895
98
0.715711
e963b0c103edd121ed321426799b672a2fef20f8
3,156
package me.eugeniomarletti.renderthread.sample; import android.animation.Animator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import me.eugeniomarletti.renderthread.CanvasProperty; import me.eugeniomarletti.renderthread.RenderThread; public class TestView extends FrameLayout { private boolean useRenderThread; private Animator radiusAnimator; private Animator alphaAnimator; private CanvasProperty<Float> centerXProperty; private CanvasProperty<Float> centerYProperty; private CanvasProperty<Float> radiusProperty; private CanvasProperty<Paint> paintProperty; private boolean animateNext; private long animationDurationMillis; public TestView(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); } public void setUseRenderThread(boolean useRenderThread) { this.useRenderThread = useRenderThread; } public void startAnimation(long durationMillis) { animationDurationMillis = durationMillis; animateNext = true; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (animateNext) { initialiseAnimation(canvas); animateNext = false; } if (centerXProperty != null && centerYProperty != null && radiusProperty != null && paintProperty != null) { RenderThread.drawCircle(canvas, centerXProperty, centerYProperty, radiusProperty, paintProperty); } } private void initialiseAnimation(Canvas canvas) { float width = getWidth(); float height = getHeight(); float centerX = width / 2f; float centerY = height / 2f; float initialRadius = 0f; float targetRadius = Math.min(width, height) / 2f; float targetAlpha = 0f; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); centerXProperty = RenderThread.createCanvasProperty(canvas, centerX, useRenderThread); centerYProperty = RenderThread.createCanvasProperty(canvas, centerY, useRenderThread); radiusProperty = RenderThread.createCanvasProperty(canvas, initialRadius, useRenderThread); paintProperty = RenderThread.createCanvasProperty(canvas, paint, useRenderThread); if (radiusAnimator != null) { radiusAnimator.cancel(); } radiusAnimator = RenderThread.createFloatAnimator(this, canvas, radiusProperty, targetRadius); radiusAnimator.setInterpolator(new LinearInterpolator()); radiusAnimator.setDuration(animationDurationMillis); radiusAnimator.start(); if (alphaAnimator != null) { alphaAnimator.cancel(); } alphaAnimator = RenderThread.createPaintAlphaAnimator(this, canvas, paintProperty, targetAlpha); alphaAnimator.setDuration(animationDurationMillis); alphaAnimator.start(); } }
34.304348
116
0.708809
8e57c3499a00a63709ce7553fac2aba4ef943155
4,806
/* * Copyright 2015 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.project.editor.libraries; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.stream.Collectors; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.rf.ide.core.executor.EnvironmentSearchPaths; import org.rf.ide.core.executor.RobotRuntimeEnvironment; import org.rf.ide.core.executor.RobotRuntimeEnvironment.RobotEnvironmentException; import org.rf.ide.core.project.RobotProjectConfig; import org.rf.ide.core.project.RobotProjectConfig.LibraryType; import org.rf.ide.core.project.RobotProjectConfig.ReferencedLibrary; import org.robotframework.ide.eclipse.main.plugin.RedWorkspace; import org.robotframework.ide.eclipse.main.plugin.project.RedEclipseProjectConfig; import com.google.common.base.Objects; import com.google.common.base.Splitter; public class PythonLibStructureBuilder implements ILibraryStructureBuilder { private final RobotRuntimeEnvironment environment; private final EnvironmentSearchPaths additionalSearchPaths; public PythonLibStructureBuilder(final RobotRuntimeEnvironment environment, final RobotProjectConfig config, final IProject project) { this.environment = environment; this.additionalSearchPaths = new RedEclipseProjectConfig(config).createEnvironmentSearchPaths(project); } @Override public Collection<ILibraryClass> provideEntriesFromFile(final URI path) throws RobotEnvironmentException { return provideEntriesFromFile(path, null, false); } public Collection<ILibraryClass> provideEntriesFromFile(final URI path, final String moduleName) throws RobotEnvironmentException { return provideEntriesFromFile(path, moduleName, true); } private Collection<ILibraryClass> provideEntriesFromFile(final URI path, final String moduleName, final boolean allowDuplicationOfFileAndClassName) { final List<String> classes = environment.getClassesFromModule(new File(path), moduleName, additionalSearchPaths); final List<PythonClass> pythonClasses = classes.stream() .map(name -> PythonClass.create(name, allowDuplicationOfFileAndClassName)) .collect(Collectors.toList()); return new LinkedHashSet<>(pythonClasses); } public static final class PythonClass implements ILibraryClass { private final String qualifiedName; private PythonClass(final String qualifiedName) { this.qualifiedName = qualifiedName; } static PythonClass create(final String name, final boolean allowDuplicationOfFileAndClassName) { final List<String> splitted = new ArrayList<>(Splitter.on('.').splitToList(name)); if (splitted.size() > 1) { final String last = splitted.get(splitted.size() - 1); final String beforeLast = splitted.get(splitted.size() - 2); // ROBOT requires whole qualified name of class if it is defined with different name // than module // containing it in module // FIXME check the comment above if its still apply if (last.equals(beforeLast) && !allowDuplicationOfFileAndClassName) { splitted.remove(splitted.size() - 1); } return new PythonClass(String.join(".", splitted)); } else { return new PythonClass(name); } } @Override public String getQualifiedName() { return qualifiedName; } @Override public ReferencedLibrary toReferencedLibrary(final String fullLibraryPath) { final IPath path = new Path(fullLibraryPath); final IPath pathWithoutModuleName = fullLibraryPath.endsWith("__init__.py") ? path.removeLastSegments(2) : path.removeLastSegments(1); return ReferencedLibrary.create(LibraryType.PYTHON, qualifiedName, RedWorkspace.Paths.toWorkspaceRelativeIfPossible(pathWithoutModuleName).toPortableString()); } @Override public boolean equals(final Object obj) { return obj != null && PythonClass.class == obj.getClass() && Objects.equal(this.qualifiedName, ((PythonClass) obj).qualifiedName); } @Override public int hashCode() { return Objects.hashCode(qualifiedName); } } }
41.076923
116
0.697462
3f4eae79ea809fe03461ea161c757cd58fb25421
324
package net.sf.l2j.gameserver.geoengine.geodata; /** * @author Hasha */ public enum GeoFormat { L2J("%d_%d.l2j"), L2OFF("%d_%d_conv.dat"), L2D("%d_%d.l2d"); private final String _filename; private GeoFormat(String filename) { _filename = filename; } public String getFilename() { return _filename; } }
14.086957
48
0.669753
e029e5052f12b3f1c132c34c64988e92cfe42f48
2,269
package com.fr.yncrea.isen.cir3.chess.domain; import javax.persistence.*; @Entity public class Figure { public static final String CODE_PREFIX = "&#"; public static final int CODE_NUMBER = 9812; @Id @Column @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "figures_seq_gen") @SequenceGenerator(name = "figures_seq_gen", sequenceName = "figures_id_seq") private Long id; @Column private Integer code; @Column private Integer x; @Column private Integer y; @Column private String name; @Column private Integer owner; @Column private Integer countPlayed = 0; @ManyToOne private Game game; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getCode() { return code; } public void setCode(int code) { if (code >= 0 && code <= 5) { this.code = code; } } public Integer getX() { return x; } public void setX(int x) { if (x >= 0 && x <= 7) { this.x = x; } } public Integer getY() { return y; } public void setY(int y) { if (y >= 0 && y <= 7) { this.y = y; } } public String getName() { return name; } public void setName(String name) { if (FigureName.stringToFigureName(name) != null) { this.name = name; } } public int getOwner() { return owner; } public void setOwner(int owner) { this.owner = owner; } public Game getGame() { return game; } public void setGame(Game game) { this.game = game; } public Integer getCountPlayed() { return countPlayed; } public void updateCountPlayed() { this.countPlayed = this.countPlayed + 1; } public String getHtmlCode() { String htmlCode = CODE_PREFIX + (CODE_NUMBER + code) + ";"; if (owner == 1) { htmlCode = CODE_PREFIX + (CODE_NUMBER + code + 6) + ";"; } return htmlCode; } public String getMoveCode() { return (char) (x + 65) + Integer.toString(8 - y); } }
18.298387
86
0.539004
ee0aded5dc4483e6e59b9995b24810326cf3bfdb
7,657
/* * Copyright 2017-2018 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.springframework.cloud.skipper.server.service; import java.util.Map; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.springframework.cloud.skipper.SkipperException; import org.springframework.cloud.skipper.domain.ConfigValues; import org.springframework.cloud.skipper.domain.Info; import org.springframework.cloud.skipper.domain.Manifest; import org.springframework.cloud.skipper.domain.Package; import org.springframework.cloud.skipper.domain.PackageIdentifier; import org.springframework.cloud.skipper.domain.PackageMetadata; import org.springframework.cloud.skipper.domain.Release; import org.springframework.cloud.skipper.domain.RollbackRequest; import org.springframework.cloud.skipper.domain.UpgradeProperties; import org.springframework.cloud.skipper.domain.UpgradeRequest; import org.springframework.cloud.skipper.server.deployer.ReleaseAnalysisReport; import org.springframework.cloud.skipper.server.deployer.ReleaseManager; import org.springframework.cloud.skipper.server.repository.PackageMetadataRepository; import org.springframework.cloud.skipper.server.repository.ReleaseRepository; import org.springframework.cloud.skipper.server.util.ConfigValueUtils; import org.springframework.cloud.skipper.server.util.ManifestUtils; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * @author Mark Pollack */ public class ReleaseReportService { private final PackageMetadataRepository packageMetadataRepository; private final ReleaseRepository releaseRepository; private final PackageService packageService; private final ReleaseManager releaseManager; public ReleaseReportService(PackageMetadataRepository packageMetadataRepository, ReleaseRepository releaseRepository, PackageService packageService, ReleaseManager releaseManager) { this.packageMetadataRepository = packageMetadataRepository; this.releaseRepository = releaseRepository; this.packageService = packageService; this.releaseManager = releaseManager; } /** * Merges the configuration values for the replacing release, creates the manfiest, and * creates the Report for the next stage of upgrading a Release. * * @param upgradeRequest containing the {@link UpgradeProperties} and * {@link PackageIdentifier} for the update. * @param rollbackRequest containing the rollback request if available * @param initial the flag indicating this is initial report creation * @return A report of what needs to change to bring the current release to the requested * release */ @Transactional public ReleaseAnalysisReport createReport(UpgradeRequest upgradeRequest, RollbackRequest rollbackRequest, boolean initial) { Assert.notNull(upgradeRequest.getUpgradeProperties(), "UpgradeProperties can not be null"); Assert.notNull(upgradeRequest.getPackageIdentifier(), "PackageIdentifier can not be null"); UpgradeProperties upgradeProperties = upgradeRequest.getUpgradeProperties(); Release existingRelease = this.releaseRepository.findLatestReleaseForUpdate(upgradeProperties.getReleaseName()); Release latestRelease = this.releaseRepository.findLatestRelease(upgradeProperties.getReleaseName()); PackageIdentifier packageIdentifier = upgradeRequest.getPackageIdentifier(); PackageMetadata packageMetadata = this.packageMetadataRepository.findByNameAndOptionalVersionRequired( packageIdentifier.getPackageName(), packageIdentifier .getPackageVersion()); // if we're about to save new release during this report, create // or restore replacing one. Release tempReplacingRelease = null; if (initial) { tempReplacingRelease = createReleaseForUpgrade(packageMetadata, latestRelease.getVersion() + 1, upgradeProperties, existingRelease.getPlatformName(), rollbackRequest); } else { tempReplacingRelease = this.releaseRepository.findByNameAndVersion( upgradeRequest.getUpgradeProperties().getReleaseName(), latestRelease.getVersion()); } // Carry over customized config values from replacing release so updates are additive with property changes. Release replacingRelease = updateReplacingReleaseConfigValues(latestRelease, tempReplacingRelease); Map<String, Object> mergedReplacingReleaseModel = ConfigValueUtils.mergeConfigValues(replacingRelease.getPkg(), replacingRelease.getConfigValues()); String manifestData = ManifestUtils.createManifest(replacingRelease.getPkg(), mergedReplacingReleaseModel); Manifest manifest = new Manifest(); manifest.setData(manifestData); replacingRelease.setManifest(manifest); return this.releaseManager.createReport(existingRelease, replacingRelease, initial); } private Release updateReplacingReleaseConfigValues(Release targetRelease, Release replacingRelease) { Map<String, Object> targetConfigValueMap = getConfigValuesAsMap(targetRelease.getConfigValues()); Map<String, Object> replacingRelaseConfigValueMap = getConfigValuesAsMap(replacingRelease.getConfigValues()); if (targetConfigValueMap != null && replacingRelaseConfigValueMap != null) { ConfigValueUtils.merge(targetConfigValueMap, replacingRelaseConfigValueMap); DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setPrettyFlow(true); Yaml yaml = new Yaml(dumperOptions); ConfigValues mergedConfigValues = new ConfigValues(); mergedConfigValues.setRaw(yaml.dump(targetConfigValueMap)); replacingRelease.setConfigValues(mergedConfigValues); } return replacingRelease; } private Map<String, Object> getConfigValuesAsMap(ConfigValues configValues) { Yaml yaml = new Yaml(); if (StringUtils.hasText(configValues.getRaw())) { Object data = yaml.load(configValues.getRaw()); if (data instanceof Map) { return (Map<String, Object>) yaml.load(configValues.getRaw()); } else { throw new SkipperException("Was expecting override values to produce a Map, instead got class = " + data.getClass() + "overrideValues.getRaw() = " + configValues.getRaw()); } } return null; } private Release createReleaseForUpgrade(PackageMetadata packageMetadata, Integer newVersion, UpgradeProperties upgradeProperties, String platformName, RollbackRequest rollbackRequest) { Assert.notNull(upgradeProperties, "Upgrade Properties can not be null"); Package packageToInstall = this.packageService.downloadPackage(packageMetadata); Release release = new Release(); release.setName(upgradeProperties.getReleaseName()); release.setPlatformName(platformName); release.setConfigValues(upgradeProperties.getConfigValues()); release.setPkg(packageToInstall); release.setVersion(newVersion); // we simply differentiate between upgrade/rollback if we know there is a rollback request Info info = Info .createNewInfo(rollbackRequest == null ? "Upgrade install underway" : "Rollback install underway"); release.setInfo(info); return release; } }
46.406061
114
0.806452
67ebb06abe0732fc65d8a4719014b464bf0aeb38
1,470
package natural.genericGA.binaryGA; import natural.AbstractIndividual; import natural.genericGA.GenericIndividual; @SuppressWarnings("WeakerAccess") public class BinaryIndividual extends GenericIndividual<Dna> { /** * Default BinaryIndividual has all solution set at 0 * Generated has each gene 50/50 as 1 or 0 * * @param length number of solution in an individual * @param generate if we use default individual or random */ BinaryIndividual(int length, boolean generate) { super(length, generate); } public void copy(AbstractIndividual individual) { solution.copyFrom(((BinaryIndividual) individual).getSolution()); fitness = individual.getFitness(); } @Override public void generateDna(boolean generate) { solution = new Dna(length); if (generate) for (int i = 0; i < length; i++) if (Math.random() >= 0.5) solution.set(i, true); } @Override public GenericIndividual<Dna> clone(boolean generate) { BinaryIndividual individual = new BinaryIndividual(length, generate); if (!generate) individual.copy(this); else individual.generateDna(true); return individual; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) sb.append(solution.get(i) ? '1' : '0'); return sb.toString(); } }
30.625
77
0.640816
9823a8f08768b2a9cc239d8b95721ea74543ad30
1,802
/* * Copyright (c) 2018 Oracle and/or its affiliates. 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 io.helidon.sitegen.asciidoctor; import java.util.Arrays; import java.util.Map; import org.asciidoctor.ast.Block; import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.extension.BlockProcessor; import org.asciidoctor.extension.Reader; import static org.asciidoctor.extension.Contexts.OPEN; /** * A {@link BlockProcessor} implementation that provides custom asciidoc syntax * for creating cards. * * @author rgrecour */ public class CardBlockProcessor extends BlockProcessor { /** * Create a new instance of {@link CardBlockProcessor}. */ public CardBlockProcessor() { super("CARD"); // this block is of type open (delimited by --) config.put(CONTEXTS, Arrays.asList(OPEN)); setConfigFinalized(); } @Override public Object process(StructuralNode parent, Reader reader, Map<String, Object> attributes) { // create a block with context "card", and put the parsed content into it Block block = this.createBlock(parent, "card", reader.readLines(), attributes); return block; } }
31.068966
81
0.690899
48241ca96fd13ba60dd9295b28ea28f3365453ad
640
package cn.misection.cvac.ast.expr.terminator; import cn.misection.cvac.ast.expr.EnumCvaExpr; import cn.misection.cvac.ast.type.basic.EnumCvaType; /** * @author Military Intelligence 6 root * @version 1.0.0 * @ClassName CvaFalseExpr * @Description TODO * @CreateTime 2021年02月14日 19:18:00 */ public final class CvaConstFalseExpr extends AbstractTerminator { public CvaConstFalseExpr(int lineNum) { super(lineNum); } @Override public EnumCvaType resType() { return EnumCvaType.BOOLEAN; } @Override public EnumCvaExpr toEnum() { return EnumCvaExpr.CONST_FALSE; } }
20
63
0.69375
ee3812681bd4d534d30a63e1065a288d05660115
2,926
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.http.annotation; import static java.lang.annotation.RetentionPolicy.RUNTIME; import io.micronaut.context.annotation.AliasFor; import io.micronaut.core.bind.annotation.Bindable; import java.lang.annotation.*; /** * <p>An annotation that can be applied to method argument to indicate that the method argument is bound from an HTTP header * This also can be used in conjunction with &#064;Headers to list headers on a client class that will always be applied.</p> * <p></p> * <p>The following example demonstrates usage at the type level to declare default values to pass in the request when using the {@code Client} annotation:</p> * <p></p> * * <pre class="code"> * &#064;Header(name="X-Username",value='Freddy'), * &#064;Header(name="X-MyParam",value='${foo.bar}') * &#064;Client('/users') * interface UserClient { * * } * </pre> * * <p>When declared as a binding annotation the <code>&#064;Header</code> annotation is declared on each parameter to be bound:</p> * * <pre class="code"> * &#064;Get('/user') * User get(&#064;Header('X-Username') String username, &#064;Header('X-MyParam') String myparam) { * return new User(username, myparam); * } * </pre> * * @author Graeme Rocher * @author rvanderwerf * @since 1.0 */ @Documented @Retention(RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) // this can be either type or param @Repeatable(value = Headers.class) @Bindable @Inherited public @interface Header { /** * If used as a bound parameter, this is the header name. If used on a class level this is value and not the header name. * @return The name of the header, otherwise it is inferred from the parameter name */ @AliasFor(annotation = Bindable.class, member = "value") String value() default ""; /** * If used on a class level with @Headers this is the header name and value is the value. * @return name of header when using with @Headers */ @AliasFor(annotation = Bindable.class, member = "value") String name() default ""; /** * @see Bindable#defaultValue() * @return The default value */ @AliasFor(annotation = Bindable.class, member = "defaultValue") String defaultValue() default ""; }
34.833333
159
0.701982
fffeab03ef35154860f31fd4d45eafad04f701aa
3,357
package com.abandy.swagger.modeler; import java.util.HashMap; import java.util.Map; public class SwaggerEntry { private final SwaggerEntryType type; private final String swaggerUrl; private String packageName; private String managerName; private Map<String, String> queryParams = new HashMap<String, String>(); private SwaggerEntry(SwaggerEntryType type, String packageName, String swaggerUrl) { this.type = type; this.packageName = packageName; this.swaggerUrl = this.processQueryParams(swaggerUrl); } private SwaggerEntry(SwaggerEntryType type, String managerName, String packageName, String swaggerUrl) { this(type, packageName, swaggerUrl); this.managerName = managerName; } public static SwaggerEntry parse(String entry) { String[] lineParts = entry.split(";"); if (lineParts.length == 2){ return new SwaggerEntry(SwaggerEntryType.PACKAGE_AND_URL, lineParts[0], lineParts[1]); } else if(lineParts.length == 3){ return new SwaggerEntry(SwaggerEntryType.PACKAGE_MANAGER_AND_URL, lineParts[0], lineParts[1], lineParts[2]); } else { String packageName = entry.substring(entry.lastIndexOf("/") + 1, entry.lastIndexOf(".")); if (entry.contains("specification/")) { int startIndex = entry.indexOf("specification/") + 14; packageName = entry.substring(startIndex, entry.indexOf("/", startIndex)); String[] packageNameParts = packageName.split("-"); StringBuilder packageBuilder = new StringBuilder(); if (packageNameParts.length > 0) { packageBuilder.append(packageNameParts[0]); } for (int i = 1; i < packageNameParts.length; i++) { if (!packageNameParts[i].equals("-")) { packageBuilder.append(Character.toUpperCase(packageNameParts[i].charAt(0))); packageBuilder.append(packageNameParts[i].substring(1)); } } packageName = packageBuilder.toString(); } packageName = packageName.replaceAll("-", ""); return new SwaggerEntry(SwaggerEntryType.PACKAGE_AND_URL, packageName, entry); } } public SwaggerEntryType type() { return this.type; } public String packageName() { return this.packageName; } public String managerName() { return this.managerName; } public String swaggerUrl() { return this.swaggerUrl; } public boolean isReadMe() { return this.swaggerUrl.endsWith("readme.md"); } public Map<String, String> queryParams() { return this.queryParams; } private String processQueryParams(String swaggerUrl) { int index = swaggerUrl.indexOf("?"); if(index > 1) { String[] queryParams = swaggerUrl.substring(index + 1).split("&"); for(String queryParam : queryParams) { String[] parts = queryParam.split("="); this.queryParams.put(parts[0], parts.length > 1 ? parts[1]: ""); } swaggerUrl = swaggerUrl.substring(0, index); } return swaggerUrl; } }
35.336842
120
0.59994
1a96852eec4001c83764b92dca910a0474ee0097
8,290
/* * Copyright 2017 LinkedIn Corp. * * 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 azkaban.executor; import azkaban.db.EncodingType; import azkaban.db.DatabaseOperator; import azkaban.db.DatabaseTransOperator; import azkaban.db.SQLTransaction; import azkaban.utils.FileIOUtils; import azkaban.utils.FileIOUtils.LogData; import azkaban.utils.GZIPUtils; import azkaban.utils.Pair; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; @Singleton public class ExecutionLogsDao { private static final Logger logger = Logger.getLogger(ExecutionLogsDao.class); private final DatabaseOperator dbOperator; private final EncodingType defaultEncodingType = EncodingType.GZIP; @Inject ExecutionLogsDao(final DatabaseOperator dbOperator) { this.dbOperator = dbOperator; } // TODO kunkun-tang: the interface's parameter is called endByte, but actually is length. LogData fetchLogs(final int execId, final String name, final int attempt, final int startByte, final int length) throws ExecutorManagerException { final FetchLogsHandler handler = new FetchLogsHandler(startByte, length + startByte); try { return this.dbOperator.query(FetchLogsHandler.FETCH_LOGS, handler, execId, name, attempt, startByte, startByte + length); } catch (final SQLException e) { throw new ExecutorManagerException("Error fetching logs " + execId + " : " + name, e); } } public void uploadLogFile(final int execId, final String name, final int attempt, final File... files) throws ExecutorManagerException { final SQLTransaction<Integer> transaction = transOperator -> { uploadLogFile(transOperator, execId, name, attempt, files, this.defaultEncodingType); transOperator.getConnection().commit(); return 1; }; try { this.dbOperator.transaction(transaction); } catch (final SQLException e) { logger.error("uploadLogFile failed.", e); throw new ExecutorManagerException("uploadLogFile failed.", e); } } private void uploadLogFile(final DatabaseTransOperator transOperator, final int execId, final String name, final int attempt, final File[] files, final EncodingType encType) throws SQLException { // 50K buffer... if logs are greater than this, we chunk. // However, we better prevent large log files from being uploaded somehow final byte[] buffer = new byte[50 * 1024]; int pos = 0; int length = buffer.length; int startByte = 0; try { for (int i = 0; i < files.length; ++i) { final File file = files[i]; final BufferedInputStream bufferedStream = new BufferedInputStream(new FileInputStream(file)); try { int size = bufferedStream.read(buffer, pos, length); while (size >= 0) { if (pos + size == buffer.length) { // Flush here. uploadLogPart(transOperator, execId, name, attempt, startByte, startByte + buffer.length, encType, buffer, buffer.length); pos = 0; length = buffer.length; startByte += buffer.length; } else { // Usually end of file. pos += size; length = buffer.length - pos; } size = bufferedStream.read(buffer, pos, length); } } finally { IOUtils.closeQuietly(bufferedStream); } } // Final commit of buffer. if (pos > 0) { uploadLogPart(transOperator, execId, name, attempt, startByte, startByte + pos, encType, buffer, pos); } } catch (final SQLException e) { logger.error("Error writing log part.", e); throw new SQLException("Error writing log part", e); } catch (final IOException e) { logger.error("Error chunking.", e); throw new SQLException("Error chunking", e); } } int removeExecutionLogsByTime(final long millis) throws ExecutorManagerException { final String DELETE_BY_TIME = "DELETE FROM execution_logs WHERE upload_time < ?"; try { return this.dbOperator.update(DELETE_BY_TIME, millis); } catch (final SQLException e) { logger.error("delete execution logs failed", e); throw new ExecutorManagerException( "Error deleting old execution_logs before " + millis, e); } } private void uploadLogPart(final DatabaseTransOperator transOperator, final int execId, final String name, final int attempt, final int startByte, final int endByte, final EncodingType encType, final byte[] buffer, final int length) throws SQLException, IOException { final String INSERT_EXECUTION_LOGS = "INSERT INTO execution_logs " + "(exec_id, name, attempt, enc_type, start_byte, end_byte, " + "log, upload_time) VALUES (?,?,?,?,?,?,?,?)"; byte[] buf = buffer; if (encType == EncodingType.GZIP) { buf = GZIPUtils.gzipBytes(buf, 0, length); } else if (length < buf.length) { buf = Arrays.copyOf(buffer, length); } transOperator.update(INSERT_EXECUTION_LOGS, execId, name, attempt, encType.getNumVal(), startByte, startByte + length, buf, DateTime.now() .getMillis()); } //查询任务运行日志的处理 private static class FetchLogsHandler implements ResultSetHandler<LogData> { private static final String FETCH_LOGS = "SELECT exec_id, name, attempt, enc_type, start_byte, end_byte, log " + "FROM execution_logs " + "WHERE exec_id=? AND name=? AND attempt=? AND end_byte > ? " + "AND start_byte <= ? ORDER BY start_byte"; private final int startByte; private final int endByte; FetchLogsHandler(final int startByte, final int endByte) { this.startByte = startByte; this.endByte = endByte; } @Override public LogData handle(final ResultSet rs) throws SQLException { if (!rs.next()) { return null; } final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); do { // int execId = rs.getInt(1); // String name = rs.getString(2); final int attempt = rs.getInt(3); final EncodingType encType = EncodingType.fromInteger(rs.getInt(4)); final int startByte = rs.getInt(5); final int endByte = rs.getInt(6); final byte[] data = rs.getBytes(7); final int offset = this.startByte > startByte ? this.startByte - startByte : 0; final int length = this.endByte < endByte ? this.endByte - startByte - offset : endByte - startByte - offset; try { byte[] buffer = data; if (encType == EncodingType.GZIP) { buffer = GZIPUtils.unGzipBytes(data); } byteStream.write(buffer, offset, length); } catch (final IOException e) { throw new SQLException(e); } } while (rs.next()); final byte[] buffer = byteStream.toByteArray(); final Pair<Integer, Integer> result = FileIOUtils.getUtf8Range(buffer, 0, buffer.length); return new LogData(this.startByte + result.getFirst(), result.getSecond(), new String(buffer, result.getFirst(), result.getSecond(), StandardCharsets.UTF_8)); } } }
35.42735
93
0.661399
24beda8eab5b2f42a8c57a47e3472ccbc33dc964
3,058
/* * Copyright 2012 Lokesh Jain. * * 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.jain.addon.web.table; import java.text.SimpleDateFormat; import java.util.Date; import com.jain.addon.component.JStreamSource; import com.jain.addon.web.bean.JNIProperty; import com.jain.addon.web.bean.helper.JainHelper; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.server.StreamResource; import com.vaadin.ui.Component; import com.vaadin.ui.Embedded; import com.vaadin.ui.Table; import com.vaadin.ui.Table.Align; import com.vaadin.ui.Table.ColumnGenerator; /** * <code>JainColumnGenerator<code> is a default column generator for the {@link JTable} * @author Lokesh Jain * @since Aug 28, 2012 * @version 1.0.0 */ @SuppressWarnings("serial") public class JainColumnGenerator implements ColumnGenerator { private JNIProperty[] properties; public JainColumnGenerator(JNIProperty... properties) { this.properties = properties; } public Component generateCell(final Table source, final Object itemId, final Object columnId) { JNIProperty property = JainHelper.getPropertyForName(properties, columnId); if(property != null && property.getType() != null) { final Item item = source.getItem(itemId); final Property<?> itemProperty = item.getItemProperty(property.getName()); switch (property.getType()) { case IMAGE: return createImage(itemProperty, source); default: break; } } return null; } private Component createImage(final Property<?> itemProperty, final Table source) { if(itemProperty.getValue() != null) { JStreamSource streamSource = new JStreamSource((byte[]) itemProperty.getValue()); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String filename = "myfilename-" + df.format(new Date()) + ".png"; StreamResource resource = new StreamResource(streamSource, filename); Embedded embedded = new Embedded("", resource); embedded.setHeight("20px"); return embedded; } return null; } public JNIProperty[] getProperties() { return properties; } public void setProperties(JNIProperty[] properties) { this.properties = properties; } public void addGeneratedColumn(final Table source) { for (JNIProperty property : properties) { if(property.getType() != null) { switch (property.getType()) { case IMAGE: source.addGeneratedColumn(property.getName(), this); source.setColumnAlignment(property.getName(), Align.CENTER); break; default: break; } } } } }
29.980392
96
0.731197
4f21a9aa105c1f6fd85c63fbffcfbfd99ddd00db
1,453
package build.please.test.result; import org.junit.runner.notification.Failure; import org.w3c.dom.Document; import org.w3c.dom.Element; public final class ErrorCaseResult extends TestCaseResult { private final String message; private final String type; private final String stackTrace; public ErrorCaseResult(String testClassName, String testMethodName, String message, String type, String stackTrace) { super(testClassName, testMethodName); this.message = message; this.type = type; this.stackTrace = stackTrace; } public static ErrorCaseResult fromFailure(Failure failure) { return new ErrorCaseResult( failure.getDescription().getClassName(), failure.getDescription().getMethodName(), failure.getMessage(), failure.getException().getClass().getName(), failure.getTrace()); } @Override public boolean isSuccess() { return false; } @Override public void renderToXml(Document doc, Element testCaseElement) { super.renderToXml(doc, testCaseElement); Element error = doc.createElement("error"); if (message != null) { error.setAttribute("message", message); } error.setAttribute("type", type); error.setTextContent(stackTrace); testCaseElement.appendChild(error); } public String getMessage() { return message; } }
27.415094
66
0.66552
20b1021709fc158dd1208839c3684fd76f50cb76
594
import model.Animal; import model.Cat; import model.Dog; public class Main { public static void main(String[] args) { System.out.println("Seja Bem Vindo"); Animal animal = new Animal(); animal.setName("Nome do animal"); System.out.println(animal); Dog dog = new Dog(); dog.setName("Tobby"); dog.setAge(5); dog.setNumberPaws(4); System.out.println(dog); Cat cat = new Cat(); cat.setName("Leonidas"); cat.setAge(300); cat.setNumberPaws(4); System.out.println(cat); } }
20.482759
45
0.56734
4ccae09334a29258ff0afe31fc6a1ea6c4a88ec2
10,170
/* * Copyright 2010-2013 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.beatrix.osgi; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.testng.Assert; import com.ning.billing.osgi.api.config.PluginConfig.PluginLanguage; import com.ning.billing.osgi.api.config.PluginConfig.PluginType; import com.ning.billing.osgi.api.config.PluginJavaConfig; import com.ning.billing.util.config.OSGIConfig; import com.google.common.io.ByteStreams; import com.google.common.io.Resources; public class SetupBundleWithAssertion { private final String JRUBY_BUNDLE_RESOURCE = "killbill-osgi-bundles-jruby"; private final String bundleName; private final OSGIConfig config; private final String killbillVersion; private final File rootInstallDir; public SetupBundleWithAssertion(final String bundleName, final OSGIConfig config, final String killbillVersion) { this.bundleName = bundleName; this.config = config; this.killbillVersion = killbillVersion; this.rootInstallDir = new File(config.getRootInstallationDir()); } public void setupJrubyBundle() { try { installJrubyJar(); final URL resourceUrl = Resources.getResource(bundleName); final File unzippedRubyPlugin = unGzip(new File(resourceUrl.getFile()), rootInstallDir); final StringBuilder tmp = new StringBuilder(rootInstallDir.getAbsolutePath()); tmp.append("/plugins/") .append(PluginLanguage.RUBY.toString().toLowerCase()); final File destination = new File(tmp.toString()); if (!destination.exists()) { destination.mkdir(); } unTar(unzippedRubyPlugin, destination); } catch (IOException e) { Assert.fail(e.getMessage()); } catch (ArchiveException e) { Assert.fail(e.getMessage()); } } public void setupJavaBundle() { try { // Retrieve PluginConfig info from classpath // test bundle should have been exported under Beatrix resource by the maven maven-dependency-plugin final PluginJavaConfig pluginConfig = extractJavaBundleTestResource(); Assert.assertNotNull(pluginConfig); // Create OSGI install bundle directory setupDirectoryStructure(pluginConfig); // Copy the jar ByteStreams.copy(new FileInputStream(new File(pluginConfig.getBundleJarPath())), new FileOutputStream(new File(pluginConfig.getPluginVersionRoot().getAbsolutePath(), pluginConfig.getPluginVersionnedName() + ".jar"))); // Create the osgiConfig file createConfigFile(pluginConfig); } catch (IOException e) { Assert.fail(e.getMessage()); } } public void cleanBundleInstallDir() { if (rootInstallDir.exists()) { deleteDirectory(rootInstallDir, false); } } private void createConfigFile(final PluginJavaConfig pluginConfig) throws IOException { PrintStream printStream = null; try { final File configFile = new File(pluginConfig.getPluginVersionRoot(), config.getOSGIKillbillPropertyName()); configFile.createNewFile(); printStream = new PrintStream(new FileOutputStream(configFile)); printStream.print("pluginType=" + PluginType.NOTIFICATION); } finally { if (printStream != null) { printStream.close(); } } } private void setupDirectoryStructure(final PluginJavaConfig pluginConfig) { cleanBundleInstallDir(); pluginConfig.getPluginVersionRoot().mkdirs(); } private static void deleteDirectory(final File path, final boolean deleteParent) { if (path == null) { return; } if (path.exists()) { final File[] files = path.listFiles(); if (files != null) { for (final File f : files) { if (f.isDirectory()) { deleteDirectory(f, true); } f.delete(); } } if (deleteParent) { path.delete(); } } } private void installJrubyJar() throws IOException { final String resourceName = JRUBY_BUNDLE_RESOURCE + "-" + killbillVersion + ".jar"; final URL resourceUrl = Resources.getResource(resourceName); final File rubyJarInput = new File(resourceUrl.getFile()); final File platform = new File(rootInstallDir, "platform"); if (!platform.exists()) { platform.mkdir(); } final File rubyJarDestination = new File(platform, "jruby.jar"); ByteStreams.copy(new FileInputStream(rubyJarInput), new FileOutputStream(rubyJarDestination)); } private PluginJavaConfig extractJavaBundleTestResource() { final String resourceName = bundleName + "-" + killbillVersion + "-jar-with-dependencies.jar"; final URL resourceUrl = Resources.getResource(resourceName); if (resourceUrl != null) { final String[] parts = resourceUrl.getPath().split("/"); final String lastPart = parts[parts.length - 1]; if (lastPart.startsWith(bundleName)) { return createPluginJavaConfig(resourceUrl.getPath()); } } return null; } private PluginJavaConfig createPluginJavaConfig(final String bundleTestResourcePath) { return new PluginJavaConfig() { @Override public String getBundleJarPath() { return bundleTestResourcePath; } @Override public String getPluginName() { return bundleName; } @Override public PluginType getPluginType() { return PluginType.PAYMENT; } @Override public String getVersion() { return killbillVersion; } @Override public String getPluginVersionnedName() { return bundleName + "-" + killbillVersion; } @Override public File getPluginVersionRoot() { final StringBuilder tmp = new StringBuilder(rootInstallDir.getAbsolutePath()); tmp.append("/plugins/") .append(PluginLanguage.JAVA.toString().toLowerCase()) .append("/") .append(bundleName) .append("/") .append(killbillVersion); final File result = new File(tmp.toString()); return result; } @Override public PluginLanguage getPluginLanguage() { return PluginLanguage.JAVA; } }; } private static void unTar(final File inputFile, final File outputDir) throws IOException, ArchiveException { InputStream is = null; TarArchiveInputStream archiveInputStream = null; TarArchiveEntry entry = null; try { is = new FileInputStream(inputFile); archiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is); while ((entry = (TarArchiveEntry) archiveInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { final OutputStream outputFileStream = new FileOutputStream(outputFile); ByteStreams.copy(archiveInputStream, outputFileStream); outputFileStream.close(); } } } finally { if (archiveInputStream != null) { archiveInputStream.close(); } if (is != null) { is.close(); } } } private static File unGzip(final File inputFile, final File outputDir) throws IOException { GZIPInputStream in = null; FileOutputStream out = null; try { final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3)); in = new GZIPInputStream(new FileInputStream(inputFile)); out = new FileOutputStream(outputFile); for (int c = in.read(); c != -1; c = in.read()) { out.write(c); } return outputFile; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
34.127517
229
0.603245
b615ffc085d07805164140f79629ea80df18e49a
5,106
package com.elytradev.davincisvessels; import com.elytradev.davincisvessels.client.ClientProxy; import com.elytradev.davincisvessels.common.CommonProxy; import com.elytradev.davincisvessels.common.DavincisVesselsConfig; import com.elytradev.davincisvessels.common.command.*; import com.elytradev.davincisvessels.common.entity.EntityParachute; import com.elytradev.davincisvessels.common.entity.EntitySeat; import com.elytradev.davincisvessels.common.entity.EntityShip; import com.elytradev.davincisvessels.common.handler.ConnectionHandler; import com.elytradev.davincisvessels.common.network.DavincisVesselsNetworking; import com.elytradev.davincisvessels.common.object.DavincisVesselsObjects; import com.elytradev.davincisvessels.movingworld.MovingWorldLib; import net.minecraft.command.CommandBase; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; import org.apache.logging.log4j.Logger; import java.util.Collections; @Mod(modid = ModConstants.MOD_ID, name = ModConstants.MOD_NAME, dependencies = ModConstants.DEPENDENCIES, version = ModConstants.MOD_VERSION, guiFactory = ModConstants.MOD_GUIFACTORY) public class DavincisVesselsMod { public static final DavincisVesselsObjects OBJECTS = new DavincisVesselsObjects(); @Mod.Instance(ModConstants.MOD_ID) public static DavincisVesselsMod INSTANCE; @SidedProxy(clientSide = "com.elytradev.davincisvessels.client.ClientProxy", serverSide = "com.elytradev.davincisvessels.common.CommonProxy") public static CommonProxy PROXY; public static Logger LOG; public static CreativeTabs CREATIVE_TAB = new CreativeTabs("davincisTab") { @Override public ItemStack getTabIconItem() { return new ItemStack(DavincisVesselsObjects.blockMarkShip); } }; public DavincisVesselsMod() { new MovingWorldLib(); } private DavincisVesselsConfig localConfig; public DavincisVesselsConfig getNetworkConfig() { if (FMLCommonHandler.instance().getSide().isClient()) { if (((ClientProxy) PROXY).syncedConfig != null) { return ((ClientProxy) PROXY).syncedConfig; } } return localConfig; } public DavincisVesselsConfig getLocalConfig() { return localConfig; } @Mod.EventHandler public void preInitMod(FMLPreInitializationEvent event) { LOG = event.getModLog(); MovingWorldLib.INSTANCE.preInit(event); MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(PROXY); MinecraftForge.EVENT_BUS.register(OBJECTS); OBJECTS.preInit(event); localConfig = new DavincisVesselsConfig(new Configuration(event.getSuggestedConfigurationFile())); localConfig.loadAndSave(); EntityRegistry.registerModEntity(new ResourceLocation(ModConstants.MOD_ID, "ship"), EntityShip.class, "shipmod", 1, this, 64, localConfig.getShared().shipEntitySyncRate, true); EntityRegistry.registerModEntity(new ResourceLocation(ModConstants.MOD_ID, "seat"), EntitySeat.class, "attachment.seat", 2, this, 64, 20, false); EntityRegistry.registerModEntity(new ResourceLocation(ModConstants.MOD_ID, "parachute"), EntityParachute.class, "parachute", 3, this, 32, localConfig.getShared().shipEntitySyncRate, true); PROXY.registerRenderers(event.getModState()); } @Mod.EventHandler public void initMod(FMLInitializationEvent event) { MovingWorldLib.INSTANCE.init(event); DavincisVesselsNetworking.setupNetwork(); OBJECTS.init(event); MinecraftForge.EVENT_BUS.register(new ConnectionHandler()); PROXY.registerKeyHandlers(localConfig); PROXY.registerEventHandlers(); PROXY.registerRenderers(event.getModState()); localConfig.postLoad(); localConfig.addBlacklistWhitelistEntries(); } @Mod.EventHandler public void postInitMod(FMLPostInitializationEvent event) { MovingWorldLib.INSTANCE.postInit(event); PROXY.registerRenderers(event.getModState()); } @Mod.EventHandler public void serverStarting(FMLServerStartingEvent event) { registerASCommand(event, new CommandDVHelp()); registerASCommand(event, new CommandDisassembleShip()); registerASCommand(event, new CommandShipInfo()); registerASCommand(event, new CommandDisassembleNear()); registerASCommand(event, new CommandDVTP()); Collections.sort(CommandDVHelp.asCommands); } private void registerASCommand(FMLServerStartingEvent event, CommandBase commandbase) { event.registerServerCommand(commandbase); CommandDVHelp.asCommands.add(commandbase); } public World getWorld(int id) { return PROXY.getWorld(id); } }
37.822222
190
0.814728
de4eb68b6d1362f2d58db166e5e0c155a6ae4b73
2,692
package org.restonfire; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; /** * Test class for PathUtil. */ public class PathUtilTest { private static final String PATH = "foo/bar"; private static final String PATH_WITH_SLASH = "foo/bar/"; private static final String SINGLE_PATH = "foo"; @Rule public ExpectedException exception = ExpectedException.none(); @Test public void getParent_pathIsNull() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("path cannot be null"); PathUtil.getParent(null); } @Test public void getParent_pathIsEmptyString() throws Exception { assertEquals(null, PathUtil.getParent("")); } @Test public void getParent_pathIsSingleSlash() throws Exception { assertEquals(null, PathUtil.getParent("/")); } @Test public void getParent_singleCharPath() throws Exception { assertEquals("", PathUtil.getParent("a")); } @Test public void getParent_singleCharPathWithSlash() throws Exception { assertEquals("", PathUtil.getParent("a/")); } @Test public void getParent_pathEndsWithSlash() throws Exception { assertEquals("foo", PathUtil.getParent(PATH_WITH_SLASH)); } @Test public void getParent_pathDoesNotEndWithSlash() throws Exception { assertEquals("foo", PathUtil.getParent(PATH)); } @Test public void getChild_pathIsNull() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("path cannot be null"); PathUtil.concatenatePath(null, SINGLE_PATH); } @Test public void getChild_ofRootPath() throws Exception { assertEquals("foo", PathUtil.concatenatePath("", SINGLE_PATH)); } @Test public void getChild_ofRootPathWithSlash() throws Exception { assertEquals("foo", PathUtil.concatenatePath("/", SINGLE_PATH)); } @Test public void getChild_ofExistingPath() throws Exception { assertEquals("foo/bar/foo", PathUtil.concatenatePath(PATH, SINGLE_PATH)); } @Test public void getChild_ofExistingPathWithSlash() throws Exception { assertEquals("foo/bar/foo", PathUtil.concatenatePath(PATH_WITH_SLASH, SINGLE_PATH)); } @Test public void getChild_ofExistingPathWithWithMultileveChild() throws Exception { assertEquals("foo/bar/foo/bar", PathUtil.concatenatePath(PATH, PATH)); assertEquals("foo/bar/foo/bar", PathUtil.concatenatePath(PATH_WITH_SLASH, PATH_WITH_SLASH)); } @Test public void normalizePath() { assertEquals(PATH, PathUtil.normalizePath(PATH)); assertEquals(PATH, PathUtil.normalizePath(PATH_WITH_SLASH)); } }
27.191919
96
0.73997
abd6802ec493842ee5aef096c8e4a2b0e0cf38e3
5,620
// SPDX-License-Identifier: Apache-2.0 // YAPI // Copyright (C) 2019,2020 yoyosource package yapi.ui; import org.jutils.jprocesses.JProcesses; import org.jutils.jprocesses.model.ProcessInfo; import yapi.file.FileUtils; import yapi.math.Fraction; import yapi.math.NumberUtils; import yapi.runtime.ThreadUtils; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TestTest { public static void main(String[] args) { test(); //Clip clip = AudioSystem.getClip(); //clip.loop(); //productSystem(3); //System.out.println(); //System.out.println(count); if (false) { int count = 7; double d1 = 0.9; double d2 = 0.1; StringBuilder st = new StringBuilder(); for (int i = 0; i <= count; i++) { st.append(NumberUtils.over(count, i)).append("*").append(d1).append("^{").append(count - i).append("}*").append(d2).append("^{").append(i).append("}+"); } System.out.println(st.toString()); } if (true) { int count = 5; Fraction percent = Fraction.decode("65%"); for (int i = 0; i <= count; i++) { System.out.println(i + ": " + (new Fraction(NumberUtils.over(count, i)).multiply(percent.power(i).multiply(Fraction.ONE.subtract(percent).power(count - i)))).encodePercent()); } } } private static void test() { System.out.println(FileUtils.getSize(FileUtils.getDiskSpace(), true, true, 1)); System.out.println(FileUtils.getSize(FileUtils.getFreeSpace(), true, true, 1)); System.out.println(FileUtils.getSize(FileUtils.getUsableSpace(), true, true, 1)); System.out.println(); List<ProcessInfo> processesList = JProcesses.getProcessList(); /*double cpuUsage = 0; for (final ProcessInfo processInfo : processesList) { //send(processInfo); cpuUsage += getCPUUsage(processInfo); System.out.println("Process PID: " + processInfo.getPid()); System.out.println("Process Name: " + processInfo.getName()); System.out.println("Process Time: " + processInfo.getTime()); System.out.println("User: " + processInfo.getUser()); System.out.println("Virtual Memory: " + processInfo.getVirtualMemory()); System.out.println("Physical Memory: " + processInfo.getPhysicalMemory()); System.out.println("CPU usage: " + processInfo.getCpuUsage()); System.out.println("Start Time: " + processInfo.getStartTime()); System.out.println("Priority: " + processInfo.getPriority()); System.out.println("Full command: " + processInfo.getCommand()); System.out.println("------------------"); } System.out.println(cpuUsage); */ for (;;) { double usage = getCPUUsage(); System.out.println(usage + "/" + Runtime.getRuntime().availableProcessors() + " ~ " + (usage / Runtime.getRuntime().availableProcessors())); ThreadUtils.sleep(10); } } private static void send(ProcessInfo info) { System.out.println(pad(5, info.getPid()) + " " + pad(12, info.getName()) + " " + pad(5, info.getCpuUsage()) + " "); } private static double getCPUUsage() { double cpuUsage = 0; for (ProcessInfo processInfo : JProcesses.getProcessList()) { cpuUsage += getCPUUsage(processInfo); } return cpuUsage; } private static double getCPUUsage(ProcessInfo info) { return Double.parseDouble(info.getCpuUsage()); } private static String pad(int pad, Object object) { if (object.toString().length() > pad) { return object.toString().substring(0, pad); } return " ".repeat(pad - object.toString().length()) + object; } private static int count = 0; private static void productSystem(int diceNumber) { int[] dices = new int[diceNumber]; Arrays.fill(dices, 1); Map<Integer, Integer> integerIntegerMap = new HashMap<>(); double d = Math.pow(6, diceNumber); for (long l = 0; l < d; l++) { int index = 0; while (index != -1) { if (index >= dices.length) { break; } dices[index]++; if (dices[index] > 6) { dices[index] = 1; index++; } else { index = -1; } } appendToMap(integerIntegerMap, dices); } List<Integer> keys = integerIntegerMap.keySet().stream().collect(Collectors.toList()); keys.sort(Integer::compareTo); for (int k : keys) { System.out.print(k + "=" + integerIntegerMap.get(k) + ", "); } } private static void appendToMap(Map<Integer, Integer> integerIntegerMap, int[] dices) { int l = 1; //System.out.print(Arrays.toString(dices) + " " + count + " "); count = 0; for (int i : dices) { if (i == 3 || i == 4) { count++; } l *= i; } l = count; //System.out.println(count); if (integerIntegerMap.containsKey(l)) { integerIntegerMap.replace(l, integerIntegerMap.get(l) + 1); } else { integerIntegerMap.put(l, 1); } } }
34.060606
191
0.551957
0f0f00dd45a2abc87fc1d7891f75a3f062ffa27b
1,303
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.trading.api; /** * * Units of measure that you can use to specify properties such as weight and size * dimensions. * */ public enum UnitCodeType { /** * * Kilograms * */ KG("kg"), /** * * Grams * */ GM("gm"), /** * * Pounds * */ LBS("lbs"), /** * * Ounces * */ OZ("oz"), /** * * Centimeters * */ CM("cm"), /** * * Milimeters * */ MM("mm"), /** * * Inches * */ INCHES("inches"), /** * * Feet * */ FT("ft"), /** * * Reserved for internal or future use. * */ CUSTOM_CODE("CustomCode"); private final String value; UnitCodeType(String v) { value = v; } public String value() { return value; } public static UnitCodeType fromValue(String v) { if (v != null) { for (UnitCodeType c: UnitCodeType.values()) { if (c.value.equals(v)) { return c; } } } throw new IllegalArgumentException(v); } }
12.409524
82
0.406754
7cd436cc5cddf77a30223ec2fba41bec093a3ac4
6,808
/* * CentralMapExtraFragment.java * Copyright (C) 2015 Nicholas Killewald * * This file is distributed under the terms of the BSD license. * The source package should have a LICENSE file at the toplevel. */ package net.exclaimindustries.geohashdroid.fragments; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.View; import com.google.android.gms.location.LocationListener; import net.exclaimindustries.geohashdroid.activities.DetailedInfoActivity; import net.exclaimindustries.geohashdroid.activities.WikiActivity; import net.exclaimindustries.geohashdroid.util.Info; import net.exclaimindustries.geohashdroid.util.PermissionsDeniedListener; /** * This is the base class from which the two extra Fragments {@link net.exclaimindustries.geohashdroid.activities.CentralMap} * can use derive. It simply allows better communication between them and * {@link net.exclaimindustries.geohashdroid.util.ExpeditionMode}. */ public abstract class CentralMapExtraFragment extends BaseGHDThemeFragment implements LocationListener, PermissionsDeniedListener { /** * The various types of CentralMapExtraFragment that can exist. It's either * this or a mess of instanceof checks to see what's currently showing. */ public enum FragmentType { /** The Detailed Info fragment. */ DETAILS, /** The Wiki fragment. */ WIKI } /** The bundle key for the Info. */ public final static String INFO = "info"; /** * The bundle key for if permissions were explicitly denied coming into the * fragment. */ public final static String PERMISSIONS_DENIED = "permissionsDenied"; /** * Now, what you've got here is your garden-variety interface that something * ought to implement to handle the close button on this here fragment. */ public interface CloseListener { /** * Called when the user clicks the close button. Use this opportunity * to either dismiss the fragment or close the activity that contains * it. * * @param fragment the CentralMapExtraFragment that is about to be closed */ void extraFragmentClosing(CentralMapExtraFragment fragment); /** * Called during onDestroy(). ExpeditionMode needs this so it knows * when the user backed out of the fragment, as opposed to just the * close button. * * @param fragment the CentralMapExtraFragment that is being destroyed */ void extraFragmentDestroying(CentralMapExtraFragment fragment); } protected CloseListener mCloseListener; protected Info mInfo; protected boolean mPermissionsDenied; /** * Sets what'll be listening for the close button and/or an onDestroy event. * * @param listener some CloseListener somewhere */ public void setCloseListener(CloseListener listener) { mCloseListener = listener; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // First, see if there's an instance state. if(savedInstanceState != null) { // If so, use what's in there. mInfo = savedInstanceState.getParcelable(INFO); mPermissionsDenied = savedInstanceState.getBoolean(PERMISSIONS_DENIED, false); } else { // If not, go to the arguments. Bundle args = getArguments(); if(args != null) { mInfo = args.getParcelable(INFO); mPermissionsDenied = args.getBoolean(PERMISSIONS_DENIED, false); } } } @Override public void onDestroy() { // The parent needs to know when this fragment is destroyed so it can // make the FrameLayout go away. if(mCloseListener != null) mCloseListener.extraFragmentDestroying(this); super.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Remember that last info. Owing to how ExpeditionMode works, it might // have changed since arguments time. If it DIDN'T change, well, it'll // be the same as the arguments anyway. outState.putParcelable(INFO, mInfo); outState.putBoolean(PERMISSIONS_DENIED, mPermissionsDenied); } /** * Registers a button (or, well, a {@link View} in general) to act as the * close button, calling the close method on the CloseListener. * * @param v the View that will act as the close button */ protected void registerCloseButton(@NonNull View v) { v.setOnClickListener(v1 -> { if(mCloseListener != null) mCloseListener.extraFragmentClosing(CentralMapExtraFragment.this); }); } /** * Sets the Info for this fragment, to whatever degree that's useful for it. * Whatever gets set here will override any arguments originally passed in * if and when onSaveInstanceState is needed. * * @param info that new Info */ public void setInfo(@Nullable final Info info) { mInfo = info; } /** * Gets what type of CentralMapExtraFragment this is so you don't have to * keep using instanceof. Stop that. * * @return a FragmentType enum */ @NonNull public abstract FragmentType getType(); /** * Static factory that makes an Intent for a given FragmentType's Activity * container. This happens if the user's on a phone. * * @param type the type * @return one factory-direct Intent */ @NonNull public static Intent makeIntentForType(Context c, FragmentType type) { switch(type) { case DETAILS: return new Intent(c, DetailedInfoActivity.class); case WIKI: return new Intent(c, WikiActivity.class); } throw new RuntimeException("I don't know what sort of FragmentType " + type + " is supposed to be!"); } /** * Static factory that makes a Fragment for a given FragmentType. This * happens if the user's on a tablet. * * @param type the type * @return a fragment */ public static CentralMapExtraFragment makeFragmentForType(FragmentType type) { switch(type) { case DETAILS: return new DetailedInfoFragment(); case WIKI: return new WikiFragment(); } throw new RuntimeException("I don't know what sort of FragmentType " + type + " is supposed to be!"); } }
33.70297
125
0.657609
c03ec959587e1cfb3d54ecf18d9153e81ae7ec58
1,111
package ee.pri.rl.algorithmics.sort; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class HeapsortBenchmark { public static void main(String[] args) throws IOException { File out = new File("data/heapsort.dat"); BufferedWriter writer = new BufferedWriter(new FileWriter(out)); int count = 100; while (count <= 10 * 1000 * 1000) { System.gc(); int[] array = SortUtil.generateRandomIntArray(count, Integer.MAX_VALUE); long start = System.currentTimeMillis(); Heapsort.sort(array); long endHeapsort = System.currentTimeMillis() - start; System.gc(); array = SortUtil.generateSortedIntArray(count, Integer.MAX_VALUE, false); start = System.currentTimeMillis(); RandomizedQuicksort.sort(array); long endRandomizedQuicksort = System.currentTimeMillis() - start; if (count >= 1000) { writer.append(count + " " + endHeapsort + " " + endRandomizedQuicksort); writer.newLine(); } System.out.println(count); count *= 2; } writer.close(); } }
23.145833
76
0.679568
a74ef2d6e6c366cf49b0dd7e64091735429d9748
254
package ru.yandex.qatools.allure.testng.testdata; import org.junit.Test; /** * @author Dmitry Baev charlie@yandex-team.ru * Date: 25.02.15 */ public class SimpleTestngTest { @Test public void simpleTest() throws Exception { } }
16.933333
49
0.673228
94765218549b27fa47a37bdd105d02eb031e7362
2,292
package ru.stqa.pft.adressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.adressbook.model.ContactData; import ru.stqa.pft.adressbook.model.Contacts; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class ContactModificationTest extends TestBase { @BeforeMethod public void ensurePreconditions() { app.goTo().homePage(); if (app.contact().all().size()==0) { app.contact().create(new ContactData() .withFirstName("TheFirstName") .withMiddleName("middleName") .withLastName("lastName") .withTitle("testTitle") .withCompany("testCompany") .withAddress("test address") .withHomePhone("1") .withMobilePhone("+23456789") .withWorkPhone("+12345677") .withEmail("test@test.com") .witBirthDay("18") .withBirthMonth("December") .withBirthYear("1990") .withSecondaryAddress("TheTest2") .withSecondaryHome("secondaryHome") .withSelectGroup("TheTest2") , true); } app.goTo().homePage(); } @Test public void testContactModification() throws Exception { Contacts before = app.contact().all(); ContactData modifiedContact = before.iterator().next(); ContactData contact = new ContactData() .withId(modifiedContact.getId()) .withFirstName("ChangedFirstName") .withLastName("ChangedLastName") .witBirthDay("18") .withBirthMonth("December") .withBirthYear("1990"); app.contact().modify(contact); app.goTo().homePage(); assertThat(app.contact().count(), equalTo(before.size())); Contacts after = app.contact().all(); contact.withId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId()); before.remove(modifiedContact); before.add(contact); assertThat(after, equalTo(before)); } }
39.517241
110
0.573298
2f895c134fb430a89908c371e0a628353522b2b6
4,037
/* * MIT License * * Copyright (c) 2017 Barracks Inc. * * 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 io.barracks.membergateway.rest; import io.barracks.membergateway.manager.StatsManager; import io.barracks.membergateway.model.DataSet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; import java.time.OffsetDateTime; @RestController @RequestMapping("/stats") public class StatsResource { static final OffsetDateTime DEFAULT_START = OffsetDateTime.MIN; static final OffsetDateTime DEFAULT_END = OffsetDateTime.MAX; private final StatsManager statsManager; @Autowired public StatsResource(StatsManager statsManager) { this.statsManager = statsManager; } @RequestMapping("/devices/perVersionId") public DataSet getDeviceCountPerVersionId(Principal principal) { return statsManager.getDevicesPerVersionId(principal.getName()); } @RequestMapping("/devices/lastSeen") public DataSet getLastSeenDevices( Principal principal, @RequestParam(required = false, name = "start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime start, @RequestParam(required = false, name = "end") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime end ) { if (start == null) { start = DEFAULT_START; } if (end == null) { end = DEFAULT_END; } return statsManager.getLastSeenDevices(principal.getName(), start, end); } @RequestMapping("/devices/seen") public DataSet getSeenDevices( Principal principal, @RequestParam(required = false, name = "start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime start, @RequestParam(required = false, name = "end") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime end ) { if (start == null) { start = DEFAULT_START; } if (end == null) { end = DEFAULT_END; } return statsManager.getSeenDevices(principal.getName(), start, end); } @RequestMapping("/devices/perSegmentId") public DataSet getDevicesPerSegmentId( Principal principal, @RequestParam(name = "updated", defaultValue = "false", required = false) boolean updated ) { if (updated) { return statsManager.getUpdatedDevicesPerSegmentId(principal.getName()); } else { return statsManager.getDevicesPerSegmentId(principal.getName()); } } }
37.728972
85
0.68541
c73b647314feb5a4c3cba26d19742f5d1c379403
359
public interface Level { /** * Set how many total bubbles the level will have * * @param numBubbles */ void setNumberBubbles(int numBubbles); /** * Set how many lives a player has for that specific level * * @param numLives The number of lives a player should start this level with */ void setNumberOfLives(int numLives); }
19.944444
78
0.674095
6da8abb20007becff442997b32f4d601f2f7c2f5
1,986
package lv.llu.science.dwh.vaults; import lombok.Getter; import lombok.extern.java.Log; import lv.llu.science.dwh.domain.messages.DataInMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListenerConfigurer; import org.springframework.jms.config.JmsListenerEndpointRegistrar; import org.springframework.jms.config.SimpleJmsListenerEndpoint; import org.springframework.jms.support.converter.MappingJackson2MessageConverter; import org.springframework.stereotype.Service; import javax.jms.JMSException; import java.util.List; import static java.text.MessageFormat.format; @Service @Log public class VaultsTopicConfigurator implements JmsListenerConfigurer { private final MappingJackson2MessageConverter converter; @Getter private List<BasicDataInVault> dataInVaults; @Autowired public VaultsTopicConfigurator(MappingJackson2MessageConverter converter) { this.converter = converter; } @Autowired public void setDataInVaults(List<BasicDataInVault> dataInVaults) { this.dataInVaults = dataInVaults; } @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { for (BasicDataInVault vault : dataInVaults) { SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint(); endpoint.setId("data-in-" + vault.getDataInTopic()); endpoint.setDestination("swamp:" + vault.getDataInTopic()); endpoint.setMessageListener(message -> { try { DataInMessage payload = (DataInMessage) converter.fromMessage(message); vault.receiveDataInMessage(payload); } catch (JMSException e) { e.printStackTrace(); } }); registrar.registerEndpoint(endpoint); log.info(format("Registered data-in topic: {0}", vault.getDataInTopic())); } } }
36.109091
91
0.715509
625315777e43e991727784101109815ce3eac2f6
1,148
package com.github.ruediste.lambdaPegParser.weaving; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; /** * Method Visitor determining the minimal and maximal line number in a method */ public class MinMaxLineMethodAdapter extends MethodVisitor { private Integer minLineNumber; private Integer maxLineNumber; public MinMaxLineMethodAdapter(int api, MethodVisitor mv) { super(api, mv); } public Integer getMaxLineNumber() { return maxLineNumber; } public int getMaxLineNumberOr(int fallback) { return maxLineNumber == null ? fallback : maxLineNumber; } public Integer getMinLineNumber() { return minLineNumber; } public int getMinLineNumberOr(int fallback) { return minLineNumber == null ? fallback : minLineNumber; } @Override public void visitLineNumber(int line, Label start) { if (minLineNumber == null || minLineNumber > line) minLineNumber = line; if (maxLineNumber == null || maxLineNumber < line) maxLineNumber = line; super.visitLineNumber(line, start); } }
26.697674
77
0.681185
a8ef854c0d072f4afc1e1df56b16e9dbb4150297
2,326
//package com.vaadin.addon.spreadsheet.test; // //import static org.junit.Assert.assertEquals; //import static org.junit.Assert.assertNotEquals; // //import org.junit.Test; // //import com.vaadin.addon.spreadsheet.test.fixtures.TestFixtures; //import com.vaadin.testbench.parallel.Browser; // //public class HideTest extends AbstractSpreadsheetTestCase { // // @Test // public void testHideColumn() { // headerPage.createNewSpreadsheet(); // // sheetController.selectCell("C2"); // headerPage.loadTestFixture(TestFixtures.ColumnToggle); // assertCellIsVisible("B2"); // assertCellIsHidden("C2"); // assertCellIsVisible("D2"); // // sheetController.selectRegion("B2", "D2"); // headerPage.loadTestFixture(TestFixtures.ColumnToggle); // assertCellIsHidden("B2"); // assertCellIsVisible("C2"); // assertCellIsHidden("D2"); // } // // @Test // public void testHideRow() { // headerPage.createNewSpreadsheet(); // skipBrowser("Fails on phantom JS, B3 is visible after hiding region", Browser.PHANTOMJS); // // sheetController.selectCell("B3"); // headerPage.loadTestFixture(TestFixtures.RowToggle); // assertCellIsVisible("B2"); // assertCellIsHidden("B3"); // assertCellIsVisible("B4"); // // sheetController.selectRegion("B2", "B4"); // headerPage.loadTestFixture(TestFixtures.RowToggle); // assertCellIsHidden("B2"); // assertCellIsVisible("B3"); // assertCellIsHidden("B4"); // } // // private void assertCellIsHidden(String cell) { // try { // assertEquals("Cell " + cell + " should be HIDDEN.", "none", // sheetController.getCellStyle(cell, "display")); // } catch (AssertionError error) { // assertEquals("Cell " + cell + " should be HIDDEN.", "0px", // sheetController.getCellStyle(cell, "height")); // } // } // // private void assertCellIsVisible(String cell) { // assertNotEquals("Cell " + cell + " should be VISIBLE.", "none", // sheetController.getCellStyle(cell, "display")); // assertNotEquals("Cell " + cell + " should be VISIBLE.", "0px", // sheetController.getCellStyle(cell, "height")); // } //}
35.784615
99
0.614789
0d53f031ad8a80219895c7046ed1c9af68788c56
10,084
/* * Copyright 2018-2020 Pavel Ponec, * https://github.com/pponec/ujorm/blob/master/project-m2/ujo-tools/src/main/java/org/ujorm/tools/XmlElement.java * * 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.ujorm.tools.xml.model; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.ujorm.tools.Assert; import org.ujorm.tools.Check; import org.ujorm.tools.xml.AbstractWriter; import org.ujorm.tools.xml.ApiElement; import org.ujorm.tools.xml.config.XmlConfig; import org.ujorm.tools.xml.model.XmlModel.RawEnvelope; import static org.ujorm.tools.xml.AbstractWriter.*; import static org.ujorm.tools.xml.config.impl.DefaultXmlConfig.REQUIRED_MSG; /** * XML element <strong>model</strong> to rendering a XML file. * The main benefits are: * <ul> * <li>secure building well-formed XML documents by the Java code</li> * <li>a simple API built on a single XmlElement class</li> * <li>creating XML components by a subclass is possible</li> * <li>great performance and small memory footprint</li> * </ul>¨ * <h3>How to use the class:</h3> * <pre class="pre"> * XmlElement root = new XmlElement("root"); * root.addElement("childA") * .setAttrib("x", 1) * .setAttrib("y", 2); * root.addElement("childB") * .setAttrib("x", 3) * .setAttrib("y", 4) * .addText("A text message &lt;&\"&gt;"); * root.addRawText("\n&lt;rawXml/&gt;\n"); * root.addCDATA("A character data &lt;&\"&gt;"); * String result = root.toString(); * </pre> * * @see HtmlElement * @since 2.03 * @author Pavel Ponec */ public class XmlModel implements ApiElement<XmlModel>, Serializable { /** Element name */ @Nullable protected final String name; /** Attributes */ @Nullable protected Map<String, Object> attributes; /** Child elements with a {@code null} items */ @Nullable protected List<Object> children; /** * @param name The element name must not be special HTML characters. * The {@code null} value is intended to build a root of AJAX queries. */ public XmlModel(@Nonnull final String name) { this.name = name; } /** New element with a parent */ public XmlModel(@Nonnull final String name, @Nonnull final XmlModel parent) { this(name); parent.addChild(this); } @Nullable @Override public String getName() { return name; } /** Return attributes */ @Nonnull protected Map<String, Object> getAttribs() { if (attributes == null) { attributes = new LinkedHashMap<>(); } return attributes; } /** Add a child entity */ @Nonnull protected void addChild(@Nullable final Object child) { if (children == null) { children = new ArrayList<>(); } children.add(child); } /** * Add a child element * @param element Add a child element is required. An undefined argument is ignored. * @return The argument type of XmlElement! */ @Nonnull public final XmlModel addElement(@Nonnull final XmlModel element) { addChild(Assert.notNull(element, REQUIRED_MSG, "element")); return element; } /** Create a new {@link XmlModel} for a required name and add it to children. * @param name A name of the new XmlElement is required. * @return The new XmlElement! */ @Override @Nonnull public XmlModel addElement(@Nonnull final String name) { return new XmlModel(name, this); } /** * Set one attribute * @param name Required element name * @param value The {@code null} value is ignored. Formatting is performed by the * {@link XmlWriter#writeValue(java.lang.Object, org.ujorm.tools.dom.XmlElement, java.lang.String, java.io.Writer) } * method, where the default implementation calls a {@code toString()} only. * @return The original element */ @Override @Nonnull public final XmlModel setAttribute(@Nonnull final String name, @Nullable final Object value) { Assert.hasLength(name, REQUIRED_MSG, "name"); if (value != null) { if (attributes == null) { attributes = new LinkedHashMap<>(); } attributes.put(name, value); } return this; } /** * Add a text and escape special character * @param value The {@code null} value is allowed. Formatting is performed by the * {@link XmlWriter#writeValue(java.lang.Object, org.ujorm.tools.dom.XmlElement, java.lang.String, java.io.Writer) } * method, where the default implementation calls a {@code toString()} only. * @return This instance */ @Override @Nonnull public final XmlModel addText(@Nullable final Object value) { addChild(value); return this; } /** * Message template with hight performance. * * @param template Message template where parameters are marked by the {@code {}} symbol * @param values argument values * @return The original builder */ @Override @Nonnull public final XmlModel addTextTemplated(@Nullable final CharSequence template, @Nonnull final Object... values) { try { return addText(AbstractWriter.FORMATTER.formatMsg(null, template, values)); } catch (IOException e) { throw new IllegalStateException(e); } } /** Add an native text with no escaped characters, for example: XML code, JavaScript, CSS styles * @param value The {@code null} value is ignored. * @return This instance */ @Override @Nonnull public final XmlModel addRawText(@Nullable final Object value) { if (value != null) { addChild(new RawEnvelope(value)); } return this; } /** * Add a <strong>comment text</strong>. * The CDATA structure isn't really for HTML at all. * @param comment A comment text must not contain a string {@code -->} . * @return This instance */ @Override @Nonnull public final XmlModel addComment(@Nullable final CharSequence comment) { if (Check.hasLength(comment)) { Assert.isTrue(!comment.toString().contains(COMMENT_END), "The text contains a forbidden string: " + COMMENT_END); StringBuilder msg = new StringBuilder ( COMMENT_BEG.length() + COMMENT_END.length() + comment.length() + 2); addRawText(msg.append(COMMENT_BEG) .append(SPACE) .append(comment) .append(SPACE) .append(COMMENT_END)); } return this; } /** * Add a <strong>character data</strong> in {@code CDATA} format to XML only. * The CDATA structure isn't really for HTML at all. * @param charData A text including the final DATA sequence. An empty argument is ignored. * @return This instance */ @Override @Nonnull public final XmlModel addCDATA(@Nullable final CharSequence charData) { if (Check.hasLength(charData)) { addRawText(CDATA_BEG); final String text = charData.toString(); int i = 0, j; while ((j = text.indexOf(CDATA_END, i)) >= 0) { j += CDATA_END.length(); addRawText(text.subSequence(i, j)); i = j; addText(CDATA_END); addRawText(CDATA_BEG); } addRawText(i == 0 ? text : text.substring(i)); addRawText(CDATA_END); } return this; } /** Get an unmodifiable map of attributes */ @Nonnull public Map<String, Object> getAttributes() { return attributes != null ? Collections.unmodifiableMap(attributes) : Collections.emptyMap(); } /** Get an unmodifiable list of children */ @Nonnull public List<Object> getChildren() { return children != null ? Collections.unmodifiableList(children) : Collections.emptyList(); } /** An empty method */ @Override public final void close() { } /** Render the XML code including header */ @Nonnull @Override public String toString() { try { final XmlConfig config = XmlConfig.ofDefault(); final XmlWriter writer = new XmlWriter(new StringBuilder(512) .append(AbstractWriter.XML_HEADER) .append(config.getNewLine())); return toWriter(0, writer).toString(); } catch (IOException e) { throw new IllegalStateException(e); } } /** Render the XML code without header */ @Nonnull public XmlWriter toWriter(final int level, @Nonnull final XmlWriter out) throws IOException { return out.write(level, this); } // -------- Inner class -------- /** Raw XML code envelope */ protected static final class RawEnvelope { /** XML content */ @Nonnull private final Object body; public RawEnvelope(@Nonnull final Object body) { this.body = body; } /** Get the body */ @Nonnull public Object get() { return body; } } }
32.846906
125
0.616422
85ff28d2113cd402bf0e4da9918bd147e747560f
38,862
package com.meterware.httpunit; /******************************************************************************************************************** * $Id: WebForm.java 952 2008-05-02 16:01:23Z wolfgang_fahl $ * * Copyright (c) 2000-2008, Russell Gold * * 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. * *******************************************************************************************************************/ import com.meterware.httpunit.scripting.NamedDelegate; import com.meterware.httpunit.scripting.ScriptableDelegate; import com.meterware.httpunit.scripting.FormScriptable; import com.meterware.httpunit.protocol.UploadFileSpec; import com.meterware.httpunit.protocol.ParameterProcessor; import java.io.IOException; import java.io.File; import java.net.URL; import java.net.UnknownServiceException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.w3c.dom.Node; import org.w3c.dom.html.HTMLFormElement; import org.w3c.dom.html.HTMLCollection; import org.xml.sax.SAXException; /** * This class represents a form in an HTML page. Users of this class may examine the parameters * defined for the form, the structure of the form (as a DOM), or the text of the form. They * may also create a {@link WebRequest} to simulate the submission of the form. * * @author <a href="mailto:russgold@httpunit.org">Russell Gold</a> **/ public class WebForm extends WebRequestSource { private static final FormParameter UNKNOWN_PARAMETER = new FormParameter(); private final static String[] NO_VALUES = new String[0]; private Button[] _buttons; /** The submit buttons in this form. **/ private SubmitButton[] _submitButtons; /** The character set in which the form will be submitted. **/ private String _characterSet; private Vector _buttonVector; private FormControl[] _presetParameters; private ArrayList _presets; private ElementRegistry _registry; /** Predicate to match a link's name. **/ public final static HTMLElementPredicate MATCH_NAME; private HTMLFormElement _domElement; /** * Submits this form using the web client from which it was originally obtained. **/ public WebResponse submit() throws IOException, SAXException { return submit( getDefaultButton() ); } /** * Submits this form using the web client from which it was originally obtained. * Will usually return the result of that submission; however, if the submit button's 'onclick' * or the form's 'onsubmit' event is triggered and * inhibits the submission, will return the updated contents of the frame containing this form. **/ public WebResponse submit( SubmitButton button ) throws IOException, SAXException { WebResponse result=submit(button,0,0); return result; } /** * Submits this form using the web client from which it was originally obtained. * Will usually return the result of that submission; however, if the submit button's 'onclick' * or the form's 'onsubmit' event is triggered and * inhibits the submission, will return the updated contents of the frame containing this form. * @since 1.6 **/ public WebResponse submit( SubmitButton button, int x, int y ) throws IOException, SAXException { WebResponse result=null; if (button==null || button.doOnClickSequence(x, y)) { result= doFormSubmit( button, x, y ); } else { result=getCurrentFrameContents(); } return result; } /** * Submits this form using the web client from which it was originally obtained, ignoring any buttons defined for the form. * @since 1.6 **/ public WebResponse submitNoButton() throws SAXException, IOException { return submit( SubmitButton.createFakeSubmitButton( this /* fake */ ) ); } protected WebResponse submitRequest( String event, WebRequest request ) throws IOException, SAXException { try { return super.submitRequest( event, request ); } catch (UnknownServiceException e) { throw new UnsupportedActionException( "HttpUnit does not support " + request.getURL().getProtocol() + " URLs in form submissions" ); } } /** * Submits the form without also invoking the button's "onclick" event. */ WebResponse doFormSubmit( SubmitButton button ) throws IOException, SAXException { return submitRequest( getAttribute( "onsubmit" ), getRequest( button ) ); } WebResponse doFormSubmit( SubmitButton button, int x, int y ) throws IOException, SAXException { return submitRequest( getAttribute( "onsubmit" ), getRequest( button, x, y ) ); } /** * Returns the method defined for this form. **/ public String getMethod() { return getAttribute( "method", "GET" ); } /** * Returns the action defined for this form. **/ public String getAction() { return getDestination(); } /** * Returns true if a parameter with given name exists in this form. **/ public boolean hasParameterNamed( String soughtName ) { return getFormParameters().containsKey( soughtName ); } /** * Returns true if a parameter starting with a given name exists, **/ public boolean hasParameterStartingWithPrefix( String prefix ) { String[] names = getParameterNames(); for (int i = 0; i < names.length; i++) { if (names[i].startsWith( prefix )) return true; } return false; } /** * Returns an array containing all of the buttons defined for this form. **/ public Button[] getButtons() { if (_buttons == null) { FormControl[] controls = getFormControls(); ArrayList buttonList = new ArrayList(); for (int i = 0; i < controls.length; i++) { FormControl control = controls[ i ]; if (control instanceof Button) buttonList.add( control ); } _buttons = (Button[]) buttonList.toArray( new Button[ buttonList.size() ] ); } return _buttons; } public Button getButton( HTMLElementPredicate predicate, Object criteria ) { Button[] buttons = getButtons(); for (int i = 0; i < buttons.length; i++) { if (predicate.matchesCriteria( buttons[i], criteria )) return buttons[i]; } return null; } /** * Convenience method which returns the button with the specified ID. */ public Button getButtonWithID( String buttonID ) { return getButton( Button.WITH_ID, buttonID ); } /** * Returns an array containing the submit buttons defined for this form. **/ public SubmitButton[] getSubmitButtons() { if (_submitButtons == null) { Vector buttons = getSubmitButtonVector(); _submitButtons = new SubmitButton[ buttons.size() ]; buttons.copyInto( _submitButtons ); } return _submitButtons; } /** * Returns the submit button defined in this form with the specified name. * If more than one such button exists, will return the first found. * If no such button is found, will return null. **/ public SubmitButton getSubmitButton( String name ) { SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { if (buttons[i].getName().equals( name )) { return buttons[i]; } } return null; } /** * Returns the submit button defined in this form with the specified name and value. * If more than one such button exists, will return the first found. * If no such button is found, will return null. **/ public SubmitButton getSubmitButton( String name, String value ) { SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { if (buttons[i].getName().equals( name ) && buttons[i].getValue().equals( value )) { return buttons[i]; } } return null; } /** * Returns the submit button defined in this form with the specified ID. * If more than one such button exists, will return the first found. * If no such button is found, will return null. **/ public SubmitButton getSubmitButtonWithID( String ID ) { SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { if (buttons[i].getID().equals( ID )) { return buttons[i]; } } return null; } /** * Creates and returns a web request which will simulate the submission of this form with a button with the specified name and value. **/ public WebRequest getRequest( String submitButtonName, String submitButtonValue ) { SubmitButton sb = getSubmitButton( submitButtonName, submitButtonValue ); if (sb == null) throw new IllegalSubmitButtonException( submitButtonName, submitButtonValue ); return getRequest( sb ); } /** * Creates and returns a web request which will simulate the submission of this form with a button with the specified name. **/ public WebRequest getRequest( String submitButtonName ) { SubmitButton sb = getSubmitButton( submitButtonName ); if (sb == null) throw new IllegalSubmitButtonException( submitButtonName, "" ); return getRequest( sb ); } /** * Creates and returns a web request which will simulate the submission of this form by pressing the specified button. * If the button is null, simulates the pressing of the default button. **/ public WebRequest getRequest( SubmitButton button ) { return getRequest( button, 0, 0 ); } /** * Creates and returns a web request which will simulate the submission of this form by pressing the specified button. * If the button is null, simulates the pressing of the default button. * @param button - the submitbutton to be pressed - may be null * @param x - the x position * @param y - the y position **/ public WebRequest getRequest( SubmitButton button, int x, int y ) { if (button == null) button = getDefaultButton(); if (HttpUnitOptions.getParameterValuesValidated()) { if (button == null) { throw new IllegalUnnamedSubmitButtonException(); } else if (button.isFake()) { // bypass checks } else if (!getSubmitButtonVector().contains( button )) { throw new IllegalSubmitButtonException( button ); } else if (!button.wasEnabled()) { // this is too late for the check of isDisabled() // onclick has already been done ... // [ 1289151 ] Order of events in button.click() is wrong button.throwDisabledException(); } } SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { buttons[i].setPressed( false ); } button.setPressed( true ); if (getMethod().equalsIgnoreCase( "post" )) { return new PostMethodWebRequest( this, button, x, y ); } else { return new GetMethodWebRequest( this, WebRequest.newParameterHolder( this ), button, x, y ); } } /** * Creates and returns a web request which includes the specified button. If no button is specified, will include * the default button, if any. No parameter validation will be done on the returned request and no scripts * will be run when it is submitted. **/ public WebRequest newUnvalidatedRequest( SubmitButton button ) { return newUnvalidatedRequest( button, 0, 0 ); } /** * Creates and returns a web request which includes the specified button and position. If no button is specified, * will include the default button, if any. No parameter validation will be done on the returned request * and no scripts will be run when it is submitted. **/ public WebRequest newUnvalidatedRequest( SubmitButton button, int x, int y ) { if (button == null) button = getDefaultButton(); SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { buttons[i].setPressed( false ); } button.setPressed( true ); if (getMethod().equalsIgnoreCase( "post" )) { return new PostMethodWebRequest( this, new UncheckedParameterHolder( this ), button, x, y ); } else { return new GetMethodWebRequest( this, new UncheckedParameterHolder( this ), button, x, y ); } } private WebRequest getScriptedSubmitRequest() { SubmitButton[] buttons = getSubmitButtons(); for (int i = 0; i < buttons.length; i++) { buttons[i].setPressed( false ); } if (getMethod().equalsIgnoreCase( "post" )) { return new PostMethodWebRequest( this ); } else { return new GetMethodWebRequest( this ); } } /** * Returns the default value of the named parameter. If the parameter does not exist returns null. **/ public String getParameterValue( String name ) { String[] values = getParameterValues( name ); return values.length == 0 ? null : values[0]; } /** * Returns the displayed options defined for the specified parameter name. **/ public String[] getOptions( String name ) { return getParameter( name ).getOptions(); } /** * Returns the option values defined for the specified parameter name. **/ public String[] getOptionValues( String name ) { return getParameter( name ).getOptionValues(); } /** * Returns true if the named parameter accepts multiple values. **/ public boolean isMultiValuedParameter( String name ) { return getParameter( name ).isMultiValuedParameter(); } /** * Returns the number of text parameters in this form with the specified name. **/ public int getNumTextParameters( String name ) { return getParameter( name ).getNumTextParameters(); } /** * Returns true if the named parameter accepts free-form text. **/ public boolean isTextParameter( String name ) { return getParameter( name ).isTextParameter(); } /** * Returns true if this form is to be submitted using mime encoding (the default is URL encoding). **/ public boolean isSubmitAsMime() { return "multipart/form-data".equalsIgnoreCase( getAttribute( "enctype" ) ); } public FormScriptable getScriptableObject() { return (FormScriptable) getScriptingHandler(); } /** * Resets all parameters to their initial values. */ public void reset() { if (handleEvent("onreset")) resetControls(); } private void resetControls() { FormControl[] controls = getFormControls(); for (int i = 0; i < controls.length; i++) { controls[i].reset(); } } public ScriptableDelegate newScriptable() { return new Scriptable(); } //---------------------------------- WebRequestSource methods -------------------------------- /** * Returns the character set encoding for this form. **/ public String getCharacterSet() { return _characterSet; } /** * Returns true if the named parameter accepts files for upload. **/ public boolean isFileParameter( String name ) { return getParameter( name ).isFileParameter(); } /** * Returns an array containing the names of the parameters defined for this form. **/ public String[] getParameterNames() { ArrayList parameterNames = new ArrayList( getFormParameters().keySet() ); return (String[]) parameterNames.toArray( new String[ parameterNames.size() ] ); } /** * Returns the multiple default values of the named parameter. **/ public String[] getParameterValues( String name ) { final FormParameter parameter = getParameter( name ); return parameter.getValues(); } /** * Returns true if the named parameter is read-only. If more than one control exists with the same name, * will return true only if all such controls are read-only. **/ public boolean isReadOnlyParameter( String name ) { return getParameter( name ).isReadOnlyParameter(); } /** * Returns true if the named parameter is disabled. If more than one control exists with the same name, * will return true only if all such controls are read-only. **/ public boolean isDisabledParameter( String name ) { return getParameter( name ).isDisabledParameter(); } /** * Returns true if the named parameter is hidden. If more than one control exists with the same name, * will return true only if all such controls are hidden. **/ public boolean isHiddenParameter( String name ) { return getParameter( name ).isHiddenParameter(); } /** * Creates and returns a web request which will simulate the submission of this form with an unnamed submit button. **/ public WebRequest getRequest() { return getRequest( (SubmitButton) null ); } /** * Creates and returns a web request based on the current state of this form. No parameter validation will be done * and there is no guarantee over the order of parameters transmitted. */ public WebRequest newUnvalidatedRequest() { return newUnvalidatedRequest( null ); } /** * Records a parameter defined by including it in the destination URL. Ignores any parameters whose name matches * a form control. **/ protected void addPresetParameter( String name, String value ) { FormControl[] formControls = getFormControls(); for (int i = 0; i < formControls.length; i++) { if (formControls[i].getName().equals( name)) return; } _presets.add( new PresetFormParameter( this, name, value ) ); } protected String getEmptyParameterValue() { return null; } //---------------------------------- ParameterHolder methods -------------------------------- /** * Specifies the position at which an image button (if any) was clicked. **/ void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { imageButton.setLocation( x, y ); } /** * Iterates through the fixed, predefined parameters in this holder, recording them in the supplied parameter processor.\ * These parameters always go on the URL, no matter what encoding method is used. **/ void recordPredefinedParameters( ParameterProcessor processor ) throws IOException { FormControl[] controls = getPresetParameters(); for (int i = 0; i < controls.length; i++) { controls[i].addValues( processor, getCharacterSet() ); } } /** * Iterates through the parameters in this holder, recording them in the supplied parameter processor. **/ public void recordParameters( ParameterProcessor processor ) throws IOException { FormControl[] controls = getFormControls(); for (int i = 0; i < controls.length; i++) { controls[i].addValues( processor, getCharacterSet() ); } } /** * Removes a parameter name from this collection. **/ public void removeParameter( String name ) { setParameter( name, NO_VALUES ); } /** * Sets the value of a parameter in this form. * @param name - the name of the parameter * @param value - the value of the parameter **/ public void setParameter( String name, String value ) { setParameter( name, new String[] { value } ); } /** * Sets the multiple values of a parameter in this form. This is generally used when there are multiple * controls with the same name in the form. */ public void setParameter( String name, final String[] values ) { FormParameter parameter = getParameter( name ); if (parameter == UNKNOWN_PARAMETER) throw new NoSuchParameterException( name ); if (parameter.isFileParameter()) { throw new InvalidFileParameterException(name,values); } parameter.setValues( values ); } /** * Sets the multiple values of a file upload parameter in a web request. **/ public void setParameter( String name, UploadFileSpec[] files ) { FormParameter parameter = getParameter( name ); if ((parameter == null) || (!parameter.isFileParameter())) throw new NoSuchParameterException( name ); parameter.setFiles( files ); } /** * Sets the single value of a file upload parameter in this form. * A more convenient way to do this than using {@link #setParameter(String,com.meterware.httpunit.protocol.UploadFileSpec[])} * @since 1.6 */ public void setParameter( String name, File file ) { setParameter( name, new UploadFileSpec[] { new UploadFileSpec( file ) } ); } /** * Toggles the value of the specified checkbox parameter. * @param name the name of the checkbox parameter * @throws IllegalArgumentException if the specified parameter is not a checkbox or there is more than one * control with that name. * @since 1.5.4 */ public void toggleCheckbox( String name ) { FormParameter parameter = getParameter( name ); if (parameter == null) throw new NoSuchParameterException( name ); parameter.toggleCheckbox(); } /** * Toggles the value of the specified checkbox parameter. * @param name the name of the checkbox parameter * @param value of the checkbox parameter * @throws IllegalArgumentException if the specified parameter is not a checkbox or if there is no checkbox * with the specified name and value. * @since 1.6 */ public void toggleCheckbox( String name, String value ) { FormParameter parameter = getParameter( name ); if (parameter == null) throw new NoSuchParameterException( name ); parameter.toggleCheckbox( value ); } /** * Sets the value of the specified checkbox parameter. * @param name the name of the checkbox parameter * @param state the new state of the checkbox * @throws IllegalArgumentException if the specified parameter is not a checkbox or there is more than one * control with that name. * @since 1.5.4 */ public void setCheckbox( String name, boolean state ) { FormParameter parameter = getParameter( name ); if (parameter == null) throw new NoSuchParameterException( name ); parameter.setValue( state ); } /** * Sets the value of the specified checkbox parameter. * @param name the name of the checkbox parameter * @param value of the checkbox parameter * @param state the new state of the checkbox * @throws IllegalArgumentException if the specified parameter is not a checkbox or if there is no checkbox * with the specified name and value. * @since 1.6 */ public void setCheckbox( String name, String value, boolean state ) { FormParameter parameter = getParameter( name ); if (parameter == null) throw new NoSuchParameterException( name ); parameter.setValue( value, state ); } public class Scriptable extends HTMLElementScriptable implements NamedDelegate, FormScriptable { public String getAction() { return WebForm.this.getAction(); } public void setAction( String newAction ) { setDestination( newAction ); _presetParameters = null; } public void submit() throws IOException, SAXException { submitRequest( getScriptedSubmitRequest() ); } public void reset() throws IOException, SAXException { resetControls(); } public String getName() { return WebForm.this.getID().length() != 0 ? WebForm.this.getID() : WebForm.this.getName(); } /** * get the Object for the given propertyName * @param propertyName - the name of the property to get * @return the Object for the property */ public Object get( String propertyName ) { if (propertyName.equals( "target" )) { return getTarget(); } else if (propertyName.equals( "action" )) { return getAction(); } else if (propertyName.equals( "length" )) { return new Integer(getFormControls().length); } else { final FormParameter parameter = getParameter( propertyName ); if (parameter != UNKNOWN_PARAMETER) return parameter.getScriptableObject(); FormControl control = getControlWithID( propertyName ); return control == null ? super.get( propertyName ) : control.getScriptingHandler(); } } /** * Sets the value of the named property. Will throw a runtime exception if the property does not exist or * cannot accept the specified value. * @param propertyName - the name of the property * @param value - the new value **/ public void set( String propertyName, Object value ) { if (propertyName.equals( "target" )) { setTargetAttribute( value.toString() ); } else if (propertyName.equals( "action" )) { setAction( value.toString() ); } else if (value instanceof String) { setParameterValue( propertyName, (String) value ); } else if (value instanceof Number) { setParameterValue( propertyName, HttpUnitUtils.trimmedValue( (Number) value ) ); } else { super.set( propertyName, value ); } } public void setParameterValue( String name, String value ) { final Object scriptableObject = getParameter( name ).getScriptableObject(); if (scriptableObject instanceof ScriptableDelegate) { ((ScriptableDelegate) scriptableObject).set( "value", value ); } else if (scriptableObject instanceof ScriptableDelegate[]) { ((ScriptableDelegate[]) scriptableObject)[0].set( "value", value ); } } public ScriptableDelegate[] getElementDelegates() { FormControl[] controls = getFormControls(); ScriptableDelegate[] result = new ScriptableDelegate[ controls.length ]; for (int i = 0; i < result.length; i++) { result[i] = (ScriptableDelegate) controls[i].getScriptingHandler(); } return result; } public ScriptableDelegate[] getElementsByTagName( String name ) throws SAXException { return getDelegates( getHTMLPage().getElementsByTagName( getElement(), name ) ); } Scriptable() { super( WebForm.this ); } } //---------------------------------- package members -------------------------------- /** * Contructs a web form given the URL of its source page and the DOM extracted * from that page. **/ WebForm( WebResponse response, URL baseURL, Node node, FrameSelector frame, String defaultTarget, String characterSet, ElementRegistry registry ) { super( response, node, baseURL, "action", frame, defaultTarget ); _characterSet = characterSet; _registry = registry; _domElement = (HTMLFormElement) node; } /** * Returns the form control which is part of this form with the specified ID. */ public FormControl getControlWithID( String id ) { FormControl[] controls = getFormControls(); for (int i = 0; i < controls.length; i++) { FormControl control = controls[i]; if (control.getID().equals(id)) return control; } return null; } //---------------------------------- private members -------------------------------- private SubmitButton getDefaultButton() { if (getSubmitButtons().length == 1) { return getSubmitButtons()[0]; } else { return getSubmitButton( "" ); } } /** * get the Vector of submit buttons - will always contain at least * one button - if the original vector has none a faked submit button will be added * @return a Vector with the submit buttons */ private Vector getSubmitButtonVector() { if (_buttonVector == null) { _buttonVector = new Vector(); FormControl[] controls = getFormControls(); for (int i = 0; i < controls.length; i++) { FormControl control = controls[ i ]; if (control instanceof SubmitButton) { SubmitButton sb=(SubmitButton)control; sb.rememberEnableState(); _buttonVector.add( sb ); } } /** * make sure that there is always at least one submit button * if none is in the Vector add a faked one */ if (_buttonVector.isEmpty()) _buttonVector.addElement( SubmitButton.createFakeSubmitButton( this ) ); } return _buttonVector; } private FormControl[] getPresetParameters() { if (_presetParameters == null) { _presets = new ArrayList(); loadDestinationParameters(); _presetParameters = (FormControl[]) _presets.toArray( new FormControl[ _presets.size() ] ); } return _presetParameters; } FormControl newFormControl( Node child ) { return FormControl.newFormParameter( this, child ); } /** * Returns an array of form parameter attributes for this form. **/ private FormControl[] getFormControls() { HTMLCollection controlElements = _domElement.getElements(); FormControl[] controls = new FormControl[ controlElements.getLength() ]; for (int i = 0; i < controls.length; i++) { controls[i] = getControlForNode( controlElements.item( i ) ); } return controls; } private FormControl getControlForNode( Node node ) { if (_registry.hasNode( node )) { return (FormControl) _registry.getRegisteredElement( node ); } else { return (FormControl) _registry.registerElement( node, newFormControl( node ) ); } } /** * get the form parameter with the given name * @param name * @return the form parameter with this name */ public FormParameter getParameter( String name ) { final FormParameter parameter = ((FormParameter) getFormParameters().get( name )); return parameter != null ? parameter : UNKNOWN_PARAMETER; } /** * Returns a map of parameter name to form parameter objects. Each form parameter object represents the set of form * controls with a particular name. Unnamed parameters are ignored. */ private Map getFormParameters() { Map formParameters = new HashMap(); loadFormParameters( formParameters, getPresetParameters() ); loadFormParameters( formParameters, getFormControls() ); return formParameters; } private void loadFormParameters( Map formParameters, FormControl[] controls ) { for (int i = 0; i < controls.length; i++) { if (controls[i].getName().length() == 0) continue; FormParameter parameter = (FormParameter) formParameters.get( controls[i].getName() ); if (parameter == null) { parameter = new FormParameter(); formParameters.put( controls[i].getName(), parameter ); } parameter.addControl( controls[i] ); } } static { MATCH_NAME = new HTMLElementPredicate() { public boolean matchesCriteria( Object htmlElement, Object criteria ) { return HttpUnitUtils.matches( ((WebForm) htmlElement).getName(), (String) criteria ); } }; } //===========================---===== exception class NoSuchParameterException ========================================= /** * This exception is thrown on an attempt to set a file parameter to a non file type **/ class InvalidFileParameterException extends IllegalRequestParameterException { /** * construct a new InvalidFileParameterException for the given parameter name and value list * @param parameterName * @param values */ InvalidFileParameterException( String parameterName, String[] values ) { _parameterName = parameterName; _values=values; } /** * get the message for this exception */ public String getMessage() { String valueList=""; String delim=""; for (int i=0;i<_values.length;i++) { valueList+=delim+"'"+_values[i]+"'"; delim=", "; } String msg="The file parameter with the name '"+_parameterName+"' must have type File but the string values "+valueList+" where supplied"; return msg; } private String _parameterName; private String[] _values; } /** * This exception is thrown on an attempt to set a parameter to a value not permitted to it by the form. **/ class NoSuchParameterException extends IllegalRequestParameterException { NoSuchParameterException( String parameterName ) { _parameterName = parameterName; } public String getMessage() { return "No parameter named '" + _parameterName + "' is defined in the form"; } private String _parameterName; } //============================= exception class IllegalUnnamedSubmitButtonException ====================================== /** * This exception is thrown on an attempt to define a form request with a button not defined on that form. **/ class IllegalUnnamedSubmitButtonException extends IllegalRequestParameterException { IllegalUnnamedSubmitButtonException() { } public String getMessage() { return "This form has more than one submit button, none unnamed. You must specify the button to be used."; } } //============================= exception class IllegalSubmitButtonException ====================================== /** * This exception is thrown on an attempt to define a form request with a button not defined on that form. **/ class IllegalSubmitButtonException extends IllegalRequestParameterException { IllegalSubmitButtonException( SubmitButton button ) { _name = button.getName(); _value = button.getValue(); } IllegalSubmitButtonException( String name, String value ) { _name = name; _value = value; } public String getMessage() { return "Specified submit button (name=\"" + _name + "\" value=\"" + _value + "\") not part of this form."; } private String _name; private String _value; } //============================= exception class IllegalUnnamedSubmitButtonException ====================================== } //========================================== class PresetFormParameter ================================================= class PresetFormParameter extends FormControl { PresetFormParameter( WebForm form, String name, String value ) { super( form ); _name = name; _value = value; } /** * Returns the name of this control.. **/ public String getName() { return _name; } /** * Returns true if this control is read-only. **/ public boolean isReadOnly() { return true; } /** * Returns true if this control accepts free-form text. **/ public boolean isTextControl() { return true; } /** * Remove any required values for this control from the list, throwing an exception if they are missing. **/ void claimRequiredValues( List values ) { if (_value != null) claimValueIsRequired( values, _value ); } public String getType() { return UNDEFINED_TYPE; } /** * Returns the current value(s) associated with this control. These values will be transmitted to the server * if the control is 'successful'. **/ public String[] getValues() { if (_values == null) _values = new String[] { _value }; return _values; } protected void addValues( ParameterProcessor processor, String characterSet ) throws IOException { processor.addParameter( _name, _value, characterSet ); } private String _name; private String _value; private String[] _values; }
33.646753
151
0.613041
87000ee14309d7c6a3b4cd88d5da0b3a397b0be9
886
package htsjdk.tribble.util.ftp; import htsjdk.HtsjdkTest; import htsjdk.samtools.util.ftp.FTPUtils; import org.testng.annotations.Test; import java.net.URL; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * @author Jim Robinson * @since 10/4/11 */ public class FTPUtilsTest extends HtsjdkTest { @Test public void testResourceAvailable() throws Exception { URL goodUrl = new URL("ftp://ftp.broadinstitute.org/pub/igv/TEST/test.txt"); assertTrue(FTPUtils.resourceAvailable(goodUrl)); URL nonExistentURL = new URL("ftp://ftp.broadinstitute.org/pub/igv/TEST/doesntExist"); assertFalse(FTPUtils.resourceAvailable(nonExistentURL)); URL nonExistentServer = new URL("ftp://noSuchServer/pub/igv/TEST/doesntExist"); assertFalse(FTPUtils.resourceAvailable(nonExistentServer)); } }
26.848485
94
0.735892
6ae436850da24ca35dc146f199aa7bcc7db9c9af
6,550
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal; import android.os.Parcel; import com.google.android.gms.common.internal.safeparcel.zzb; import com.google.android.gms.common.internal.safeparcel.zzc; // Referenced classes of package com.google.android.gms.internal: // zzayx, zzayz public class zzayy implements android.os.Parcelable.Creator { public zzayy() { // 0 0:aload_0 // 1 1:invokespecial #11 <Method void Object()> // 2 4:return } static void zza(zzayx zzayx1, Parcel parcel, int i) { int j = zzc.zzaZ(parcel); // 0 0:aload_1 // 1 1:invokestatic #20 <Method int zzc.zzaZ(Parcel)> // 2 4:istore_3 zzc.zzc(parcel, 2, zzayx1.zzbBy); // 3 5:aload_1 // 4 6:iconst_2 // 5 7:aload_0 // 6 8:getfield #26 <Field int zzayx.zzbBy> // 7 11:invokestatic #30 <Method void zzc.zzc(Parcel, int, int)> zzc.zza(parcel, 3, ((android.os.Parcelable []) (zzayx1.zzbBz)), i, false); // 8 14:aload_1 // 9 15:iconst_3 // 10 16:aload_0 // 11 17:getfield #34 <Field zzayz[] zzayx.zzbBz> // 12 20:iload_2 // 13 21:iconst_0 // 14 22:invokestatic #37 <Method void zzc.zza(Parcel, int, android.os.Parcelable[], int, boolean)> zzc.zza(parcel, 4, zzayx1.zzbBA, false); // 15 25:aload_1 // 16 26:iconst_4 // 17 27:aload_0 // 18 28:getfield #41 <Field String[] zzayx.zzbBA> // 19 31:iconst_0 // 20 32:invokestatic #44 <Method void zzc.zza(Parcel, int, String[], boolean)> zzc.zzJ(parcel, j); // 21 35:aload_1 // 22 36:iload_3 // 23 37:invokestatic #48 <Method void zzc.zzJ(Parcel, int)> // 24 40:return } public Object createFromParcel(Parcel parcel) { return ((Object) (zzja(parcel))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokevirtual #54 <Method zzayx zzja(Parcel)> // 3 5:areturn } public Object[] newArray(int i) { return ((Object []) (zzmX(i))); // 0 0:aload_0 // 1 1:iload_1 // 2 2:invokevirtual #60 <Method zzayx[] zzmX(int)> // 3 5:areturn } public zzayx zzja(Parcel parcel) { int j = zzb.zzaY(parcel); // 0 0:aload_1 // 1 1:invokestatic #65 <Method int zzb.zzaY(Parcel)> // 2 4:istore_3 int i = 0; // 3 5:iconst_0 // 4 6:istore_2 zzayz azzayz[] = null; // 5 7:aconst_null // 6 8:astore 6 String as[] = null; // 7 10:aconst_null // 8 11:astore 5 do if(parcel.dataPosition() < j) //* 9 13:aload_1 //* 10 14:invokevirtual #71 <Method int Parcel.dataPosition()> //* 11 17:iload_3 //* 12 18:icmpge 110 { int k = zzb.zzaX(parcel); // 13 21:aload_1 // 14 22:invokestatic #74 <Method int zzb.zzaX(Parcel)> // 15 25:istore 4 switch(zzb.zzdc(k)) //* 16 27:iload 4 //* 17 29:invokestatic #78 <Method int zzb.zzdc(int)> { //* 18 32:tableswitch 2 4: default 60 // 2 63 // 3 73 // 4 90 //* 19 60:goto 101 case 2: // '\002' i = zzb.zzg(parcel, k); // 20 63:aload_1 // 21 64:iload 4 // 22 66:invokestatic #82 <Method int zzb.zzg(Parcel, int)> // 23 69:istore_2 break; //* 24 70:goto 107 case 3: // '\003' azzayz = (zzayz[])zzb.zzb(parcel, k, zzayz.CREATOR); // 25 73:aload_1 // 26 74:iload 4 // 27 76:getstatic #88 <Field android.os.Parcelable$Creator zzayz.CREATOR> // 28 79:invokestatic #92 <Method Object[] zzb.zzb(Parcel, int, android.os.Parcelable$Creator)> // 29 82:checkcast #93 <Class zzayz[]> // 30 85:astore 6 break; //* 31 87:goto 107 case 4: // '\004' as = zzb.zzC(parcel, k); // 32 90:aload_1 // 33 91:iload 4 // 34 93:invokestatic #97 <Method String[] zzb.zzC(Parcel, int)> // 35 96:astore 5 break; //* 36 98:goto 107 default: zzb.zzb(parcel, k); // 37 101:aload_1 // 38 102:iload 4 // 39 104:invokestatic #99 <Method void zzb.zzb(Parcel, int)> break; } } else //* 40 107:goto 13 if(parcel.dataPosition() != j) //* 41 110:aload_1 //* 42 111:invokevirtual #71 <Method int Parcel.dataPosition()> //* 43 114:iload_3 //* 44 115:icmpeq 148 throw new com.google.android.gms.common.internal.safeparcel.zzb.zza((new StringBuilder(37)).append("Overread allowed size end=").append(j).toString(), parcel); // 45 118:new #101 <Class com.google.android.gms.common.internal.safeparcel.zzb$zza> // 46 121:dup // 47 122:new #103 <Class StringBuilder> // 48 125:dup // 49 126:bipush 37 // 50 128:invokespecial #106 <Method void StringBuilder(int)> // 51 131:ldc1 #108 <String "Overread allowed size end="> // 52 133:invokevirtual #112 <Method StringBuilder StringBuilder.append(String)> // 53 136:iload_3 // 54 137:invokevirtual #115 <Method StringBuilder StringBuilder.append(int)> // 55 140:invokevirtual #119 <Method String StringBuilder.toString()> // 56 143:aload_1 // 57 144:invokespecial #122 <Method void com.google.android.gms.common.internal.safeparcel.zzb$zza(String, Parcel)> // 58 147:athrow else return new zzayx(i, azzayz, as); // 59 148:new #22 <Class zzayx> // 60 151:dup // 61 152:iload_2 // 62 153:aload 6 // 63 155:aload 5 // 64 157:invokespecial #125 <Method void zzayx(int, zzayz[], String[])> // 65 160:areturn while(true); } public zzayx[] zzmX(int i) { return new zzayx[i]; // 0 0:iload_1 // 1 1:anewarray zzayx[] // 2 4:areturn } }
34.473684
163
0.524885
e79fee94e7fafe26f2cf9c1382ccbe88da6ad61c
2,367
package deformablemesh; import deformablemesh.gui.ControlFrame; import deformablemesh.gui.PropertySaver; import deformablemesh.gui.RingController; import deformablemesh.meshview.MeshFrame3D; import ij.IJ; import ij.ImagePlus; import ij.plugin.filter.PlugInFilter; import ij.process.ImageProcessor; import javax.swing.JOptionPane; import java.io.IOException; import java.util.stream.IntStream; /** * An entry point for starting the application. * * Created by msmith on 12/1/15. */ public class Deforming3DMesh_Plugin implements PlugInFilter { public static final String version = "0.8.0"; public static SegmentationModel createDeformingMeshApplication(){ MeshFrame3D mf3d = new MeshFrame3D(); SegmentationModel model = new SegmentationModel(); SegmentationController control = new SegmentationController(model); try { PropertySaver.loadProperties(control); } catch (IOException e) { System.err.println("cannot load properties: " + e.getMessage()); } ControlFrame controller = new ControlFrame(control); controller.showFrame(); mf3d.showFrame(false); mf3d.addLights(); controller.addMeshFrame3D(mf3d); control.setMeshFrame3D(mf3d); PropertySaver.positionFrames(controller, mf3d); return model; } @Override public int setup(String s, ImagePlus imagePlus) { SegmentationModel model = createDeformingMeshApplication(); if(imagePlus != null) { int channel = 0; if(imagePlus.getNChannels()>1){ Object[] values = IntStream.range(1, imagePlus.getNChannels()+1).boxed().toArray(); Object channelChoice = JOptionPane.showInputDialog( IJ.getInstance(), "Select Channel:", "Choose Channel", JOptionPane.QUESTION_MESSAGE, null, values, values[0] ); if(channelChoice == null) channelChoice = 1; channel = (Integer)channelChoice - 1; } model.setOriginalPlus(imagePlus, channel); } return DOES_ALL; } @Override public void run(ImageProcessor imageProcessor) { } }
29.5875
99
0.620617
4dc6a8e6ac135ae8e764a109805f63908e974d00
4,676
package com.bitcola.exchange.security.admin.biz; import com.bitcola.exchange.security.admin.entity.ColaUserReward; import com.bitcola.exchange.security.admin.entity.ColaVirtualAsset; import com.bitcola.exchange.security.admin.feign.IDataServiceFeign; import com.bitcola.exchange.security.admin.mapper.ColaFinancialMapper; import com.bitcola.exchange.security.admin.mapper.ColaUserRewardMapper; import com.bitcola.exchange.security.admin.mapper.ColaVirtualAssetMapper; import com.bitcola.exchange.security.auth.common.util.EncoderUtil; import com.bitcola.exchange.security.common.constant.FinancialConstant; import com.bitcola.exchange.security.common.constant.SystemBalanceConstant; import com.bitcola.exchange.security.common.constant.UserConstant; import com.bitcola.exchange.security.common.msg.TableResultResponse; import com.bitcola.exchange.security.common.util.AdminQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.UUID; /** * @author zkq * @create 2018-11-28 16:55 **/ @Service public class ColaFinancialBiz { @Autowired IDataServiceFeign dataServiceFeign; @Autowired ColaUserRewardMapper userRewardMapper; @Autowired ColaFinancialMapper financialMapper; @Autowired ColaVirtualAssetMapper virtualAssetMapper; @Transactional(isolation = Isolation.READ_COMMITTED) public boolean reward(String coinCode, BigDecimal number, String userId,String description) { // 系统扣钱,用户加钱,记录日志 boolean b = dataServiceFeign.transformBalance(UserConstant.SYS_ACCOUNT_ID, userId, coinCode, false, false, number, SystemBalanceConstant.REWARD_SYSTEM, description); if (!b) return false; ColaUserReward userReward = new ColaUserReward(); userReward.setId(UUID.randomUUID().toString()); userReward.setAccount(number); userReward.setCoinCode(coinCode); userReward.setTime(System.currentTimeMillis()); userReward.setUserId(userId); userReward.setStatus("Completed"); userReward.setActionType(FinancialConstant.SYSTEM_REWARD); userReward.setDescription(description); userRewardMapper.insertSelective(userReward); return true; } public TableResultResponse page(AdminQuery query) { Long total = financialMapper.total(query); List<Map<String,Object>> list = financialMapper.page(query); return new TableResultResponse(total,list); } public boolean freeze(String coinCode, BigDecimal amount, String userId, String description) { boolean b = dataServiceFeign.transformBalance(userId, userId, coinCode, false, true, amount, SystemBalanceConstant.FROZEN_SYSTEM, description); return b; } public boolean unFrozen(String coinCode, BigDecimal amount, String userId, String description) { boolean b = dataServiceFeign.transformBalance(userId, userId, coinCode, true, false, amount, SystemBalanceConstant.UNFROZEN_SYSTEM, description); return b; } public boolean reduce(String coinCode, BigDecimal amount, String userId, String description) { boolean b = dataServiceFeign.transformBalance(userId, UserConstant.SYS_ACCOUNT_ID, coinCode, false, false, amount, SystemBalanceConstant.REDUCE_SYSTEM, description); return b; } public void addVirtualAsset(String coinCode, String number, String description) { ColaVirtualAsset asset = new ColaVirtualAsset(); BigDecimal amount = new BigDecimal(number); asset.setId(UUID.randomUUID().toString()); asset.setTimestamp(System.currentTimeMillis()); asset.setToUser("8"); asset.setCoinCode(coinCode); asset.setNumber(amount); asset.setDescription(description); virtualAssetMapper.insertSelective(asset); virtualAssetMapper.addVirtualAsset(amount,coinCode,EncoderUtil.BALANCE_KEY); } // id, 昵称,用户名,手机,邮箱,资产 public TableResultResponse coinRange(AdminQuery query) { Long total = financialMapper.countUser(query); List<Map<String,Object>> list = financialMapper.coinRange(query); return new TableResultResponse(total,list); } public TableResultResponse financialPage(AdminQuery query) { List<Map<String,Object>> list = financialMapper.financialPage(query); Long total = financialMapper.financialCount(query); return new TableResultResponse(total,list); } }
42.509091
173
0.755774
8d9fb6d63fe3d0a43d7c21ac91227c13f6307fdf
1,543
package boltzmann.training.learningfactor; import java.io.Serializable; public class AdaptiveLearningFactor implements Serializable { private static final long serialVersionUID = 1L; protected double learningFactor; protected double rhoD; protected double rhoI; protected int maxLearningFactorCounter; public AdaptiveLearningFactor() { this.learningFactor = 0.01; this.rhoD = 0.8; this.rhoI = 1.5; this.maxLearningFactorCounter = 0; } public AdaptiveLearningFactor(double learningFactor, double rhoD, double rhoI) { this.learningFactor = learningFactor; this.rhoD = rhoD; this.rhoI = rhoI; this.maxLearningFactorCounter = 0; } public void updateLearningFactor(double previousError, double currentError) { if (previousError != 0.0) { if (currentError > previousError) { decreaseLearningFactor(); } else if (previousError - currentError < 0.01) { increaseLearningFactor(); } if (learningFactor == 1.0) { maxLearningFactorCounter++; } else { maxLearningFactorCounter = 0; } if (maxLearningFactorCounter == 2000) { maxLearningFactorCounter = 0; learningFactor = 0.2; } } } public double getLearningFactor() { return learningFactor; } private void decreaseLearningFactor() { learningFactor *= rhoD; if (learningFactor >= 1.0) { learningFactor = 1.0; } } private void increaseLearningFactor() { learningFactor *= rhoI; if (learningFactor >= 1.0) { learningFactor = 1.0; } } }
24.887097
82
0.687622
07b66b268df3ea0cb17ad0cb63e55c882bb9c161
28,944
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.campocolombia.vista; import com.campocolombia.controlador.ControladorGestionEmpleados; import java.awt.event.ActionListener; /** * * @author Jonattan */ public class GestionEmpleados extends javax.swing.JFrame { public ControladorGestionEmpleados controlador = null; public GestionEmpleados() { initComponents(); setLocationRelativeTo(null); setVisible(false); } /** * 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() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); jPanel10 = new javax.swing.JPanel(); jLabel18 = new javax.swing.JLabel(); textNombreEmpleado = new javax.swing.JTextField(); jSeparator12 = new javax.swing.JSeparator(); jLabel19 = new javax.swing.JLabel(); textApellidoEmpleado = new javax.swing.JTextField(); jSeparator13 = new javax.swing.JSeparator(); jLabel20 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); btmIngresarEmpleado = new javax.swing.JButton(); fechaNacimientoEmpleado = new com.toedter.calendar.JDateChooser(); textDireccionEmpleado = new javax.swing.JTextField(); jSeparator14 = new javax.swing.JSeparator(); textEdadEmpleado = new javax.swing.JTextField(); jSeparator15 = new javax.swing.JSeparator(); textSueldoEmpleado = new javax.swing.JTextField(); jSeparator17 = new javax.swing.JSeparator(); textUsuarioEmpleado = new javax.swing.JTextField(); jSeparator18 = new javax.swing.JSeparator(); textPassWordEmpleado = new javax.swing.JTextField(); jSeparator19 = new javax.swing.JSeparator(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); selectTipoContrato = new javax.swing.JComboBox<>(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); selectRol = new javax.swing.JComboBox<>(); jSeparator16 = new javax.swing.JSeparator(); jLabel21 = new javax.swing.JLabel(); jSeparator20 = new javax.swing.JSeparator(); textIDEmpleadoIngreso = new javax.swing.JTextField(); jSeparator21 = new javax.swing.JSeparator(); jPanel3 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); tblConsulta = new javax.swing.JTable(); jPanel9 = new javax.swing.JPanel(); selectBorradoEmpleado = new javax.swing.JComboBox<>(); textIDEmpleadoModificar = new javax.swing.JTextField(); jSeparator11 = new javax.swing.JSeparator(); jLabel17 = new javax.swing.JLabel(); btmModificarEmpleado = new javax.swing.JButton(); btmConsultaEmpleado = new javax.swing.JButton(); btmBorradoEmpleado = new javax.swing.JButton(); selectConsultaEmpleado = new javax.swing.JComboBox<>(); btnAtras = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/User.png"))); // NOI18N jLabel2.setFont(new java.awt.Font("Segoe UI Light", 1, 48)); // NOI18N jLabel2.setText("Gestión del Empleados"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(130, 130, 130) .addComponent(jLabel2)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 856, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(109, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 9, Short.MAX_VALUE)) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1150, 150)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel10.setBackground(new java.awt.Color(255, 255, 255)); jPanel10.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel18.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel18.setText("Nombre"); jPanel10.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, -1, -1)); textNombreEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textNombreEmpleado.setBorder(null); textNombreEmpleado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textNombreEmpleadoActionPerformed(evt); } }); jPanel10.add(textNombreEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 30, 228, 30)); jPanel10.add(jSeparator12, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 30, 228, 10)); jLabel19.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel19.setText("Apellido"); jPanel10.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, -1, -1)); textApellidoEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textApellidoEmpleado.setBorder(null); jPanel10.add(textApellidoEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 80, 228, 30)); jPanel10.add(jSeparator13, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 110, 228, 12)); jLabel20.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel20.setText("Fecha de Nacimiento"); jPanel10.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, -1, -1)); jLabel23.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel23.setText("Tipo Empleado"); jPanel10.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 460, -1, -1)); btmIngresarEmpleado.setBackground(new java.awt.Color(255, 255, 255)); btmIngresarEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N btmIngresarEmpleado.setText("Ingresar"); jPanel10.add(btmIngresarEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 540, -1, -1)); fechaNacimientoEmpleado.setBackground(new java.awt.Color(255, 255, 255)); fechaNacimientoEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jPanel10.add(fechaNacimientoEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 180, 230, 30)); textDireccionEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textDireccionEmpleado.setBorder(null); jPanel10.add(textDireccionEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 120, 228, 30)); jPanel10.add(jSeparator14, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 150, 228, 12)); textEdadEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textEdadEmpleado.setBorder(null); jPanel10.add(textEdadEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 240, 228, 30)); jPanel10.add(jSeparator15, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 270, 228, 12)); textSueldoEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textSueldoEmpleado.setBorder(null); jPanel10.add(textSueldoEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 330, 228, 30)); jPanel10.add(jSeparator17, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 360, 228, 12)); textUsuarioEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textUsuarioEmpleado.setBorder(null); jPanel10.add(textUsuarioEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 370, 228, 30)); jPanel10.add(jSeparator18, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 400, 228, 12)); textPassWordEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textPassWordEmpleado.setBorder(null); jPanel10.add(textPassWordEmpleado, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 410, 228, 30)); jPanel10.add(jSeparator19, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 440, 228, 12)); jLabel24.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel24.setText("Dirección"); jPanel10.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 130, -1, -1)); jLabel25.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel25.setText("Edad"); jPanel10.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 240, -1, -1)); jLabel26.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel26.setText("Tipo de Contrato"); jPanel10.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 290, -1, -1)); jLabel27.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel27.setText("Sueldo"); jPanel10.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 330, -1, -1)); selectTipoContrato.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N selectTipoContrato.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Fijo", "Indefinido", "Servicio", "Hora" })); jPanel10.add(selectTipoContrato, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 290, 230, 30)); jLabel28.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel28.setText("Usuario Asignado"); jPanel10.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 370, -1, -1)); jLabel29.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel29.setText("Contraseña"); jPanel10.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 410, -1, -1)); selectRol.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N selectRol.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Apicultor", "Gerente", "Investigador" })); jPanel10.add(selectRol, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 460, 230, 30)); jPanel10.add(jSeparator16, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jLabel21.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel21.setText("ID"); jPanel10.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 0, -1, -1)); jPanel10.add(jSeparator20, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 60, 228, 10)); textIDEmpleadoIngreso.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N textIDEmpleadoIngreso.setBorder(null); textIDEmpleadoIngreso.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textIDEmpleadoIngresoActionPerformed(evt); } }); jPanel10.add(textIDEmpleadoIngreso, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, -10, 228, 30)); jPanel10.add(jSeparator21, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 20, 228, 20)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(66, Short.MAX_VALUE) .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, 588, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 560, 650)); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); tblConsulta.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane3.setViewportView(tblConsulta); jPanel9.setBackground(new java.awt.Color(255, 255, 255)); selectBorradoEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N selectBorradoEmpleado.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Por ID" })); textIDEmpleadoModificar.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N textIDEmpleadoModificar.setBorder(null); jLabel17.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel17.setText("ID"); btmModificarEmpleado.setBackground(new java.awt.Color(255, 255, 255)); btmModificarEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N btmModificarEmpleado.setText("Modificar"); btmModificarEmpleado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmModificarEmpleadoActionPerformed(evt); } }); btmConsultaEmpleado.setBackground(new java.awt.Color(255, 255, 255)); btmConsultaEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N btmConsultaEmpleado.setText("Consulta"); btmBorradoEmpleado.setBackground(new java.awt.Color(255, 255, 255)); btmBorradoEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N btmBorradoEmpleado.setText("Borrado"); selectConsultaEmpleado.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N selectConsultaEmpleado.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Por ID", "General" })); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup() .addContainerGap(71, Short.MAX_VALUE) .addComponent(jLabel17) .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textIDEmpleadoModificar, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE) .addComponent(jSeparator11)) .addComponent(selectBorradoEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(selectConsultaEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(54, 54, 54) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btmModificarEmpleado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btmConsultaEmpleado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btmBorradoEmpleado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(20, 20, 20)) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(textIDEmpleadoModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator11, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(btmModificarEmpleado))) .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btmConsultaEmpleado) .addComponent(selectConsultaEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selectBorradoEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btmBorradoEmpleado)) .addGap(126, 126, 126)) ); btnAtras.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N btnAtras.setText("Atras"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(54, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39)) ); getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 150, 590, 650)); pack(); }// </editor-fold>//GEN-END:initComponents private void textNombreEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNombreEmpleadoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textNombreEmpleadoActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox1ActionPerformed private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox2ActionPerformed private void btmModificarEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btmModificarEmpleadoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btmModificarEmpleadoActionPerformed private void textIDEmpleadoIngresoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textIDEmpleadoIngresoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textIDEmpleadoIngresoActionPerformed /** * @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(GestionEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GestionEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GestionEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GestionEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GestionEmpleados().setVisible(true); } }); } public void setControlador(ControladorGestionEmpleados controlador) { //Bototones Abeja this.controlador = controlador; this.btmIngresarEmpleado.addActionListener((ActionListener) controlador); this.btmConsultaEmpleado.addActionListener((ActionListener) controlador); this.btmModificarEmpleado.addActionListener((ActionListener) controlador); this.btmBorradoEmpleado.addActionListener((ActionListener) controlador); this.btnAtras.addActionListener((ActionListener) controlador); } // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JButton btmBorradoEmpleado; public javax.swing.JButton btmConsultaEmpleado; public javax.swing.JButton btmIngresarEmpleado; public javax.swing.JButton btmModificarEmpleado; public javax.swing.JButton btnAtras; public com.toedter.calendar.JDateChooser fechaNacimientoEmpleado; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel9; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator11; private javax.swing.JSeparator jSeparator12; private javax.swing.JSeparator jSeparator13; private javax.swing.JSeparator jSeparator14; private javax.swing.JSeparator jSeparator15; private javax.swing.JSeparator jSeparator16; private javax.swing.JSeparator jSeparator17; private javax.swing.JSeparator jSeparator18; private javax.swing.JSeparator jSeparator19; private javax.swing.JSeparator jSeparator20; private javax.swing.JSeparator jSeparator21; public javax.swing.JComboBox<String> selectBorradoEmpleado; public javax.swing.JComboBox<String> selectConsultaEmpleado; public javax.swing.JComboBox<String> selectRol; public javax.swing.JComboBox<String> selectTipoContrato; public javax.swing.JTable tblConsulta; public javax.swing.JTextField textApellidoEmpleado; public javax.swing.JTextField textDireccionEmpleado; public javax.swing.JTextField textEdadEmpleado; public javax.swing.JTextField textIDEmpleadoIngreso; public javax.swing.JTextField textIDEmpleadoModificar; public javax.swing.JTextField textNombreEmpleado; public javax.swing.JTextField textPassWordEmpleado; public javax.swing.JTextField textSueldoEmpleado; public javax.swing.JTextField textUsuarioEmpleado; // End of variables declaration//GEN-END:variables }
56.421053
176
0.688156
c1dfc0fe86262115db295805dc5bea32b7b3e8e6
1,601
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity.rntbd; import io.netty.util.HashedWheelTimer; import io.netty.util.Timeout; import io.netty.util.Timer; import io.netty.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public final class RntbdRequestTimer implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestTimer.class); private static final ThreadFactory threadFactory = new RntbdThreadFactory( "request-timer", true, Thread.NORM_PRIORITY); private final long requestTimeoutInNanos; private final Timer timer; public RntbdRequestTimer(final long requestTimeoutInNanos, final long requestTimerResolutionInNanos) { // The HashWheelTimer code shows that cancellation of a timeout takes two timer resolution units to complete this.timer = new HashedWheelTimer(threadFactory, requestTimerResolutionInNanos, TimeUnit.NANOSECONDS); this.requestTimeoutInNanos = requestTimeoutInNanos; } @Override public void close() { final Set<Timeout> cancelledTimeouts = this.timer.stop(); logger.debug("request expiration tasks cancelled: {}", cancelledTimeouts.size()); } public Timeout newTimeout(final TimerTask task) { return this.timer.newTimeout(task, this.requestTimeoutInNanos, TimeUnit.NANOSECONDS); } }
35.577778
116
0.761399
f55152ab81c809425ddda6d81193abf9ac6051b1
11,029
/** * Copyright (C) 2002 Mike Hummel (mh@mhus.de) * * 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 de.mhus.lib.core; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Function; import de.mhus.lib.basics.IsNull; import de.mhus.lib.core.util.MObject; import de.mhus.lib.errors.MException; import de.mhus.lib.errors.MRuntimeException; import de.mhus.lib.errors.NotFoundException; public abstract class AbstractProperties extends MObject implements IProperties { private static final long serialVersionUID = 1L; /** * Overwrite this function to provide values in string format. * * @param key * @return null if the property not exists or the property value. */ @Override public abstract Object getProperty(String key); // @Deprecated // public boolean getProperty(String name, boolean def) { // return getBoolean(name, def); // } // // @Deprecated // public String getProperty(String name, String def) { // Object out = getProperty(name); // if (out == null) return def; // return String.valueOf(out); // } @Override public String getString(String key, String def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } if (out == null) return def; return String.valueOf(out); } @Override public String getString(String key) throws NotFoundException { Object out = getProperty(key); if (out == null) throw new NotFoundException("value not found", key); return String.valueOf(out); } @Override public boolean getBoolean(String key, boolean def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } return MCast.toboolean(out, def); } @Override public boolean getBoolean(String key) throws NotFoundException { Object out = getProperty(key); if (out == null) throw new NotFoundException("value not found", key); return MCast.toboolean(out, false); } @Override public int getInt(String key, int def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } return MCast.toint(out, def); } @Override public long getLong(String key, long def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } return MCast.tolong(out, def); } @Override public float getFloat(String key, float def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } return MCast.tofloat(out, def); } @Override public double getDouble(String key, double def) { Object out; try { out = getProperty(key); } catch (Throwable e) { return def; } return MCast.todouble(out, def); } @Override public Calendar getCalendar(String key) throws MException { Object out = getProperty(key); return MCast.toCalendar(out); } @Override public Date getDate(String key) { try { Object out = getProperty(key); return MCast.toDate(out, null); } catch (Throwable t) { } return null; } @Override public void setString(String key, String value) { setProperty(key, value); } @Override public void setInt(String key, int value) { setProperty(key, value); } @Override public void setLong(String key, long value) { setProperty(key, value); } @Override public void setDouble(String key, double value) { setProperty(key, value); } @Override public void setFloat(String key, float value) { setProperty(key, value); } @Override public void setBoolean(String key, boolean value) { setProperty(key, value); } @Override public void setCalendar(String key, Calendar value) { setProperty(key, value); } @Override public void setDate(String key, Date value) { setProperty(key, value); } @Override public void setNumber(String key, Number value) { if (value == null) { removeProperty(key); return; } if (value instanceof Integer) setInt(key, (Integer) value); else if (value instanceof Long) { setLong(key, (Long) value); } else if (value instanceof Float) { setFloat(key, (Float) value); } else if (value instanceof Double) { setDouble(key, (Double) value); } else throw new MRuntimeException("Unknown number class", key, value.getClass()); } @Override public Number getNumber(String key, Number def) { Object out = getProperty(key); if (out == null) return def; if (out instanceof Number) return (Number) out; try { return MCast.todouble(out, 0); } catch (NumberFormatException e) { return def; } } /** * Return true if the property exists. * * @param key * @return if exists */ @Override public abstract boolean isProperty(String key); /** * Remove the property field in the list of properties. * * @param key */ @Override public abstract void removeProperty(String key); /** * Overwrite this function to allow changes in properties. * * @param key * @param value */ @Override public abstract void setProperty(String key, Object value); /** * Overwrite this function and return true if the property set can be edited. * * @return if is editable */ @Override public abstract boolean isEditable(); /** @return the keys */ @Override public abstract Set<String> keys(); @Override public Iterator<Map.Entry<String, Object>> iterator() { return new IPIterator(); } public Map<String, Object> toMap() { Map<String, Object> out = new HashMap<>(); for (Map.Entry<String, Object> entry : this) { out.put(entry.getKey(), entry.getValue()); } return out; } private class IPIterator implements Iterator<Map.Entry<String, Object>> { private Iterator<String> keys; private String currentkey; IPIterator() { keys = keys().iterator(); } @Override public boolean hasNext() { return keys.hasNext(); } @Override public Entry<String, Object> next() { currentkey = keys.next(); return new IPEntry(currentkey); } @Override public void remove() { try { removeProperty(currentkey); } catch (Throwable e) { log().t(e); } } } private class IPEntry implements Map.Entry<String, Object> { private String key; public IPEntry(String next) { key = next; } @Override public String getKey() { return key; } @Override public Object getValue() { try { return getProperty(key); } catch (Throwable e) { throw new MRuntimeException(e); } } @Override public Object setValue(Object value) { Object old = null; try { old = getProperty(key); } catch (Throwable e1) { log().t(key, e1); } try { setProperty(key, value); } catch (Throwable e) { log().t(key, e); } return old; } } @Override public abstract int size(); @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(Object key) { if (key == null) return false; return isProperty(String.valueOf(key)); } @Override public Object get(Object key) { if (key == null) return null; return getProperty(String.valueOf(key)); } @Override public Object put(String key, Object value) { Object current = get(key); setProperty(key, value); return current; } @Override public Object remove(Object key) { if (key == null) return null; Object current = get(key); removeProperty(String.valueOf(key)); return current; } @Override public void putAll(Map<? extends String, ? extends Object> m) { for (Map.Entry<? extends String, ? extends Object> e : m.entrySet()) if (e.getValue() instanceof IsNull) remove(e.getKey()); else put(e.getKey(), e.getValue()); } public void putMap(Map<?, ?> m) { for (Map.Entry<?, ?> e : m.entrySet()) if (e.getValue() instanceof IsNull) remove(e.getKey()); else put(String.valueOf(e.getKey()), e.getValue()); } public void putReadProperties(IReadProperties m) { for (Map.Entry<? extends String, ? extends Object> e : m.entrySet()) if (e.getValue() instanceof IsNull) remove(e.getKey()); else put(e.getKey(), e.getValue()); } // @Override // public void clear() { // // for (String name : keys()) // removeProperty(name); // } @Override public Set<String> keySet() { return keys(); } @Override public String getFormatted(String key, String def, Object... values) { String format = getString(key, def); if (format == null) return def; // probably null return String.format(format, values); } @Override public String getStringOrCreate(String name, Function<String, String> def) { Object out; try { out = getProperty(name); } catch (Throwable e) { return def.apply(name); } if (out == null) return def.apply(name); return String.valueOf(out); } }
25.82904
90
0.567232
10b7e565965dc7ec2fd80fbee3a78b57a49c74b9
1,020
package io.github.polysantiago.spring.rest; import lombok.AccessLevel; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import java.net.URI; import java.util.*; @AllArgsConstructor(access = AccessLevel.PACKAGE) class RestClientContext { private List<RestClientSpecification> specifications = new ArrayList<>(); private Map<String, Object> services = new HashMap<>(); RestClientSpecification findByRestClientName(String name) { return specifications .stream() .filter(specification -> StringUtils.equals(specification.getName(), name)) .findAny() .orElseThrow(() -> new IllegalStateException("Unable to find a @RestClient with name: " + name)); } URI findServiceUriByName(String name) { return Optional.ofNullable(services.get(name)) .map(Object::toString) .map(URI::create) .orElseThrow(() -> new IllegalStateException("Invalid URL for service " + name)); } }
32.903226
109
0.684314
d45cb46b9ec5d6d585dd2e8454bebb5494d17bad
137
package com.alibaba.alink.common.linalg.tensor; public enum DataType { FLOAT, DOUBLE, INT, LONG, BOOLEAN, BYTE, UBYTE, STRING }
10.538462
47
0.715328
6b3ed72869ec8f32f4390b87495c902db98a2290
115
package com.surmount.core.task; /** * @author Qiannan Lu * @date 06/03/2018. */ public class TaskExecution { }
12.777778
31
0.669565
48e417f87453e33539c21327e6d99a6a3d302065
21,235
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package de.unioninvestment.eai.portal.support.scripting; import com.vaadin.ui.Button; import de.unioninvestment.eai.portal.portlet.crud.config.*; import de.unioninvestment.eai.portal.portlet.crud.domain.exception.BusinessException; import de.unioninvestment.eai.portal.portlet.crud.domain.model.ModelSupport; import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptPortlet; import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptRow; import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptTab; import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptTabs; import de.unioninvestment.eai.portal.support.vaadin.groovy.VaadinBuilder; import groovy.lang.Closure; import groovy.lang.Script; import org.junit.Before; import org.junit.Test; import org.mockito.internal.matchers.InstanceOf; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.xml.sax.SAXException; import javax.xml.bind.JAXBException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.contains; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.startsWith; import static org.mockito.Mockito.*; @ContextConfiguration({ "/eai-portal-web-test-applicationcontext.xml" }) public class ConfigurationScriptsCompilerTest extends ModelSupport { private ScriptCompiler scriptCompilerMock = mock(ScriptCompiler.class); private ConfigurationScriptsCompiler compiler; @Before public void setUp() { compiler = new ConfigurationScriptsCompiler(scriptCompilerMock); } @Test public void shouldCompileExistingScript() throws JAXBException, SAXException, ScriptingException { PortletConfig portletConfig = createConfiguration("validScriptConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock) .compileScript( "log.info \"Hello World\"\nlog.debug 'MainPortletScript.groovy execution finished...'", "MainPortletScript.groovy"); } @Test public void shouldCompileScriptsWithSrcAttribute() throws JAXBException, SAXException, ScriptingException { PortletConfig portletConfig = createConfiguration("validMultiScriptConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock).compileScript( contains("log.info \"Hello Shared\""), eq("shared.groovy")); verify(scriptCompilerMock).compileScript( contains("log.info \"Hello Main\""), eq("MainPortletScript.groovy")); } @Test public void shouldCompileEmptyScriptIfNothingConfigured() throws JAXBException, SAXException, ScriptingException { PortletConfig portletConfig = createConfiguration("validConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock).compileScript(""); } @Test public void shouldCompileClosureScripts() throws JAXBException, SAXException, ScriptingException { PortletConfig portletConfig = createConfiguration("validTableActionConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock) .compileScript( "def aufruf() { println \"aufruf erfolgreich\" }\nlog.debug 'MainPortletScript.groovy execution finished...'", "MainPortletScript.groovy"); verify(scriptCompilerMock).compileScript("{ it -> aufruf() }"); // assertThat(config.getScript().getValue().getClazz(), notNullValue()); } @Test public void shouldCompileAllClosureScripts() throws JAXBException, SAXException, ScriptingException, InstantiationException, IllegalAccessException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validAllClosuresConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); assertThat(portletConfig.getOnRefresh().getClazz(), notNullValue()); assertThat(portletConfig.getOnLoad().getClazz(), notNullValue()); assertThat(portletConfig.getOnReload().getClazz(), notNullValue()); assertThat(getTabs(portletConfig).getOnChange().getClazz(), notNullValue()); assertThat(getTab(portletConfig).getOnShow().getClazz(), notNullValue()); assertThat(getTab(portletConfig).getOnHide().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getOnModeChange().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getOnSelectionChange().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getOnRowChange().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getRowEditable().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getRowDeletable().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getRowValidator().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getColumns().getColumn().get(2) .getDefault().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getColumns().getColumn().get(1) .getValidator().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getColumns().getColumn().get(9) .getGenerator().getClazz(), notNullValue()); assertThat(getTable(portletConfig).getColumns().getColumn().get(9) .getGeneratedValue().getClazz(), notNullValue()); assertThat(getTableAction(portletConfig).getOnExecution().getClazz(), notNullValue()); assertThat(getTableActions(portletConfig).get(1).getExport() .getFilename().getClazz(), notNullValue()); assertThat(getTableActions(portletConfig).get(2).getDownload() .getGenerator().getClazz(), notNullValue()); assertThat(getFormAction(portletConfig).getOnExecution().getClazz(), notNullValue()); assertThat(getFormField(portletConfig).getOnValueChange().getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getOnCreate().getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getOnDelete().getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getOnInsert().getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getOnUpdate().getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getInsert().getStatement() .getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getUpdate().getStatement() .getClazz(), notNullValue()); assertThat(getDatabaseQuery(portletConfig).getDelete().getStatement() .getClazz(), notNullValue()); assertThat(getComponentInCompoundSearch(portletConfig).getGenerator() .getClazz(), notNullValue()); // TODO add missing closures assertScriptExecution(portletConfig); } private ScriptComponentConfig getComponentInCompoundSearch( PortletConfig portletConfig) { CompoundSearchConfig search = (CompoundSearchConfig) portletConfig .getPage().getElements().get(0); return (ScriptComponentConfig) search.getDetails().getElements().get(0); } @Test public void shouldCompileClosureScriptDynamicDropDown() throws JAXBException, SAXException, ScriptingException, InstantiationException, IllegalAccessException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validDynamicDropDownConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); assertThat(getDynamicSelect(portletConfig).getDynamic().getOptions() .getClazz(), notNullValue()); Script script = portletConfig.getScript().get(0).getValue().getClazz() .newInstance(); script.getBinding() .setVariable( "log", LoggerFactory .getLogger(ConfigurationScriptsCompilerTest.class)); script.run(); Script dynamicClosureScript = getDynamicSelect(portletConfig) .getDynamic().getOptions().getClazz().newInstance(); @SuppressWarnings("unchecked") Closure<List<Integer>> dynamicClosure = (Closure<List<Integer>>) dynamicClosureScript .run(); dynamicClosure.setDelegate(script); ScriptRow scriptRowMock = mock(ScriptRow.class); java.util.List<Integer> ret = dynamicClosure.call(scriptRowMock, null); assertThat(ret.get(1), is(Integer.class)); verify(scriptRowMock).getValues(); } @Test public void shouldCompileComponentGeneratorScript() throws JAXBException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validCustomComponentConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); ScriptComponentConfig scriptComponentConfig = (ScriptComponentConfig) portletConfig .getPage().getElements().get(0); assertThat(scriptComponentConfig.getGenerator().getClazz(), notNullValue()); } @Test public void shouldCompileCustomFilterScript() throws JAXBException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validScriptContainerConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); FormConfig formConfig = (FormConfig) portletConfig.getPage() .getElements().get(0); FormActionConfig actionConfig = formConfig.getAction().get(0); List<FilterConfig> filters = actionConfig.getSearch().getApplyFilters() .getFilters(); List<FilterConfig> nestedFilters = ((AnyFilterConfig) filters.get(0)) .getFilters(); CustomFilterConfig customFilterConfig = (CustomFilterConfig) nestedFilters .get(nestedFilters.size() - 1); assertThat(customFilterConfig.getFilter().getClazz(), notNullValue()); } @Test public void shouldCompileCustomFilterScriptInSubfilters() throws JAXBException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validScriptContainerConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); FormConfig formConfig = (FormConfig) portletConfig.getPage() .getElements().get(0); FormActionConfig actionConfig = formConfig.getAction().get(0); List<FilterConfig> filters = actionConfig.getSearch().getApplyFilters() .getFilters(); AnyFilterConfig anyFilterConfig = (AnyFilterConfig) filters.get(0); CustomFilterConfig customFilterConfig = (CustomFilterConfig) anyFilterConfig .getFilters().get(anyFilterConfig.getFilters().size() - 1); assertThat(customFilterConfig.getFilter().getClazz(), notNullValue()); } @Test public void shouldReturnScriptComponentButton() throws JAXBException, InstantiationException, IllegalAccessException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validCustomComponentConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); ScriptComponentConfig scriptComponentConfig = (ScriptComponentConfig) portletConfig .getPage().getElements().get(0); Script generatorScript = scriptComponentConfig.getGenerator() .getClazz().newInstance(); Closure<?> generatorClosure = (Closure<?>) generatorScript.run(); Script mainScript = portletConfig.getScript().get(0).getValue() .getClazz().newInstance(); generatorClosure.setDelegate(mainScript); Object result = generatorClosure.call(new VaadinBuilder()); assertThat(result, new InstanceOf(Button.class)); } @Test public void shouldCompileTableStyleClosures() throws JAXBException, InstantiationException, IllegalAccessException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validTableStyleConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); Script mainScript = portletConfig.getScript().get(0).getValue() .getClazz().newInstance(); TableConfig tableConfig = (TableConfig) portletConfig.getPage() .getElements().get(0); assertThat(tableConfig.getRowStyle().getClazz(), notNullValue()); Script rowScript = tableConfig.getRowStyle().getClazz().newInstance(); @SuppressWarnings("unchecked") Closure<String> rowClosure = (Closure<String>) rowScript.run(); rowClosure.setDelegate(mainScript); ScriptRow scriptRowMock = mock(ScriptRow.class); String rowResult = rowClosure.call(scriptRowMock); assertThat(rowResult, is("rowStyle")); assertThat(tableConfig.getColumns().getColumn().size(), is(1)); int j = 0; for (ColumnConfig columnConfig : tableConfig.getColumns().getColumn()) { assertThat(columnConfig.getStyle().getClazz(), notNullValue()); Script columnScript = columnConfig.getStyle().getClazz() .newInstance(); @SuppressWarnings("unchecked") Closure<String> columnClosure = (Closure<String>) columnScript .run(); columnClosure.setDelegate(mainScript); String columnResult = columnClosure.call(scriptRowMock, "columnName" + j); assertThat(columnResult, is("style-columnName" + j)); j++; } } @Test public void shouldShowScriptPositionOnScriptErrors() throws JAXBException, SAXException, ScriptingException { PortletConfig portletConfig = createConfiguration("validScriptConfig.xml"); when( scriptCompilerMock .compileScript( "log.info \"Hello World\"\nlog.debug 'MainPortletScript.groovy execution finished...'", "MainPortletScript.groovy")).thenThrow( new ScriptingException(null, "portlet.crud.error.compilingScript")); try { compiler.compileAllScripts(portletConfig); fail(); } catch (BusinessException e) { assertThat(e.getCode(), is("portlet.crud.error.compilingScript")); } } @Test public void shouldCompileGStringDefaultColumnValue() throws JAXBException, InstantiationException, IllegalAccessException { ScriptCompiler scriptCompiler = new ScriptCompiler(); PortletConfig portletConfig = createConfiguration("validDefaultColumnValueConfig.xml"); new ConfigurationScriptsCompiler(scriptCompiler) .compileAllScripts(portletConfig); Script mainScript = portletConfig.getScript().get(0).getValue() .getClazz().newInstance(); TableConfig tableConfig = (TableConfig) portletConfig.getPage() .getElements().get(0); assertThat(tableConfig.getColumns().getColumn().get(2).getDefault() .getClazz(), notNullValue()); Script defaulValueScript = tableConfig.getColumns().getColumn().get(2) .getDefault().getClazz().newInstance(); Closure<?> defaultValueClosure = (Closure<?>) defaulValueScript.run(); defaultValueClosure.setDelegate(mainScript); Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String datumString = df.format(dt); Object object = defaultValueClosure.call(datumString); assertThat(object.toString(), is(datumString)); } @Test public void shouldCompileStatementClosure() throws JAXBException, InstantiationException, IllegalAccessException { PortletConfig portletConfig = createConfiguration("validScriptCrudConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock).compileScript(contains("def doInsert(row)"), eq("MainPortletScript.groovy")); verify(scriptCompilerMock).compileScript(contains("doInsert(row) //")); verify(scriptCompilerMock).compileScript(contains("doUpdate(row) //")); verify(scriptCompilerMock).compileScript(contains("doDelete(row) //")); } @Test public void shouldCompileScriptContainerDelegate() throws JAXBException { PortletConfig portletConfig = createConfiguration("validScriptContainerConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock, times(3)).compileScript(anyString()); } @Test public void shouldCompileReSTContainerScripts() throws JAXBException { PortletConfig portletConfig = createConfiguration("validReSTContainerFullXmlConfig.xml"); when(scriptCompilerMock.compileScript(anyString())).thenReturn( Script.class); compiler.compileAllScripts(portletConfig); TableConfig tableConfig = (TableConfig) portletConfig.getPage() .getElements().get(0); ReSTContainerConfig container = tableConfig.getRestContainer(); List<ReSTAttributeConfig> attributes = container.getQuery() .getAttribute(); assertScriptCompiled(container.getQuery().getCollection()); assertScriptCompiled(attributes.get(0).getPath()); assertScriptCompiled(attributes.get(1).getPath()); assertScriptCompiled(attributes.get(2).getPath()); assertScriptCompiled(container.getInsert().getValue()); assertScriptCompiled(container.getInsert().getUrl()); assertScriptCompiled(container.getUpdate().getValue()); assertScriptCompiled(container.getUpdate().getUrl()); assertScriptCompiled(container.getDelete().getUrl()); } private void assertScriptCompiled(GroovyScript collection) { assertThat(collection.getClazz(), notNullValue()); } @Test public void shouldCompileSqlStatementGString() throws JAXBException, InstantiationException, IllegalAccessException { PortletConfig portletConfig = createConfiguration("validQueryConfig.xml"); compiler.compileAllScripts(portletConfig); verify(scriptCompilerMock).compileScript(""); verify(scriptCompilerMock, times(3)).compileScript( startsWith("{ container,row,connection -> \"\"\"")); } @Test public void shouldCompileSimpleCompoundSearch() throws JAXBException, InstantiationException, IllegalAccessException { PortletConfig portletConfig = createConfiguration("validCompoundSearchSimpleConfig.xml"); compiler.compileAllScripts(portletConfig); } private SelectConfig getDynamicSelect(PortletConfig portletConfig) { ColumnsConfig columns = ((TableConfig) portletConfig.getPage() .getElements().get(0)).getColumns(); for (ColumnConfig cfg : columns.getColumn()) { if (cfg.getSelect() != null && cfg.getSelect().getDynamic() != null) { return cfg.getSelect(); } } return null; } private void assertScriptExecution(PortletConfig portletConfig) throws InstantiationException, IllegalAccessException { // mocking ScriptPortlet portletMock = mock(ScriptPortlet.class); ScriptTabs tabsMock = mock(ScriptTabs.class); ScriptTab tabMock = mock(ScriptTab.class); ScriptTab tabMock2 = mock(ScriptTab.class); Map<String, ScriptTab> elements = new LinkedHashMap<String, ScriptTab>(); elements.put("tab1", tabMock); elements.put("tab2", tabMock2); when(portletMock.getTabs()).thenReturn(tabsMock); when(tabsMock.getElements()).thenReturn(elements); when(tabsMock.getActiveTab()).thenReturn(tabMock); when(tabMock.getId()).thenReturn("tab1"); Script script = portletConfig.getScript().get(0).getValue().getClazz() .newInstance(); script.getBinding().setVariable("portlet", portletMock); script.getBinding() .setVariable( "log", LoggerFactory .getLogger(ConfigurationScriptsCompilerTest.class)); script.run(); @SuppressWarnings("unchecked") Closure<ScriptTab> closure = ((Closure<ScriptTab>) getTabs( portletConfig).getOnChange().getClazz().newInstance().run()); closure.setDelegate(script); } private TabsConfig getTabs(PortletConfig portletConfig) { return (TabsConfig) portletConfig.getPage().getElements().get(2); } private TabConfig getTab(PortletConfig portletConfig) { return getTabs(portletConfig).getTab().get(0); } private TableConfig getTable(PortletConfig portletConfig) { return ((TableConfig) getTab(portletConfig).getElements().get(0)); } private FormConfig getForm(PortletConfig portletConfig) { return (FormConfig) portletConfig.getPage().getElements().get(1); } private FormActionConfig getFormAction(PortletConfig portletConfig) { return getForm(portletConfig).getAction().get(0); } private FormFieldConfig getFormField(PortletConfig portletConfig) { return getForm(portletConfig).getField().get(0); } private TableActionConfig getTableAction(PortletConfig portletConfig) { return getTableActions(portletConfig).get(0); } private List<TableActionConfig> getTableActions(PortletConfig portletConfig) { return getTable(portletConfig).getAction(); } private DatabaseQueryConfig getDatabaseQuery(PortletConfig portletConfig) { return getTable(portletConfig).getDatabaseQuery(); } }
37.385563
116
0.772404
e755d98233c1c3f90b3c16aab36ec0c732a3dc78
6,692
/* * Created by JFormDesigner on Thu Dec 25 17:41:56 KST 2014 */ package kr.pe.sinnori.gui.screen; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; import kr.pe.sinnori.gui.table.ConfigItemKeyRenderer; import kr.pe.sinnori.gui.table.ConfigItemTableModel; import kr.pe.sinnori.gui.table.ConfigItemValueEditor; import kr.pe.sinnori.gui.table.ConfigItemValueRenderer; import com.jgoodies.forms.factories.*; import com.jgoodies.forms.layout.*; /** * @author Jonghoon Won */ @SuppressWarnings("serial") public class DBCPPartConfigPopup extends JDialog { private String mainProjectName; private String selectedDBCPConnPoolName; private ConfigItemTableModel dbcpPartTableModel; public DBCPPartConfigPopup(Frame owner, String mainProjectName, String selectedDBCPConnPoolName, ConfigItemTableModel dbcpPartTableModel) { super(owner); initComponents(); this.mainProjectName = mainProjectName; this.selectedDBCPConnPoolName = selectedDBCPConnPoolName; this.dbcpPartTableModel = dbcpPartTableModel; mainProjectNameValueLabel.setText(this.mainProjectName); dbcpConnPoolNameValueLabel.setText(this.selectedDBCPConnPoolName); dbcpPartTable.setModel(this.dbcpPartTableModel); dbcpPartTable.getColumnModel().getColumn(0).setCellRenderer(new ConfigItemKeyRenderer()); dbcpPartTable.getColumnModel().getColumn(1).setResizable(false); dbcpPartTable.getColumnModel().getColumn(1).setPreferredWidth(250); dbcpPartTable.getColumnModel().getColumn(1).setCellRenderer(new ConfigItemValueRenderer()); dbcpPartTable.getColumnModel().getColumn(1).setCellEditor(new ConfigItemValueEditor(new JCheckBox())); dbcpPartTable.setRowHeight(38); dbcpPartScrollPane.repaint(); } /* public DBCPPartConfigPopup(Dialog owner) { super(owner); initComponents(); // dbcpPartTable }*/ private void okButtonActionPerformed(ActionEvent e) { // TODO add your code here } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents // Generated using JFormDesigner non-commercial license dialogPane = new JPanel(); contentPanel = new JPanel(); mainProjectLinePanel = new JPanel(); mainProjectNameTitleLabel = new JLabel(); mainProjectNameValueLabel = new JLabel(); dbcpConnPoolNameLinePanel = new JPanel(); dbcpConnPoolNameTitleLabel = new JLabel(); dbcpConnPoolNameValueLabel = new JLabel(); dbcpPartIntroductionLable = new JLabel(); dbcpPartScrollPane = new JScrollPane(); dbcpPartTable = new JTable(); buttonBar = new JPanel(); okButton = new JButton(); //======== this ======== Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== dialogPane ======== { dialogPane.setBorder(Borders.createEmptyBorder("7dlu, 7dlu, 7dlu, 7dlu")); dialogPane.setLayout(new BorderLayout()); //======== contentPanel ======== { contentPanel.setLayout(new FormLayout( "394dlu:grow", "3*(default, $lgap), default")); //======== mainProjectLinePanel ======== { mainProjectLinePanel.setLayout(new FormLayout( "110dlu, $lcgap, 168dlu", "default")); //---- mainProjectNameTitleLabel ---- mainProjectNameTitleLabel.setText("Main Project Name :"); mainProjectLinePanel.add(mainProjectNameTitleLabel, CC.xy(1, 1)); mainProjectLinePanel.add(mainProjectNameValueLabel, CC.xy(3, 1)); } contentPanel.add(mainProjectLinePanel, CC.xy(1, 1)); //======== dbcpConnPoolNameLinePanel ======== { dbcpConnPoolNameLinePanel.setLayout(new FormLayout( "110dlu, $lcgap, 200dlu", "default")); //---- dbcpConnPoolNameTitleLabel ---- dbcpConnPoolNameTitleLabel.setText("DBCP Connection Pool Name :"); dbcpConnPoolNameLinePanel.add(dbcpConnPoolNameTitleLabel, CC.xy(1, 1)); dbcpConnPoolNameLinePanel.add(dbcpConnPoolNameValueLabel, CC.xy(3, 1)); } contentPanel.add(dbcpConnPoolNameLinePanel, CC.xy(1, 3)); //---- dbcpPartIntroductionLable ---- dbcpPartIntroductionLable.setText("DBCP Part Config"); contentPanel.add(dbcpPartIntroductionLable, CC.xy(1, 5)); //======== dbcpPartScrollPane ======== { //---- dbcpPartTable ---- dbcpPartTable.setModel(new DefaultTableModel( new Object[][] { {null, null}, }, new String[] { "key", "value" } ) { Class<?>[] columnTypes = new Class<?>[] { String.class, Object.class }; boolean[] columnEditable = new boolean[] { false, false }; @Override public Class<?> getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnEditable[columnIndex]; } }); { TableColumnModel cm = dbcpPartTable.getColumnModel(); cm.getColumn(1).setMinWidth(150); } dbcpPartTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); dbcpPartTable.setAutoCreateColumnsFromModel(false); dbcpPartScrollPane.setViewportView(dbcpPartTable); } contentPanel.add(dbcpPartScrollPane, CC.xy(1, 7)); } dialogPane.add(contentPanel, BorderLayout.CENTER); //======== buttonBar ======== { buttonBar.setBorder(Borders.createEmptyBorder("5dlu, 0dlu, 0dlu, 0dlu")); buttonBar.setLayout(new FormLayout( "$glue, $button", "pref")); //---- okButton ---- okButton.setText("Close"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { okButtonActionPerformed(e); } }); buttonBar.add(okButton, CC.xy(2, 1)); } dialogPane.add(buttonBar, BorderLayout.SOUTH); } contentPane.add(dialogPane, BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables // Generated using JFormDesigner non-commercial license private JPanel dialogPane; private JPanel contentPanel; private JPanel mainProjectLinePanel; private JLabel mainProjectNameTitleLabel; private JLabel mainProjectNameValueLabel; private JPanel dbcpConnPoolNameLinePanel; private JLabel dbcpConnPoolNameTitleLabel; private JLabel dbcpConnPoolNameValueLabel; private JLabel dbcpPartIntroductionLable; private JScrollPane dbcpPartScrollPane; private JTable dbcpPartTable; private JPanel buttonBar; private JButton okButton; // JFormDesigner - End of variables declaration //GEN-END:variables }
31.866667
104
0.712642
b84e8ccb8c3ae0eb87ce5dd9de700b3bca483ce9
578
package com.baigaoli.easyweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by likaisong on 2018/11/28. */ public class Forecast { @SerializedName("date") public String date; @SerializedName("tmp") public TemperaTure temperaTure; @SerializedName("cond") public More more; public class TemperaTure{ @SerializedName("max") public String max; @SerializedName("min") public String min; } public class More{ @SerializedName("txt_d") public String info; } }
18.0625
50
0.641869
4fa4d13223b31d9de3f1c26f6a397cd972dfbe4b
849
package com.oa.core.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * 错误页面的控制器 * * @author zxd * */ @Controller public class ErrorController { /** * 重复提交页面 * @author zxd * @return */ @RequestMapping(value = "/error_repeat_submit", method = RequestMethod.GET) public ModelAndView gotoRepeatSubmitErrorPage() { ModelAndView mav = new ModelAndView("error_repeat_submit"); return mav; } /** * 无权查看页面 * @author zxd * @return */ @RequestMapping(value = "/error_no_right", method = RequestMethod.GET) public ModelAndView gotoNoRightErrorPage() { ModelAndView mav = new ModelAndView("error_no_right"); return mav; } }
21.769231
76
0.738516
167333b961b3901cf054a7af8f01a546690b4da9
4,534
/* * mxisd - Matrix Identity Server Daemon * Copyright (C) 2019 Kamax Sarl * * https://www.kamax.io/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.kamax.mxisd.as.registration; import io.kamax.mxisd.config.AppServiceConfig; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class SynapseRegistrationYaml { public static SynapseRegistrationYaml parse(AppServiceConfig cfg, String domain) { SynapseRegistrationYaml yaml = new SynapseRegistrationYaml(); yaml.setId(cfg.getRegistration().getSynapse().getId()); yaml.setUrl(cfg.getEndpoint().getToAS().getUrl()); yaml.setAsToken(cfg.getEndpoint().getToHS().getToken()); yaml.setHsToken(cfg.getEndpoint().getToAS().getToken()); yaml.setSenderLocalpart(cfg.getUser().getMain()); if (cfg.getFeature().getCleanExpiredInvite()) { Namespace ns = new Namespace(); ns.setExclusive(true); ns.setRegex("@" + cfg.getUser().getInviteExpired() + ":" + domain); yaml.getNamespaces().getUsers().add(ns); } if (cfg.getFeature().getInviteById()) { Namespace ns = new Namespace(); ns.setExclusive(false); ns.setRegex("@*:" + domain); yaml.getNamespaces().getUsers().add(ns); } return yaml; } public static class Namespace { private String regex; private boolean exclusive; public String getRegex() { return regex; } public void setRegex(String regex) { this.regex = regex; } public boolean isExclusive() { return exclusive; } public void setExclusive(boolean exclusive) { this.exclusive = exclusive; } } public static class Namespaces { private List<Namespace> users = new ArrayList<>(); private List<Namespace> aliases = new ArrayList<>(); private List<Namespace> rooms = new ArrayList<>(); public List<Namespace> getUsers() { return users; } public void setUsers(List<Namespace> users) { this.users = users; } public List<Namespace> getAliases() { return aliases; } public void setAliases(List<Namespace> aliases) { this.aliases = aliases; } public List<Namespace> getRooms() { return rooms; } public void setRooms(List<Namespace> rooms) { this.rooms = rooms; } } private String id; private String url; private String as_token; private String hs_token; private String sender_localpart; private Namespaces namespaces = new Namespaces(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public void setUrl(URL url) { if (Objects.isNull(url)) { this.url = null; } else { this.url = url.toString(); } } public String getAsToken() { return as_token; } public void setAsToken(String as_token) { this.as_token = as_token; } public String getHsToken() { return hs_token; } public void setHsToken(String hs_token) { this.hs_token = hs_token; } public String getSenderLocalpart() { return sender_localpart; } public void setSenderLocalpart(String sender_localpart) { this.sender_localpart = sender_localpart; } public Namespaces getNamespaces() { return namespaces; } public void setNamespaces(Namespaces namespaces) { this.namespaces = namespaces; } }
25.615819
86
0.613145
bd2ce83fdb14eff3185cc9228d396fdad3afba40
902
package org.ednovo.gooru.core.api.model; import java.io.Serializable; public class Idp implements Serializable{ /** * */ private static final long serialVersionUID = -8057521950467645504L; public static String defaultIdp = "NA"; private Short idpId; private String name; private Short gooruInstalled = 0; public Short getIdpId() { return idpId; } public void setIdpId(Short idpId) { this.idpId = idpId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getGooruInstalled() { return gooruInstalled; } public void setGooruInstalled(Short gooruInstalled) { this.gooruInstalled = gooruInstalled; } public static String getDefaultIdp() { return defaultIdp; } public static void setDefaultIdp(final String DEFAULT_IDP) { defaultIdp = DEFAULT_IDP; } }
20.976744
69
0.695122
4868c97a58ed370399edee517711dc49d82270bc
8,778
package net.jsunit; import com.opensymphony.xwork.config.ConfigurationProvider; import net.jsunit.configuration.CompositeConfigurationSource; import net.jsunit.configuration.ConfigurationSource; import net.jsunit.configuration.ServerConfiguration; import net.jsunit.logging.BrowserResultRepository; import net.jsunit.logging.FileBrowserResultRepository; import net.jsunit.model.Browser; import net.jsunit.model.BrowserLaunchSpecification; import net.jsunit.model.BrowserResult; import net.jsunit.model.ResultType; import net.jsunit.utility.StringUtility; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsUnitServer extends AbstractJsUnitServer implements BrowserTestRunner, WebServer { private static JsUnitServer instance; private List<TestRunListener> browserTestRunListeners = new ArrayList<TestRunListener>(); private ProcessStarter processStarter = new DefaultProcessStarter(); private TimeoutChecker timeoutChecker; private BrowserResultRepository browserResultRepository; private Map<Browser, Process> launchedBrowsersToProcesses = new HashMap<Browser, Process>(); private BrowserResult lastResult; public JsUnitServer(ServerConfiguration configuration) { this(configuration, new FileBrowserResultRepository(configuration.getLogsDirectory())); } public JsUnitServer(ServerConfiguration configuration, BrowserResultRepository repository) { super(configuration); setResultRepository(repository); registerInstance(this); } public static void main(String args[]) { try { ConfigurationSource source = CompositeConfigurationSource.forArguments(args); JsUnitServer server = new JsUnitServer(new ServerConfiguration(source)); server.start(); } catch (Throwable t) { t.printStackTrace(); } } public void accept(BrowserResult result) { Browser submittingBrowser = result.getBrowser(); endBrowser(submittingBrowser); for (TestRunListener listener : browserTestRunListeners) listener.browserTestRunFinished(submittingBrowser, result); launchedBrowsersToProcesses.remove(submittingBrowser); lastResult = result; } private void killTimeoutChecker() { if (timeoutChecker != null) { timeoutChecker.die(); timeoutChecker = null; } } public BrowserResult findResultWithId(String id, int browserId) throws InvalidBrowserIdException { Browser browser = configuration.getBrowserById(browserId); if (browser == null) throw new InvalidBrowserIdException(browserId); return findResultWithId(id, browser); } private BrowserResult findResultWithId(String id, Browser browser) { return browserResultRepository.retrieve(id, browser); } public String toString() { return "JsUnit Server"; } public List<Browser> getBrowsers() { return configuration.getBrowsers(); } public boolean isWaitingForBrowser(Browser browser) { return launchedBrowsersToProcesses.containsKey(browser); } public void addTestRunListener(TestRunListener listener) { browserTestRunListeners.add(listener); } public void removeTestRunListener(TestRunListener listener) { browserTestRunListeners.remove(listener); } public List<TestRunListener> getBrowserTestRunListeners() { return browserTestRunListeners; } private void endBrowser(Browser browser) { Process process = launchedBrowsersToProcesses.get(browser); if (process != null && configuration.shouldCloseBrowsersAfterTestRuns()) { if (!StringUtility.isEmpty(browser.getKillCommand())) { try { processStarter.execute(new String[]{browser.getKillCommand()}); } catch (IOException e) { e.printStackTrace(); } } else { process.destroy(); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } waitUntilProcessHasExitValue(process); } } killTimeoutChecker(); } private void waitUntilProcessHasExitValue(Process browserProcess) { while (true) { //noinspection EmptyCatchBlock try { if (browserProcess != null) browserProcess.exitValue(); return; } catch (IllegalThreadStateException e) { } } } public void launchBrowserTestRun(BrowserLaunchSpecification launchSpec) { long launchTime = System.currentTimeMillis(); Browser browser = launchSpec.getBrowser(); LaunchTestRunCommand command = new LaunchTestRunCommand(launchSpec, configuration); String displayName = browser.getDisplayName(); try { logger.info("Launching " + displayName + " on " + command.getTestURL()); for (TestRunListener listener : browserTestRunListeners) listener.browserTestRunStarted(browser); Process process = processStarter.execute(command.generateArray()); launchedBrowsersToProcesses.put(browser, process); startTimeoutChecker(launchTime, browser, process); } catch (Throwable throwable) { handleCrashWhileLaunching(throwable, browser); } } private void handleCrashWhileLaunching(Throwable throwable, Browser browser) { logger.info(failedToLaunchStatusMessage(browser, throwable)); BrowserResult failedToLaunchBrowserResult = new BrowserResult(); failedToLaunchBrowserResult._setResultType(ResultType.FAILED_TO_LAUNCH); failedToLaunchBrowserResult.setBrowser(browser); failedToLaunchBrowserResult._setServerSideException(throwable); accept(failedToLaunchBrowserResult); } private String failedToLaunchStatusMessage(Browser browser, Throwable throwable) { String result = "Browser " + browser.getDisplayName() + " failed to launch: " + throwable.getClass().getName(); if (throwable.getMessage() != null) result += (" - " + throwable.getMessage()); return result; } private void startTimeoutChecker(long launchTime, Browser browser, Process process) { timeoutChecker = new TimeoutChecker(process, browser, launchTime, this); timeoutChecker.start(); } void setProcessStarter(ProcessStarter starter) { this.processStarter = starter; } public void startTestRun() { for (TestRunListener listener : browserTestRunListeners) { listener.testRunStarted(); while (!listener.isReady()) //noinspection EmptyCatchBlock try { Thread.sleep(100); } catch (InterruptedException e) { } } } public void finishTestRun() { for (TestRunListener listener : browserTestRunListeners) listener.testRunFinished(); } public void dispose() { super.dispose(); for (Browser browser : new HashMap<Browser, Process>(launchedBrowsersToProcesses).keySet()) endBrowser(browser); } public int timeoutSeconds() { return configuration.getTimeoutSeconds(); } public BrowserResult lastResult() { return lastResult; } protected ConfigurationProvider createConfigurationProvider() { return new JsUnitServerConfigurationProvider(); } protected String resourceBase() { return configuration.getResourceBase().toString(); } public void setResultRepository(BrowserResultRepository repository) { this.browserResultRepository = repository; addTestRunListener(new BrowserResultLogWriter(browserResultRepository)); } protected List<String> servletNames() { List<String> result = new ArrayList<String>(); result.add("acceptor"); result.add("config"); result.add("displayer"); result.add("runner"); return result; } public static void registerInstance(JsUnitServer server) { JsUnitServer.instance = server; } public static JsUnitServer instance() { return instance; } }
36.423237
120
0.652427
38669445d5df1e0d04c9dbb3b1dcb3755bf80d7d
3,025
package kr.ync.project.admin.controller; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.mvc.support.RedirectAttributes; import kr.ync.project.admin.domain.CategorySmallVO; import kr.ync.project.admin.service.CategorySmallService; @Controller @RequestMapping("/admin/*") public class CategorySmallController { private static final Logger logger = LoggerFactory.getLogger(CategorySmallController.class); @Inject private CategorySmallService service; // 소분류 리스트 @RequestMapping(value = "/categorysmallList", method = RequestMethod.GET) public String smallList(Model model) throws Exception { logger.info("소분류 리스트목록보기"); model.addAttribute("smalllist", service.SmalllistAll()); return "admin/categorysmallList"; } // 글 작성 get @RequestMapping(value = "/categorysmallRegister", method = RequestMethod.GET) public void getCategorysmall(CategorySmallVO vo, Model model) throws Exception { logger.info("get categorysmall"); } // 글 작성 post @RequestMapping(value = "/categorysmallRegister", method = RequestMethod.POST) public String postCategorysmall(CategorySmallVO vo, RedirectAttributes rttr) throws Exception { logger.info("post categorysmall"); logger.info(vo.toString()); service.createCategorySmall(vo); rttr.addFlashAttribute("msg", "success"); return "redirect:/admin/categorysmallList"; } // 상세 @RequestMapping(value = "/categorysmallRead", method = RequestMethod.GET) public void categorysmallRead(@RequestParam("pSmall") int pSmall, Model model) throws Exception { logger.info("리스트상세보기"); model.addAttribute(service.readCategorySmall(pSmall)); } // 삭제 @RequestMapping(value = "/deleteCategorySmall", method = RequestMethod.POST) public String remove(@RequestParam("pSmall") int pSmall, RedirectAttributes rttr) throws Exception { logger.info("소분류 카테고리 삭제"); service.deleteCategorySmall(pSmall); rttr.addFlashAttribute("msg", "SUCCESS"); return "redirect:/admin/categorysmallList"; } // 글 수정 get @RequestMapping(value = "/categorysmallModify", method = RequestMethod.GET) public void getModify(int pSmall, Model model) throws Exception { logger.info("소분류 카테고리 수정 get"); model.addAttribute(service.readCategorySmall(pSmall)); } // 글 수정 post @RequestMapping(value = "/categorysmallModify", method = RequestMethod.POST) public String postModify(CategorySmallVO vo, RedirectAttributes rttr) throws Exception { logger.info("소분류 카테고리 수정 post"); service.updateCategorySmall(vo); rttr.addFlashAttribute("msg", "SUCCESS"); return "redirect:/admin/categorysmallList"; } }
28.537736
102
0.745785
e5ce27ba5803eb286740e2b03ffd0eb7b8746327
6,064
package net.a6te.lazycoder.andropos.modelClass; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Programmer on 6/19/2017. */ public class CustomerOnlineDataModel { @SerializedName("companyInfo") @Expose private List<CompanyInfo> companyInfo = null; @SerializedName("customerInfo") @Expose private List<CustomerInfo> customerInfo = null; public List<CompanyInfo> getCompanyInfo() { return companyInfo; } public void setCompanyInfo(List<CompanyInfo> companyInfo) { this.companyInfo = companyInfo; } public List<CustomerInfo> getCustomerInfo() { return customerInfo; } public void setCustomerInfo(List<CustomerInfo> customerInfo) { this.customerInfo = customerInfo; } public class CompanyInfo { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; @SerializedName("contact_no") @Expose private String contactNo; @SerializedName("email") @Expose private String email; @SerializedName("address") @Expose private String address; @SerializedName("description") @Expose private String description; @SerializedName("logo") @Expose private String logo; @SerializedName("created_date") @Expose private String createdDate; @SerializedName("modified_date") @Expose private String modifiedDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContactNo() { return contactNo; } public void setContactNo(String contactNo) { this.contactNo = contactNo; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public String getModifiedDate() { return modifiedDate; } public void setModifiedDate(String modifiedDate) { this.modifiedDate = modifiedDate; } } public class CustomerInfo { @SerializedName("id") @Expose private String id; @SerializedName("full_name") @Expose private String fullName; @SerializedName("customer_code") @Expose private String customerCode; @SerializedName("customer_type") @Expose private Object customerType; @SerializedName("gender") @Expose private String gender; @SerializedName("phone_no") @Expose private String phoneNo; @SerializedName("email") @Expose private String email; @SerializedName("address") @Expose private String address; @SerializedName("due_amount") @Expose private Object dueAmount; @SerializedName("image") @Expose private Object image; @SerializedName("emp_id") @Expose private String empId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getCustomerCode() { return customerCode; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public Object getCustomerType() { return customerType; } public void setCustomerType(Object customerType) { this.customerType = customerType; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Object getDueAmount() { return dueAmount; } public void setDueAmount(Object dueAmount) { this.dueAmount = dueAmount; } public Object getImage() { return image; } public void setImage(Object image) { this.image = image; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } } }
22.796992
66
0.551121
ff9b1ac735301687bd9d34189748cbb1c34e18f1
1,397
package com.ig.api.fix.otc.trading.app.quickfixj; import java.util.List; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import quickfix.FieldNotFound; import quickfix.Group; import quickfix.IncorrectTagValue; import quickfix.SessionID; import quickfix.UnsupportedMessageType; import quickfix.field.NoPositions; import quickfix.field.OriginatingClientOrderRef; import quickfix.fix50sp2.ExecutionReport; import quickfix.fix50sp2.MessageCracker; import quickfix.fix50sp2.PositionReport; @Slf4j @Component public class MessageCrackerFix50sp2 extends MessageCracker { @Override public void onMessage(ExecutionReport message, SessionID sessionID) throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue { log.info("Received execution report for client order: {} order status: {}", message.getClOrdID().getValue(), message.getOrdStatus().getValue()); } @Override public void onMessage(PositionReport message, SessionID sessionID) throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue { final List<Group> noPositions = message.getGroups(NoPositions.FIELD); log.info("Received position report for client order: {} on account: {}", noPositions.get(0).getString(OriginatingClientOrderRef.FIELD), message.getAccount().getValue()); } }
33.261905
112
0.758769
204fb81c5308f0a872f5e1dc8bc1c826b6a0a3f1
417
package com.jfeat.poi.agent.im.request; public class Option { public String postfix; //UPDATE POSTFIX public String type; public String getPostfix() { return postfix; } public void setPostfix(String postfix) { this.postfix = postfix; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
16.68
44
0.601918
20c71b7b8a20d360a755f0fb990ed25a5f2e06af
1,133
package PreProcessing; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PreProcessingMapper extends Mapper<Object, Text, Text, Text> { @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { Pattern pattern = Pattern.compile("(\\S+)\\s\\[(.+)\\]"); Matcher matcher = pattern.matcher(value.toString()); String name = "", link = ""; while (matcher.find()) { name = matcher.group(1); link = matcher.group(2); } StringBuilder links = new StringBuilder(); String[] linkList = link.split("\\|"); for (int i = 0; i < linkList.length; i++) { String[] splits = linkList[i].split(","); links.append(splits[0]).append(":").append(splits[0]).append(",").append(splits[1]); if (i != linkList.length - 1) links.append(";"); } context.write(new Text(name + ":" + name), new Text(links.toString())); } }
37.766667
106
0.605472
50879cb38e4af94a7b9cc33fc10bacd18d5dac87
4,102
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tdb; import org.apache.jena.atlas.lib.Pair ; import org.apache.jena.graph.Node ; import org.apache.jena.query.Query ; import org.apache.jena.query.QueryFactory ; import org.apache.jena.rdf.model.impl.Util ; import org.apache.jena.sparql.algebra.Algebra ; import org.apache.jena.sparql.algebra.Op ; import org.apache.jena.sparql.algebra.TransformCopy ; import org.apache.jena.sparql.algebra.Transformer ; import org.apache.jena.sparql.algebra.op.OpFilter ; import org.apache.jena.sparql.algebra.optimize.TransformFilterEquality ; import org.apache.jena.sparql.core.Var ; import org.apache.jena.sparql.expr.* ; import org.apache.jena.tdb.store.NodeId ; /** This transform is like {@linkplain TransformFilterEquality} but it is * value based and more aggressive. * It only work on BGPs+Filters. * It works for TDB where terms have been canonicalized (integers, decimals, date, dateTimes). */ public class TransformFilterSameValue extends TransformCopy { public static void main(String ...a) { String qs = "SELECT * { ?s ?p ?o . " + "FILTER(?o1 = 'foo')" + "FILTER(?o2 = 123)" + "FILTER(?o3 = 'foo'@en)" + "FILTER(?o4 = 123e0)" + "}" ; Query query = QueryFactory.create(qs) ; Op op = Algebra.compile(query) ; Op op1 = Transformer.transform(new TransformFilterSameValue(), op) ; // Op op1 = Algebra.optimize(op) ; // System.out.println(op1) ; } public TransformFilterSameValue() {} @Override public Op transform(OpFilter opFilter, Op subOp) { Op op = apply(opFilter.getExprs(), subOp) ; if ( op == null ) return super.transform(opFilter, subOp) ; return op ; } private Op apply(ExprList exprs, Op subOp) { //return null ; for ( Expr e : exprs.getList() ) { Pair<Var, NodeValue> p = preprocess(e) ; System.out.println(p) ; } return null ; } // From TransformFilterEquality private static Pair<Var, NodeValue> preprocess(Expr e) { if (!(e instanceof E_Equals) && !(e instanceof E_SameTerm)) return null; ExprFunction2 eq = (ExprFunction2) e; Expr left = eq.getArg1(); Expr right = eq.getArg2(); Var var = null; NodeValue constant = null; if (left.isVariable() && right.isConstant()) { var = left.asVar(); constant = right.getConstant(); } else if (right.isVariable() && left.isConstant()) { var = right.asVar(); constant = left.getConstant(); } if (var == null || constant == null) return null; Node n = constant.getNode() ; if ( ! n.isLiteral() ) // URI or blank node return Pair.create(var, constant); // General if ( Util.isLangString(n) || Util.isSimpleString(n) ) { return Pair.create(var, constant); } // TDB. Nodes that are inline are canonical constants. if ( NodeId.inline(constant.getNode()) != null ) { return Pair.create(var, constant); } // No return null ; } }
33.080645
94
0.617747
a00f07eb5b10808ce7ae24184404535e9da6d286
79
package org.javaturk.oopj.ch10.compiling; public class C { D d = new D(); }
11.285714
41
0.670886
7665a88464251d367a50e5bf5c9ff763a528336d
3,277
package graphics2d.things; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import javax.vecmath.Vector4f; import game.Main; import graphics2d.util.FontAtlas; import graphics2d.util.Glyph; import graphics2d.util.InstancedRenderConfig2d; import graphics2d.util.InstancedRenderer2d; import lepton.engine.rendering.InstanceAccumulator; import lepton.engine.rendering.Shader; public class TextGroup extends Thing2d { public static Shader textShader; public ArrayList<GenericInstancedThing2d> characters=new ArrayList<GenericInstancedThing2d>(); private String s; private FontAtlas f; public float height; public float r; public float g; public float b; private InstanceAccumulator ia; public TextGroup(String str, FontAtlas font, float x, float y, float height, float r, float g, float b, InstancedRenderer2d sl) { f=font; s=str; refreshString=true; this.x=x; this.y=y; this.height=height; if(textShader==null) { textShader=Main.shaderLoader.load("specific/textChar"); } ia=sl.loadConfiguration(textShader,f.textureImage,Thing2d.genericSquare,12,"info_buffer").instanceAccumulator; this.r=r; this.g=g; this.b=b; } private boolean refreshString=false; public void setString(String s) { this.s=s; refreshString=true; } @Override public void logic() { float pix2ui=height/f.getHeight(); if(refreshString) { int len=0; for(int i=0;i<s.length();i++) { if(f.get(s.charAt(i))!=null) { len++; } } while(len!=characters.size()) { if(len<characters.size()) { characters.remove(characters.size()-1); } else { GenericInstancedThing2d t=(GenericInstancedThing2d)new GenericInstancedThing2d(ia).setParent(parent); t.posMode=this.posMode; characters.add(t); } } Glyph a=f.get('I'); int spacew=a.end-a.start; int offset=0; int diff=0; for(int i=0;i<s.length();i++) { Glyph g=f.get(s.charAt(i)); if(g!=null) { GenericInstancedThing2d c=characters.get(i+diff); c.x=(offset*pix2ui)+x; c.y=y; c.height=height; c.width=pix2ui*(g.end-g.start); c.objectSize=GenericInstancedThing2d.defaultObjectSize+4; // c.image=f.textureImage; c.texX=g.start/(float)f.getWidth(); c.texY=0; c.texW=(g.end-g.start)/(float)f.getWidth(); c.texH=1; // c.renderingShader=textShader; c.refreshDataLength(); c.additionalData[0]=this.r; c.additionalData[1]=this.g; c.additionalData[2]=this.b; c.additionalData[3]=0; } else { diff--; } int w=g==null?spacew:g.end-g.start; offset+=w; offset+=f.getSpacing(); } refreshString=false; } runEventListeners(); } @Override public void render() { for(GenericInstancedThing2d t : characters) { t.render(); } } private Vector4f a=new Vector4f(); @Override public Vector4f getBoundingBox() { if(characters.size()==0) {a.set(x,y,x,y); return a;} Vector4f bb0=characters.get(0).getBoundingBox(); Vector4f bb1=characters.get(characters.size()-1).getBoundingBox(); a.set(bb0.x,bb1.y,bb1.z,bb0.w); return a; } @Override public Thing2d setParent(Thing2d parent) { for(GenericInstancedThing2d c : characters) { c.setParent(parent); } this.parent=parent; return this; } }
26.216
130
0.68996
0aad52b3b6860daddff52f39208046d28df33c0b
5,923
package org.concordion.internal.extension; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.concordion.api.extension.ConcordionExtension; import org.concordion.api.extension.ConcordionExtensionFactory; import org.concordion.api.extension.Extension; import org.concordion.api.extension.Extensions; import org.concordion.internal.ConcordionBuilder; public class FixtureExtensionLoader { public void addExtensions(final Object fixture, ConcordionBuilder concordionBuilder) { for (ConcordionExtension concordionExtension : getExtensionsForFixture(fixture)) { concordionExtension.addTo(concordionBuilder); } } public List<ConcordionExtension> getExtensionsForFixture(Object fixture) { final List<ConcordionExtension> extensions = new ArrayList<ConcordionExtension>(); List<Class<?>> classes = getClassHierarchyParentFirst(fixture.getClass()); for (Class<?> class1 : classes) { extensions.addAll(getExtensionsFromClassAnnotation(class1)); extensions.addAll(getExtensionsFromAnnotatedFields(fixture, class1)); } return extensions; } private Collection<? extends ConcordionExtension> getExtensionsFromClassAnnotation(Class<?> class1) { if (class1.isAnnotationPresent(Extensions.class)) { ArrayList<ConcordionExtension> extensions = new ArrayList<ConcordionExtension>(); Extensions extensionsAnnotation = class1.getAnnotation(Extensions.class); Class<?>[] value = extensionsAnnotation.value(); for (Class<?> class2 : value) { if (ConcordionExtension.class.isAssignableFrom(class2)) { ConcordionExtension extension = (ConcordionExtension) newInstance(class2, "extension"); extensions.add(extension); } else if (ConcordionExtensionFactory.class.isAssignableFrom(class2)) { ConcordionExtensionFactory factory = (ConcordionExtensionFactory) newInstance(class2, "extension factory"); extensions.add(factory.createExtension()); } else { throw new ExtensionInitialisationException( String.format("Class %s specified in @Extensions annotation in class %s must implement %s or %s", class2.getCanonicalName(), class1.getCanonicalName(), ConcordionExtension.class.getCanonicalName(), ConcordionExtensionFactory.class.getCanonicalName())); } } return extensions; } return Collections.emptyList(); } private Object newInstance(Class<?> type, String description) { Object object; try { object = type.newInstance(); } catch (InstantiationException e) { throw new ExtensionInitialisationException(String.format("Unable to instantiate %s of class %s", description, type.getCanonicalName()) , e); } catch (IllegalAccessException e) { throw new ExtensionInitialisationException(String.format("Unable to access no-args constructor of %s class %s", description, type.getCanonicalName()) , e); } return object; } private List<ConcordionExtension> getExtensionsFromAnnotatedFields(Object fixture, Class<?> class1) { List<ConcordionExtension> extensions = new ArrayList<ConcordionExtension>(); Field[] declaredFields = class1.getDeclaredFields(); for (Field field : declaredFields) { if (field.isAnnotationPresent(Extension.class)) { validatePublic(field); ConcordionExtension extension = getExtensionField(fixture, field); validateNonNull(field, extension); extensions.add(extension); } } return extensions; } /** * Returns the specified class and all of its superclasses, excluding java.lang.Object, * ordered from the most super class to the specified class. */ private List<Class<?>> getClassHierarchyParentFirst(Class<?> class1) { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); Class<?> current = class1; while (current != null && current != Object.class) { classes.add(current); current = current.getSuperclass(); } Collections.reverse(classes); return classes; } private ConcordionExtension getExtensionField(Object fixture, Field field) { try { return (ConcordionExtension) field.get(fixture); } catch (ClassCastException e) { throw new ExtensionInitialisationException("Extension field '" + field.getName() + "' must implement org.concordion.api.extension.ConcordionExtension"); } catch (IllegalArgumentException e) { throw new ExtensionInitialisationException("Defect - this exception should not occur. Please report to Concordion issues list.", e); } catch (IllegalAccessException e) { throw new ExtensionInitialisationException("Defect - this exception should not occur. Please report to Concordion issues list.", e); } } private void validatePublic(Field field) { if (!(Modifier.isPublic(field.getModifiers()))) { throw new ExtensionInitialisationException("Extension field '" + field.getName() + "' must be public"); } } private void validateNonNull(Field field, ConcordionExtension extension) { if (extension == null) { throw new ExtensionInitialisationException("Extension field '" + field.getName() + "' must be non-null"); } } }
46.273438
164
0.656086
b97adbbb11adf181f781af5a2e436dab58bfbd76
572
package de.samply.share.client.quality.report.file.excel.cell.reference; public class FirstRowCellReferenceFactoryForOneSheet extends FirstRowCellReferenceFactory { private final String sheetName; public FirstRowCellReferenceFactoryForOneSheet(String sheetName) { this.sheetName = sheetName; } /** * Creates an excel cell reference. * * @param columnOrdinal Number of column. * @return excel cell reference. */ public CellReference createCellReference(int columnOrdinal) { return createCellReference(sheetName, columnOrdinal); } }
24.869565
91
0.767483
8d9ff646c69b6fd63d637e4f1f50aca242fe78a7
1,190
package com.hubspot.singularity.api; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Optional; import com.wordnik.swagger.annotations.ApiModelProperty; public class SingularitySkipHealthchecksRequest extends SingularityExpiringRequestParent { private final Optional<Boolean> skipHealthchecks; @JsonCreator public SingularitySkipHealthchecksRequest(@JsonProperty("skipHealthchecks") Optional<Boolean> skipHealthchecks, @JsonProperty("durationMillis") Optional<Long> durationMillis, @JsonProperty("actionId") Optional<String> actionId, @JsonProperty("message") Optional<String> message) { super(durationMillis, actionId, message); this.skipHealthchecks = skipHealthchecks; } @ApiModelProperty(required=false, value="If set to true, healthchecks will be skipped for all tasks for this request until reversed") public Optional<Boolean> getSkipHealthchecks() { return skipHealthchecks; } @Override public String toString() { return "SingularitySkipHealthchecksRequest{" + "skipHealthchecks=" + skipHealthchecks + "} " + super.toString(); } }
38.387097
174
0.782353
ab333d0b58c9d6cd82df0618e560ab7a063b5bc5
1,489
import java.util.Arrays; /* * @lc app=leetcode id=345 lang=java * * [345] Reverse Vowels of a String * * https://leetcode.com/problems/reverse-vowels-of-a-string/description/ * * algorithms * Easy (45.79%) * Likes: 1166 * Dislikes: 1575 * Total Accepted: 294.9K * Total Submissions: 643.9K * Testcase Example: '"hello"' * * Given a string s, reverse only all the vowels in the string and return it. * * The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both * cases. * * * Example 1: * Input: s = "hello" * Output: "holle" * Example 2: * Input: s = "leetcode" * Output: "leotcede" * * * Constraints: * * * 1 <= s.length <= 3 * 10^5 * s consist of printable ASCII characters. * * */ // @lc code=start import java.util.HashSet; class Solution { private final static HashSet<Character> VOWELS = new HashSet<Character>( Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); public String reverseVowels(String s) { int i = 0, j = s.length() - 1; char[] result = new char[s.length()]; while (i <= j) { char first_v = s.charAt(i); char second_v = s.charAt(j); if (!VOWELS.contains(first_v)) { result[i] = first_v; i++; } else if (!VOWELS.contains(second_v)) { result[j] = second_v; j--; } else { result[i] = second_v; result[j] = first_v; i++; j--; } } return new String(result); } } // @lc code=end // 双指针法检测元音字母,然后交换 // 这种也要考虑i<=j的情况,因为都需要赋值
20.121622
77
0.587643
623a760058fa0635bbf91b3982583344f314ad6d
648
package com.reportserver.report.repository; import com.reportserver.report.model.Ristorante; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; /** * Repo ristorante */ public interface RistoranteRepository extends JpaRepository<Ristorante, Integer> { /** * Caricamento Ristoranti dentro un cantiere * * @param IdCantiere * @return */ @Query("FROM Ristorante where IdCantiere=:IdCantiere") List<Ristorante> findbycantiere(@Param("IdCantiere") int IdCantiere); }
28.173913
82
0.756173
865d233963713c9c6e59030a13f82c902f080aec
15,166
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.editors.schematic.figures; import java.util.List; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.ReportFigureUtilities; import org.eclipse.birt.report.designer.internal.ui.layout.ReportItemConstraint; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.FigureUtilities; import org.eclipse.draw2d.MarginBorder; import org.eclipse.draw2d.StackLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.draw2d.text.FlowBox; import org.eclipse.draw2d.text.FlowFigure; import org.eclipse.draw2d.text.FlowPage; import org.eclipse.draw2d.text.ParagraphTextLayout; import org.eclipse.swt.graphics.Font; import com.ibm.icu.text.BreakIterator; /** * A Figure with an embedded TextFlow within a FlowPage that contains text. * * */ public class LabelFigure extends ReportElementFigure { private static final Dimension ZERO_DIMENSION = new Dimension( ); private TextFlow label; private FlowPage flowPage; private String display; private Dimension recommendSize = new Dimension(); private boolean isFixLayout; /** * Creates a new LabelFigure with a default MarginBorder size 1 and a * FlowPage containing a TextFlow with the style WORD_WRAP_SOFT. */ public LabelFigure( ) { this( 1 ); } /** * @return */ public String getDisplay( ) { return display; } /** * Creates a new LabelFigure with a MarginBorder that is the given size and * a FlowPage containing a TextFlow with the style WORD_WRAP_HARD. * * @param borderSize * the size of the MarginBorder */ public LabelFigure( int borderSize ) { setBorder( new MarginBorder( borderSize ) ); label = new TextFlow( ) { public void postValidate( ) { if ( DesignChoiceConstants.DISPLAY_BLOCK.equals( display ) || DesignChoiceConstants.DISPLAY_INLINE.equals( display ) ) { List list = getFragments( ); FlowBox box; int left = Integer.MAX_VALUE, top = left; int bottom = Integer.MIN_VALUE; for ( int i = 0; i < list.size( ); i++ ) { box = (FlowBox) list.get( i ); left = Math.min( left, box.getX( ) ); top = Math.min( top, box.getBaseline( ) - box.getAscent( ) ); bottom = Math.max( bottom, box.getBaseline( ) + box.getDescent( ) ); } int width = LabelFigure.this.getClientArea( ).width; if (isFixLayout) { int maxWidth = calcMaxSegment( )-getInsets( ).getWidth( ); width = Math.max( width, maxWidth); } setBounds( new Rectangle( left, top, width, Math.max( LabelFigure.this.getClientArea( ).height, bottom - top ) ) ); if (isFixLayout( )) { Figure child = (Figure)getParent( ); Rectangle rect = child.getBounds( ); child.setBounds( new Rectangle(rect.x, rect.y, width, rect.height) ); } list = getChildren( ); for ( int i = 0; i < list.size( ); i++ ) { ( (FlowFigure) list.get( i ) ).postValidate( ); } } else { super.postValidate( ); } } }; label.setLayoutManager( new ParagraphTextLayout( label, ParagraphTextLayout.WORD_WRAP_SOFT ) ); flowPage = new FlowPage( ); flowPage.add( label ); setLayoutManager( new StackLayout( ) ); add( flowPage ); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.IFigure#getPreferredSize(int, int) */ private Dimension getPreferredSize( int wHint, int hHint, boolean isFix, boolean forceWidth, boolean forceHeight ) { int rx = recommendSize != null ? recommendSize.width : 0; int ry = recommendSize != null ? recommendSize.height : 0; rx = getRealRecommendSizeX( rx, wHint ); Dimension dim = null; if(isFix) { int tempHint = wHint; int maxWidth = calcMaxSegment( ); if (wHint < maxWidth && !forceWidth) { tempHint = maxWidth; } dim = super.getPreferredSize( tempHint <= 0 ? -1 : tempHint, hHint ); } // only when display is block, use passed in wHint else if ( DesignChoiceConstants.DISPLAY_BLOCK.equals( display ) ) { dim = super.getPreferredSize( rx == 0 ? wHint : rx, hHint ); } else { dim = super.getPreferredSize( rx == 0 ? -1 : rx, hHint ); //fix bug 271116. if (rx == 0 && wHint > 0 && dim.width > wHint) { dim = super.getPreferredSize( wHint, hHint ); } } return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height, ry ) ); } public Dimension getPreferredSize( int wHint, int hHint ) { return getPreferredSize( wHint, hHint, false , false, false); } public Dimension getMinimumSize( int wHint, int hHint ) { return getMinimumSize( wHint, hHint, false, false, false ); } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Figure#getMinimumSize(int, int) */ private Dimension getMinimumSize( int wHint, int hHint,boolean isFix, boolean forceWidth, boolean forceHeight ) { if ( DesignChoiceConstants.DISPLAY_NONE.equals( display ) ) { return ZERO_DIMENSION; } int rx = recommendSize != null ? recommendSize.width : 0; int ry = recommendSize != null ? recommendSize.height : 0; rx = getRealRecommendSizeX( rx, wHint ); if ( wHint == -1 && hHint == -1 ) { int maxWidth = calcMaxSegment( ); // use recommend size if specified, otherwise use max segment size Dimension dim = super.getMinimumSize( rx == 0 ? maxWidth : rx, -1 ); dim.height = Math.max( dim.height, Math.max( getInsets( ).getHeight( ), ry ) ); return dim; } Dimension dim; // return the true minimum size with minimum width; if(isFix) { int tempHint = wHint; int maxWidth = calcMaxSegment( ); if (wHint < maxWidth && !forceWidth) { tempHint = maxWidth; } dim = super.getMinimumSize( tempHint <= 0 ? -1 : tempHint, hHint ); return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height, ry ) ); } else { dim = super.getMinimumSize( rx == 0 ? -1 : rx, hHint ); } if ( dim.width < wHint ) { return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height, ry ) ); } dim = super.getMinimumSize( wHint, hHint ); return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height, ry ) ); } private int getRealRecommendSizeX( int rx, int wHint ) { if ( rx > 0 || wHint == -1 ) { return rx; } if ( getParent( ) != null && getParent( ).getLayoutManager( ) != null ) { ReportItemConstraint constraint = (ReportItemConstraint) getParent( ).getLayoutManager( ) .getConstraint( this ); if ( constraint != null && constraint.getMeasure( ) != 0 && DesignChoiceConstants.UNITS_PERCENTAGE.equals( constraint.getUnits( ) ) ) { // compute real percentag recommend size rx = (int) constraint.getMeasure( ) * wHint / 100;; } } return rx; } private int calcMaxSegment( ) { String text = label.getText( ); char[] chars = text.toCharArray( ); int position = 0; int maxWidth = 0; for ( int i = 0; i < chars.length; i++ ) { if ( canBreakAfter( chars[i] ) ) { int tempMaxWidth; String st = text.substring( position, i + 1 ); tempMaxWidth = FigureUtilities.getStringExtents( st, getFont( ) ).width; if ( tempMaxWidth > maxWidth ) { maxWidth = tempMaxWidth; } position = i; } } String st = text.substring( position, chars.length ); int tempMaxWidth = FigureUtilities.getStringExtents( st, getFont( ) ).width; if ( tempMaxWidth > maxWidth ) { maxWidth = tempMaxWidth; } return maxWidth + getInsets( ).getWidth( ) ; } static final BreakIterator LINE_BREAK = BreakIterator.getLineInstance( ); static boolean canBreakAfter( char c ) { boolean result = Character.isWhitespace( c ) || c == '-'; if ( !result && ( c < 'a' || c > 'z' ) ) { // chinese characters and such would be caught in here // LINE_BREAK is used here because INTERNAL_LINE_BREAK might be in // use LINE_BREAK.setText( c + "a" ); //$NON-NLS-1$ result = LINE_BREAK.isBoundary( 1 ); } return result; } private static int getMinimumFontSize( Font ft ) { if ( ft != null && ft.getFontData( ).length > 0 ) { return ft.getFontData( )[0].getHeight( ); } return 0; } /** * Since Eclipse TextFlow figure ignore the trailing /r/n for calculating * the client size, we must append the extra size ourselves. * * @return dimension for the client area used by the editor. */ public Rectangle getEditorArea( ) { Rectangle rect = getClientArea( ).getCopy( ); String s = getText( ); int count = 0; if ( s != null && s.length( ) > 1 ) { for ( int i = s.length( ) - 2; i >= 0; i -= 2 ) { if ( "\r\n".equals( s.substring( i, i + 2 ) ) ) //$NON-NLS-1$ { //count++; } else { break; } } } int hh = getMinimumFontSize( getFont( ) ); rect.height += count * hh + ( ( count == 0 ) ? 0 : ( hh / 2 ) ); return rect; } /** * Sets the recommended size. * * @param recommendSize */ public void setRecommendSize( Dimension recommendSize ) { this.recommendSize = recommendSize; } /**Gets the recommended size. * @return */ public Dimension getRecommendSize( ) { return recommendSize; } /** * Sets the display property of the Label. * * @param display * the display property. this should be one of the following: * DesignChoiceConstants.DISPLAY_BLOCK | * DesignChoiceConstants.DISPLAY_INLINE | * DesignChoiceConstants.DISPLAY_NONE */ public void setDisplay( String display ) { // if the display equals none, as the block if ( DesignChoiceConstants.DISPLAY_NONE.equals( display ) ) { this.display = DesignChoiceConstants.DISPLAY_BLOCK ; } else { this.display = display; } } /** * Returns the text inside the TextFlow. * * @return the text flow inside the text. */ public String getText( ) { return label.getText( ); } /** * Sets the text of the TextFlow to the given value. * * @param newText * the new text value. */ public void setText( String newText ) { if ( newText == null ) { newText = "";//$NON-NLS-1$ } label.setText( newText ); } /** * Sets the over-line style of the text. * * @param textOverline * The textOverline to set. */ public void setTextOverline( String textOverline ) { label.setTextOverline( textOverline ); } /** * Sets the line-through style of the text. * * @param textLineThrough * The textLineThrough to set. */ public void setTextLineThrough( String textLineThrough ) { label.setTextLineThrough( textLineThrough ); } /** * Sets the underline style of the text. * * @param textUnderline * The textUnderline to set. */ public void setTextUnderline( String textUnderline ) { label.setTextUnderline( textUnderline ); } /** * Sets the horizontal text alignment style. * * @param textAlign * The textAlign to set. */ public void setTextAlign( String textAlign ) { label.setTextAlign( textAlign ); } /** * Gets the horizontal text alignment style. * * @return The textAlign. */ public String getTextAlign( ) { return label.getTextAlign( ); } /** * Sets the vertical text alignment style. * * @param verticalAlign * The verticalAlign to set. */ public void setVerticalAlign( String verticalAlign ) { label.setVerticalAlign( verticalAlign ); } /** * Sets the toolTip text for this figure. * * @param toolTip */ public void setToolTipText( String toolTip ) { if ( toolTip != null ) { setToolTip( ReportFigureUtilities.createToolTipFigure( toolTip, this.getDirection( ), this.getTextAlign( ) ) ); } else { setToolTip( null ); } } /* * (non-Javadoc) * * @see org.eclipse.draw2d.Figure#setFont(org.eclipse.swt.graphics.Font) */ public void setFont( Font f ) { super.setFont( f ); label.setFont( f ); } /** * @param specialPREFIX */ public void setSpecialPREFIX( String specialPREFIX ) { label.setSpecialPREFIX( specialPREFIX ); } /** * Gets the direction property of the Label. * * @return the Label direction. * * @author bidi_hcg */ public String getDirection( ) { return label.getDirection( ); } /** * Sets the direction property of the Label. * * @param direction * the direction property. this should be one of the following: * DesignChoiceConstants.BIDI_DIRECTION_LTR | * DesignChoiceConstants.BIDI_DIRECTION_RTL * * @author bidi_hcg */ public void setDirection( String direction ) { label.setDirection( direction ); } @Override public Dimension getFixPreferredSize( int w, int h ) { int width = 0; int height = 0; if (recommendSize.width > 0) { width = recommendSize.width; } else { if (recommendSize.height > 0) { width = getPreferredSize( w, recommendSize.height, true, false, true).width; } else { width = getPreferredSize( w, h, true, false, false ).width; } } if (recommendSize.height > 0) { height = recommendSize.height; } else { if (recommendSize.width > 0) { int maxWidth = calcMaxSegment( ); height = getPreferredSize( Math.max( maxWidth, recommendSize.width ), h, true, true, false ).height; } else { height = getPreferredSize( w, h, true, false, false ).height; } } return new Dimension(width, height); } @Override public Dimension getFixMinimumSize( int w, int h ) { int width = 0; int height = 0; if (recommendSize.width > 0) { width = recommendSize.width; } else { if (recommendSize.height > 0) { width = getMinimumSize( w, recommendSize.height, true, false, true).width; } else { width = getMinimumSize( w, h, true, false, false ).width; } } if (recommendSize.height > 0) { height = recommendSize.height; } else { if (recommendSize.width > 0) { int maxWidth = calcMaxSegment( ); height = getMinimumSize( Math.max( maxWidth, recommendSize.width ), h, true, true, false ).height; } else { height = getMinimumSize( w, h, true, false, false ).height; } } return new Dimension(width, height); } public boolean isFixLayout( ) { return isFixLayout; } public void setFixLayout( boolean isFixLayout ) { this.isFixLayout = isFixLayout; } }
22.568452
115
0.632006
b745832be08b313c2a6a5504147e7bbfccc79c38
1,332
package com.self.innerclass; /** * 内部类 * @author Administrator * */ public class PublicClass { private String username; private String password; class PrivateClass{ private String age; private String address; public String getAge(){ return age; } public void setAge(String age){ this.age = age; } public String getAddress(){ return address; } public void setAddress(String address){ this.address = address; } public void printPublicProperty(){ System.out.println(username + " " +password); } } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public static void main(String[] args) { PublicClass publicClass = new PublicClass(); publicClass.setUsername("usernameValue"); publicClass.setPassword("passwordValue"); System.out.println(publicClass.getUsername() + " " + publicClass.getPassword()); PrivateClass privateClass = publicClass.new PrivateClass(); privateClass.setAge("ageValue"); privateClass.setAddress("addressValue"); System.out.println(privateClass.getAge() + " " + privateClass.getAddress()); } }
25.615385
83
0.689189
c25ecee22ccce9a69756db7158f5936ad059aa69
12,141
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.auth.RequestSigner; import com.amazonaws.opensdk.protect.auth.RequestSignerAware; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostMetricsRequest extends com.amazonaws.opensdk.BaseRequest implements Serializable, Cloneable, RequestSignerAware { private String aWSProduct; private String aWSProductVersion; private String clientID; private String oS; private String oSVersion; private String parentProduct; private String parentProductVersion; private java.util.List<MetricDatum> metricData; /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(String aWSProduct) { this.aWSProduct = aWSProduct; } /** * @return * @see AWSProduct */ public String getAWSProduct() { return this.aWSProduct; } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostMetricsRequest aWSProduct(String aWSProduct) { setAWSProduct(aWSProduct); return this; } /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(AWSProduct aWSProduct) { aWSProduct(aWSProduct); } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostMetricsRequest aWSProduct(AWSProduct aWSProduct) { this.aWSProduct = aWSProduct.toString(); return this; } /** * @param aWSProductVersion */ public void setAWSProductVersion(String aWSProductVersion) { this.aWSProductVersion = aWSProductVersion; } /** * @return */ public String getAWSProductVersion() { return this.aWSProductVersion; } /** * @param aWSProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest aWSProductVersion(String aWSProductVersion) { setAWSProductVersion(aWSProductVersion); return this; } /** * @param clientID */ public void setClientID(String clientID) { this.clientID = clientID; } /** * @return */ public String getClientID() { return this.clientID; } /** * @param clientID * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest clientID(String clientID) { setClientID(clientID); return this; } /** * @param oS */ public void setOS(String oS) { this.oS = oS; } /** * @return */ public String getOS() { return this.oS; } /** * @param oS * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest oS(String oS) { setOS(oS); return this; } /** * @param oSVersion */ public void setOSVersion(String oSVersion) { this.oSVersion = oSVersion; } /** * @return */ public String getOSVersion() { return this.oSVersion; } /** * @param oSVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest oSVersion(String oSVersion) { setOSVersion(oSVersion); return this; } /** * @param parentProduct */ public void setParentProduct(String parentProduct) { this.parentProduct = parentProduct; } /** * @return */ public String getParentProduct() { return this.parentProduct; } /** * @param parentProduct * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest parentProduct(String parentProduct) { setParentProduct(parentProduct); return this; } /** * @param parentProductVersion */ public void setParentProductVersion(String parentProductVersion) { this.parentProductVersion = parentProductVersion; } /** * @return */ public String getParentProductVersion() { return this.parentProductVersion; } /** * @param parentProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest parentProductVersion(String parentProductVersion) { setParentProductVersion(parentProductVersion); return this; } /** * @return */ public java.util.List<MetricDatum> getMetricData() { return metricData; } /** * @param metricData */ public void setMetricData(java.util.Collection<MetricDatum> metricData) { if (metricData == null) { this.metricData = null; return; } this.metricData = new java.util.ArrayList<MetricDatum>(metricData); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetricData(java.util.Collection)} or {@link #withMetricData(java.util.Collection)} if you want to * override the existing values. * </p> * * @param metricData * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest metricData(MetricDatum... metricData) { if (this.metricData == null) { setMetricData(new java.util.ArrayList<MetricDatum>(metricData.length)); } for (MetricDatum ele : metricData) { this.metricData.add(ele); } return this; } /** * @param metricData * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest metricData(java.util.Collection<MetricDatum> metricData) { setMetricData(metricData); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAWSProduct() != null) sb.append("AWSProduct: ").append(getAWSProduct()).append(","); if (getAWSProductVersion() != null) sb.append("AWSProductVersion: ").append(getAWSProductVersion()).append(","); if (getClientID() != null) sb.append("ClientID: ").append(getClientID()).append(","); if (getOS() != null) sb.append("OS: ").append(getOS()).append(","); if (getOSVersion() != null) sb.append("OSVersion: ").append(getOSVersion()).append(","); if (getParentProduct() != null) sb.append("ParentProduct: ").append(getParentProduct()).append(","); if (getParentProductVersion() != null) sb.append("ParentProductVersion: ").append(getParentProductVersion()).append(","); if (getMetricData() != null) sb.append("MetricData: ").append(getMetricData()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostMetricsRequest == false) return false; PostMetricsRequest other = (PostMetricsRequest) obj; if (other.getAWSProduct() == null ^ this.getAWSProduct() == null) return false; if (other.getAWSProduct() != null && other.getAWSProduct().equals(this.getAWSProduct()) == false) return false; if (other.getAWSProductVersion() == null ^ this.getAWSProductVersion() == null) return false; if (other.getAWSProductVersion() != null && other.getAWSProductVersion().equals(this.getAWSProductVersion()) == false) return false; if (other.getClientID() == null ^ this.getClientID() == null) return false; if (other.getClientID() != null && other.getClientID().equals(this.getClientID()) == false) return false; if (other.getOS() == null ^ this.getOS() == null) return false; if (other.getOS() != null && other.getOS().equals(this.getOS()) == false) return false; if (other.getOSVersion() == null ^ this.getOSVersion() == null) return false; if (other.getOSVersion() != null && other.getOSVersion().equals(this.getOSVersion()) == false) return false; if (other.getParentProduct() == null ^ this.getParentProduct() == null) return false; if (other.getParentProduct() != null && other.getParentProduct().equals(this.getParentProduct()) == false) return false; if (other.getParentProductVersion() == null ^ this.getParentProductVersion() == null) return false; if (other.getParentProductVersion() != null && other.getParentProductVersion().equals(this.getParentProductVersion()) == false) return false; if (other.getMetricData() == null ^ this.getMetricData() == null) return false; if (other.getMetricData() != null && other.getMetricData().equals(this.getMetricData()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAWSProduct() == null) ? 0 : getAWSProduct().hashCode()); hashCode = prime * hashCode + ((getAWSProductVersion() == null) ? 0 : getAWSProductVersion().hashCode()); hashCode = prime * hashCode + ((getClientID() == null) ? 0 : getClientID().hashCode()); hashCode = prime * hashCode + ((getOS() == null) ? 0 : getOS().hashCode()); hashCode = prime * hashCode + ((getOSVersion() == null) ? 0 : getOSVersion().hashCode()); hashCode = prime * hashCode + ((getParentProduct() == null) ? 0 : getParentProduct().hashCode()); hashCode = prime * hashCode + ((getParentProductVersion() == null) ? 0 : getParentProductVersion().hashCode()); hashCode = prime * hashCode + ((getMetricData() == null) ? 0 : getMetricData().hashCode()); return hashCode; } @Override public PostMetricsRequest clone() { return (PostMetricsRequest) super.clone(); } @Override public Class<? extends RequestSigner> signerType() { return com.amazonaws.opensdk.protect.auth.IamRequestSigner.class; } /** * Set the configuration for this request. * * @param sdkRequestConfig * Request configuration. * @return This object for method chaining. */ public PostMetricsRequest sdkRequestConfig(com.amazonaws.opensdk.SdkRequestConfig sdkRequestConfig) { super.sdkRequestConfig(sdkRequestConfig); return this; } }
29.397094
135
0.618895
970567405c88226fc9272b78a257fdb1faaa188b
25,907
package controllers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import org.apache.commons.lang3.StringEscapeUtils; import models.ClimateService; import models.Dataset; import models.ServiceConfigurationItem; import models.User; import play.Logger; import play.data.DynamicForm; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import utils.Constants; import utils.RESTfulCalls; import utils.RESTfulCalls.ResponseType; import views.html.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class ClimateServiceController extends Controller { final static Form<ClimateService> climateServiceForm = Form .form(ClimateService.class); public static Result addAClimateService() { return ok(registerAClimateService.render(climateServiceForm)); } public static Result showAllClimateServices() { List<ClimateService> climateServicesList = new ArrayList<ClimateService>(); JsonNode climateServicesNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_ALL_CLIMATE_SERVICES); // if no value is returned or error or is not json array if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) { return ok(allClimateServices.render(climateServicesList, climateServiceForm)); } // parse the json string into object for (int i = 0; i < climateServicesNode.size(); i++) { JsonNode json = climateServicesNode.path(i); ClimateService oneService = deserializeJsonToClimateService(json); climateServicesList.add(oneService); } return ok(allClimateServices.render(climateServicesList, climateServiceForm)); } public static Result addClimateService() { // Form<ClimateService> cs = climateServiceForm.bindFromRequest(); JsonNode json = request().body().asJson(); String name = json.path("name").asText(); String purpose = json.path("purpose").asText(); String url = json.path("url").asText(); String scenario = json.path("scenario").asText(); String versionNo = json.path("version").asText(); String rootServiceId = json.path("rootServiceId").asText(); JsonNode response = null; ObjectNode jsonData = Json.newObject(); try { String originalClimateServiceName = name; String newClimateServiceName = originalClimateServiceName.replace( ' ', '-'); // name should not contain spaces if (newClimateServiceName != null && !newClimateServiceName.isEmpty()) { jsonData.put("name", newClimateServiceName); } jsonData.put("creatorId", 1); // TODO, since we don't have // login/account id yet use a // default val jsonData.put("purpose", purpose); jsonData.put("url", url); DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz"); // get current date time with Date() Date date = new Date(); jsonData.put("createTime", dateFormat.format(date)); jsonData.put("scenario", scenario); jsonData.put("versionNo", versionNo); jsonData.put("rootServiceId", rootServiceId); // POST Climate Service JSON data response = RESTfulCalls.postAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.ADD_CLIMATE_SERVICE, jsonData); // flash the response message System.out.println("***************" + response); Application.flashMsg(response); } catch (IllegalStateException e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls .createResponse(ResponseType.CONVERSIONERROR)); } catch (Exception e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls .createResponse(ResponseType.UNKNOWN)); } return ok(response); } public static Result serviceModels() { JsonNode jsonData = request().body().asJson(); System.out.println("JSON data: " + jsonData); String url = jsonData.get("climateServiceCallUrl").toString(); System.out.println("JPL climate service model call url: " + url); // transfer JsonNode to Object ObjectNode object = (ObjectNode) jsonData; object.remove("climateServiceCallUrl"); System.out.println("JSON data after removing: " + (JsonNode) object); // from JsonNode to java String, always has "" quotes on the two sides JsonNode response = RESTfulCalls.postAPI( url.substring(1, url.length() - 1), (JsonNode) object); System.out.println("Response: " + response); // flash the response message Application.flashMsg(response); System.out .println(ok("Climate Service model has been called successfully!")); // return jsonData return ok(response); } // send dynamic page string public static Result passPageStr() { String str = request().body().asJson().get("pageString").toString(); String name = request().body().asJson().get("name").toString(); String purpose = request().body().asJson().get("purpose").toString(); String url = request().body().asJson().get("url").toString(); String outputButton = request().body().asJson().get("pageOutput") .toString(); String dataListContent = request().body().asJson() .get("dataListContent").toString(); System.out.println("page string: " + str); System.out.println("climate service name: " + name); ObjectNode jsonData = Json.newObject(); jsonData.put("pageString", str); // POST Climate Service JSON data to CMU 9020 backend // One copy in backend and one copy in frontend JsonNode response = RESTfulCalls.postAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.SAVE_CLIMATE_SERVICE_PAGE, jsonData); System.out.println("WARNING!!!!!!"); // save page in front-end savePage(str, name, purpose, url, outputButton, dataListContent); // flash the response message Application.flashMsg(response); return ok("Climate Service Page has been saved succussfully!"); } public static Result ruleEngineData() { JsonNode result = request().body().asJson(); // System.out.println("ticking!"); System.out.println(result); return ok("good"); } public static Result addAllParameters() { JsonNode result = request().body().asJson(); System.out.println(result); System.out.println("--------------------------"); Iterator<JsonNode> ite = result.iterator(); while (ite.hasNext()) { JsonNode tmp = ite.next(); System.out.println(tmp); JsonNode response = RESTfulCalls.postAPI( Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.ADD_ALL_PARAMETERS, tmp); System.out.println("=========" + response); } return ok("good"); } public static void savePage(String str, String name, String purpose, String url, String outputButton, String dataListContent) { System.out.println("output button test: " + outputButton); // Remove delete button from preview page String result = str .replaceAll( "<td><button type=\\\\\"button\\\\\" class=\\\\\"btn btn-danger\\\\\" onclick=\\\\\"Javascript:deleteRow\\(this,\\d+\\)\\\\\">delete</button></td>", ""); dataListContent = StringEscapeUtils.unescapeJava(dataListContent); result = StringEscapeUtils.unescapeJava(result); outputButton = StringEscapeUtils.unescapeJava(outputButton); System.out.println("output button test: " + outputButton); // remove the first char " and the last char " of result, name and // purpose dataListContent = dataListContent.substring(1, dataListContent.length() - 1); result = result.substring(1, result.length() - 1); outputButton = outputButton.substring(1, outputButton.length() - 1); name = name.substring(1, name.length() - 1); purpose = purpose.substring(1, purpose.length() - 1); String putVarAndDataList = Constants.putVar + dataListContent; System.out.println("putVarAndDataList: " + putVarAndDataList); String str11 = Constants.htmlHead1; // System.out.println("head1: " + str11); String str12 = Constants.htmlHead2; // System.out.println("head2: " + str12); String str13 = Constants.htmlHead3; // System.out.println("head3: " + str13); String str14 = Constants.htmlHead4; String str21 = Constants.htmlTail1; String str22 = Constants.htmlTail2; String str23 = Constants.htmlTail3; result = str11 + putVarAndDataList + str12 + name + str13 + purpose + str14 + result + str21 + url.substring(1, url.length() - 1) + str22 + outputButton + str23; name = name.replace(" ", ""); // Java file name cannot start with number and chars like '_' '-'... String location = "public/html/" + "service" + name.substring(0, 1).toUpperCase() + name.substring(1) + ".html"; File theDir = new File("public/html"); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: public/html"); boolean create = false; try { theDir.mkdir(); create = true; } catch (SecurityException se) { // handle it } if (create) { System.out.println("DIR created"); } } try { File file = new File(location); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(result); output.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void flashMsg(JsonNode jsonNode) { Iterator<Entry<String, JsonNode>> it = jsonNode.fields(); while (it.hasNext()) { Entry<String, JsonNode> field = it.next(); flash(field.getKey(), field.getValue().asText()); } } public static Result mostRecentlyAddedClimateServices() { List<ClimateService> climateServices = new ArrayList<ClimateService>(); JsonNode climateServicesNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_MOST_RECENTLY_ADDED_CLIMATE_SERVICES_CALL); // if no value is returned or error or is not json array if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) { return ok(mostRecentlyUsedServices.render(climateServices)); } // parse the json string into object for (int i = 0; i < climateServicesNode.size(); i++) { JsonNode json = climateServicesNode.path(i); ClimateService newService = deserializeJsonToClimateService(json); climateServices.add(newService); } return ok(mostRecentlyAddedServices.render(climateServices)); } public static Result mostPopularServices() { List<ClimateService> climateServices = new ArrayList<ClimateService>(); JsonNode climateServicesNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_MOST_POPULAR_CLIMATE_SERVICES_CALL); // if no value is returned or error or is not json array if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) { return ok(mostPopularServices.render(climateServices)); } // parse the json string into object for (int i = 0; i < climateServicesNode.size(); i++) { JsonNode json = climateServicesNode.path(i); ClimateService newService = deserializeJsonToClimateService(json); climateServices.add(newService); } return ok(mostPopularServices.render(climateServices)); } public static Result getUserByEmail() { JsonNode result = request().body().asJson(); String email = result.get("email").toString(); email = email.substring(1, email.length()-1); ObjectMapper mapper = new ObjectMapper(); ObjectNode queryJson = mapper.createObjectNode(); queryJson.put("email", email); System.out.println("SEE getUserByEmail: " + queryJson); JsonNode userIdNode = RESTfulCalls.postAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_USER_BY_EMAIL, queryJson); // parse the json string into object String id = userIdNode.findPath("id").asText(); System.out.println("SEE getUserByEmail ID: " + id); return ok(id); } public static Result getServiceByKeyword() { System.out.println("xxxx"); JsonNode result = request().body().asJson(); System.out.println(result); String userId = result.get("userId").toString(); userId = userId.substring(1,userId.length()-1); String url = "http://einstein.sv.cmu.edu:9043/getTopKUserBasedCFRecommendedServiceByUsername?username="+userId+"&top_num=5"; JsonNode serviceNode = RESTfulCalls.getAPI(url); // parse the json string into object String res = ""; for (int i = 0; i < serviceNode.size(); i++) { JsonNode json = serviceNode.path(i); String serviceName = json.findPath("dataset").asText(); res += serviceName + "!"; } System.out.println("SEE getUserByEmail ID: " + res); return ok(res); } public static Result recommendationSummary(String userId, int id, String keyword) { keyword = keyword.replaceAll(" ", "%20"); List<String> userBasedDataset = new ArrayList<String>(); List<String> itemBasedDataset = new ArrayList<String>(); List<String> featureBasedDataset = new ArrayList<String>(); List<String> userBasedDatasetHybrid = new ArrayList<String>(); List<ClimateService> climateServices = new ArrayList<ClimateService>(); List<Dataset> dataSetsList = new ArrayList<Dataset>(); List<User> usersList = new ArrayList<User>(); List<User> userSimilarList = new ArrayList<User>(); JsonNode usersNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_ALL_USERS); JsonNode usersSimilarNode = RESTfulCalls.getAPI(Constants.URL_SERVER + Constants.CMU_BACKEND_PORT + Constants.GET_TOP_K_SIMILAR_USERS + id + "/k/" + "12" + "/json"); // if no value is returned or error or is not json array if (usersNode == null || usersNode.has("error") || !usersNode.isArray()) { return ok(recommendationSummary.render(climateServices, dataSetsList, usersList, userBasedDataset, featureBasedDataset, itemBasedDataset, userId, userSimilarList, userBasedDatasetHybrid, keyword)); } JsonNode climateServicesNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_MOST_POPULAR_CLIMATE_SERVICES_CALL); // if no value is returned or error or is not json array if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) { return ok(recommendationSummary.render(climateServices, dataSetsList, usersList, userBasedDataset, featureBasedDataset, itemBasedDataset, userId, userSimilarList, userBasedDatasetHybrid, keyword)); } // parse the json string into object for (int i = 0; i < climateServicesNode.size(); i++) { JsonNode json = climateServicesNode.path(i); ClimateService newService = deserializeJsonToClimateService(json); climateServices.add(newService); } // parse the json string into object for (int i = 0; i < usersNode.size(); i++) { JsonNode json = usersNode.path(i); User oneUser = new User(); oneUser.setId(json.findPath("id").asLong()); oneUser.setUserName(json.findPath("userName").asText()); oneUser.setPassword(json.findPath("password").asText()); oneUser.setFirstName(json.findPath("firstName").asText()); oneUser.setMiddleInitial(json.findPath("middleInitial").asText()); oneUser.setLastName(json.findPath("lastName").asText()); oneUser.setAffiliation(json.findPath("affiliation").asText()); oneUser.setEmail(json.findPath("email").asText()); oneUser.setResearchFields(json.findPath("researchFields").asText()); usersList.add(oneUser); } for (int i = 0; i < usersSimilarNode.size(); i++) { JsonNode json = usersSimilarNode.path(i); User oneUser = new User(); oneUser.setId(json.findPath("id").asLong()); oneUser.setUserName(json.findPath("userName").asText()); oneUser.setPassword(json.findPath("password").asText()); oneUser.setFirstName(json.findPath("firstName").asText()); oneUser.setMiddleInitial(json.findPath("middleInitial").asText()); oneUser.setLastName(json.findPath("lastName").asText()); oneUser.setAffiliation(json.findPath("affiliation").asText()); oneUser.setEmail(json.findPath("email").asText()); oneUser.setResearchFields(json.findPath("researchFields").asText()); userSimilarList.add(oneUser); } int k = Integer.MAX_VALUE; // Set the first popular K datasets dataSetsList = DatasetController.queryFirstKDatasetsWithoutClimateService("", "", "", "", "", new Date(0), new Date(), k); JsonNode userBased = RESTfulCalls.getAPI(Constants.URL_SERVER + Constants.URL_FLASK + Constants.GET_TOP_K_USER_BASED_DATASET1 + userId + Constants.GET_TOP_K_USER_BASED_DATASET2 + 10); for (int i = 0; i<userBased.size(); i++) { userBasedDataset.add(userBased.path(i).findValue("dataset").toString()); } JsonNode userBasedHybrid = RESTfulCalls.getAPI(Constants.URL_SERVER + Constants.URL_FLASK + Constants.GET_TOP_K_USER_BASED_DATASET_HYBRID1 + userId + Constants.GET_TOP_K_USER_BASED_DATASET_HYBRID2 + 10 + Constants.GET_TOP_K_USER_BASED_DATASET_HYBRID3 + keyword); if (userBasedHybrid == null || userBasedHybrid.has("error") || !userBasedHybrid.isArray()) { return ok(recommendationSummary.render(climateServices, dataSetsList, usersList, userBasedDataset, featureBasedDataset, itemBasedDataset, userId, userSimilarList, userBasedDatasetHybrid, "No related topic with '" + keyword + "'!")); } for (int i = 0; i<userBasedHybrid.size(); i++) { userBasedDatasetHybrid.add(userBasedHybrid.path(i).findValue("dataset").toString()); } JsonNode itemBased = RESTfulCalls.getAPI(Constants.URL_SERVER + Constants.URL_FLASK + Constants.GET_TOP_K_ITEM_BASED_DATASET1 + userId + Constants.GET_TOP_K_ITEM_BASED_DATASET2 + 10); for (int i = 0; i<itemBased.size(); i++) { itemBasedDataset.add(itemBased.path(i).findValue("dataset").toString()); } JsonNode featureBased = RESTfulCalls.getAPI(Constants.URL_SERVER + Constants.URL_FLASK + Constants.GET_TOP_K_FEATURE_BASED_DATASET1 + userId + Constants.GET_TOP_K_FEATURE_BASED_DATASET2 + 10); for (int i = 0; i<featureBased.size(); i++) { featureBasedDataset.add(featureBased.path(i).findValue("dataset").toString()); } System.out.println("--------------------------"); System.out.println(userId); // JsonNode test = userBased.path(0); // System.out.println(test.findValue("dataset")); System.out.println(userBasedDataset); System.out.println("--------------------------Beeping"); return ok(recommendationSummary.render(climateServices, dataSetsList, usersList, userBasedDataset, featureBasedDataset, itemBasedDataset, userId, userSimilarList, userBasedDatasetHybrid, keyword)); } public static Result mostRecentlyUsedClimateServices() { List<ClimateService> climateServices = new ArrayList<ClimateService>(); JsonNode climateServicesNode = RESTfulCalls.getAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.GET_MOST_RECENTLY_USED_CLIMATE_SERVICES_CALL); // if no value is returned or error or is not json array if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) { return ok(mostRecentlyUsedServices.render(climateServices)); } // parse the json string into object for (int i = 0; i < climateServicesNode.size(); i++) { JsonNode json = climateServicesNode.path(i); ClimateService newService = deserializeJsonToClimateService(json); climateServices.add(newService); } return ok(mostRecentlyUsedServices.render(climateServices)); } public static Result replaceFile() { File result = request().body().asRaw().asFile(); System.out.println("result: " + request().body().asRaw().asFile()); // String content = readFile(result.getName(), StandardCharsets.UTF_8); System.out.println("result body: " + result.toString()); String line = ""; try { BufferedReader br = new BufferedReader(new FileReader( result.getAbsolutePath())); StringBuilder sb = new StringBuilder(); line = br.readLine(); //int count = 0; String fileNameLine = "<h2 class=\"text-center\">"; while (line != null ) { sb.append(line); sb.append("\n"); line = br.readLine(); // if (line.length() > 23) // System.out.println("pair1" + line.substring(0, 24)); // System.out.println("pair2" + fileNameLine); if (line.length()>= 24 && line.substring(0, 24).equals(fileNameLine)) break; //count++; } br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TEMPOARY SOLUTION : get the fileName from the html page System.out.println("original Name" + line); String tempName = line.substring(24, line.length() - 5); String fileName = "public/html/service" + tempName.substring(0, 1).toUpperCase() + tempName.substring(1) + ".html"; System.out.println("fileName: " + fileName); // replace the page in the frontend Server try { Path newPath = Paths.get(fileName); Files.move(result.toPath(), newPath, REPLACE_EXISTING); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // executeReplace(result); return ok("File uploaded"); } public static void executeReplace(String result) { try { String path = "public/html/se.html"; File theDir = new File("public/html"); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: public/html"); boolean create = false; try { theDir.mkdir(); create = true; } catch (SecurityException se) { // handle it } if (create) { System.out.println("DIR created"); } } File file = new File(path); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(result); output.close(); System.out.println("Beeping!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static ClimateService deserializeJsonToClimateService(JsonNode json) { ClimateService oneService = new ClimateService(); oneService.setName(json.path("name").asText()); oneService.setPurpose(json.path("purpose").asText()); // URL here is the dynamic page url String name = json.path("name").asText(); String url = json.path("url").asText(); // Parse NASA URL if (url.contains("/cmac/web") || name.length() == 0 || name == null) { oneService.setUrl(url); } else { String pageUrl = Constants.URL_SERVER + Constants.LOCAL_HOST_PORT + "/assets/html/service" + name.substring(0, 1).toUpperCase() + name.substring(1) + ".html"; oneService.setUrl(pageUrl); } // newService.setCreateTime(json.path("createTime").asText()); oneService.setScenario(json.path("scenario").asText()); oneService.setVersionNo(json.path("versionNo").asText()); oneService.setRootServiceId(json.path("rootServiceId").asLong()); oneService.setImageURL(); return oneService; } // Get all climate Services public static Result searchClimateServices() { return ok(searchClimateService.render(climateServiceForm)); } public static Result getSearchResult(){ Form<ClimateService> cs = climateServiceForm.bindFromRequest(); ObjectNode jsonData = Json.newObject(); String name = ""; String purpose = ""; String scenario = ""; String url = ""; String versionNo = ""; try { name = cs.field("Climate Service Name").value(); purpose = cs.field("Purpose").value(); url = cs.field("Url").value(); scenario = cs.field("Scenario").value(); versionNo = cs.field("Version Number").value(); } catch (IllegalStateException e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls .createResponse(ResponseType.CONVERSIONERROR)); } catch (Exception e) { e.printStackTrace(); Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN)); } List<ClimateService> response = queryClimateService(name, purpose, url, scenario, versionNo); return ok(climateServiceList.render(response)); } public static List<ClimateService> queryClimateService(String name, String purpose, String url, String scenario, String versionNo) { List<ClimateService> climateService = new ArrayList<ClimateService>(); ObjectMapper mapper = new ObjectMapper(); ObjectNode queryJson = mapper.createObjectNode(); queryJson.put("name", name); queryJson.put("purpose", purpose); queryJson.put("url", url); queryJson.put("scenario", scenario); queryJson.put("versionNo", versionNo); JsonNode climateServiceNode = RESTfulCalls.postAPI(Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.QUERY_CLIMATE_SERVICE, queryJson); // parse the json string into object for (int i = 0; i < climateServiceNode.size(); i++) { JsonNode json = climateServiceNode.path(i); ClimateService newClimateService = deserializeJsonToClimateService(json); climateService.add(newClimateService); } return climateService; } }
34.088158
235
0.712356
f441c2ec17fa0f879c6c262944d4ad9a84b3999c
1,583
package dev.lankydan.flink.twitter.functions; import dev.lankydan.flink.twitter.data.RecentTweet; import dev.lankydan.flink.twitter.data.StreamedTweet; import dev.lankydan.flink.twitter.json.EnrichedTweet; import dev.lankydan.flink.twitter.json.EnrichedTweetData; import dev.lankydan.flink.twitter.json.Mention; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class MapToRecentTweets implements MapFunction<Tuple2<StreamedTweet, EnrichedTweet>, Tuple2<StreamedTweet, List<RecentTweet>>> { @Override public Tuple2<StreamedTweet, List<RecentTweet>> map(Tuple2<StreamedTweet, EnrichedTweet> value) { List<EnrichedTweetData> recentTweetData = value.f1.getData(); // filters out recent results that include no tweets if (recentTweetData == null) { return new Tuple2<>(value.f0, Collections.emptyList()); } return Tuple2.of( value.f0, value.f1.getData().stream().map(this::toRecentTweet).collect(Collectors.toList()) ); } private RecentTweet toRecentTweet(EnrichedTweetData data) { if (data.getEntities() == null || data.getEntities().getMentions() == null) { return new RecentTweet(data, Set.of()); } return new RecentTweet( data, data.getEntities().getMentions().stream().map(Mention::getUsername).collect(Collectors.toSet()) ); } }
36.813953
135
0.704359
e38219f1fc8cd4dbe139e760e87f64173d383ee7
3,445
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.format.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that a field or method parameter should be formatted as a number. * * <p>Supports formatting by style or custom pattern string. Can be applied * to any JDK {@code Number} type such as {@code Double} and {@code Long}. * * <p>For style-based formatting, set the {@link #style} attribute to be the * desired {@link Style}. For custom formatting, set the {@link #pattern} * attribute to be the number pattern, such as {@code #, ###.##}. * * <p>Each attribute is mutually exclusive, so only set one attribute per * annotation instance (the one most convenient one for your formatting needs). * When the {@link #pattern} attribute is specified, it takes precedence over * the {@link #style} attribute. When no annotation attributes are specified, * the default format applied is style-based for either number of currency, * depending on the annotated field or method parameter type. * * @author Keith Donald * @author Juergen Hoeller * @see java.text.NumberFormat * @since 3.0 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) public @interface NumberFormat { /** * The style pattern to use to format the field. * <p>Defaults to {@link Style#DEFAULT} for general-purpose number formatting * for most annotated types, except for money types which default to currency * formatting. Set this attribute when you wish to format your field in * accordance with a common style other than the default style. */ Style style() default Style.DEFAULT; /** * The custom pattern to use to format the field. * <p>Defaults to empty String, indicating no custom pattern String has been specified. * Set this attribute when you wish to format your field in accordance with a * custom number pattern not represented by a style. */ String pattern() default ""; /** * Common number format styles. */ enum Style { /** * The default format for the annotated type: typically 'number' but possibly * 'currency' for a money type (e.g. {@code javax.money.MonetaryAmount)}. * * @since 4.2 */ DEFAULT, /** * The general-purpose number format for the current locale. */ NUMBER, /** * The percent format for the current locale. */ PERCENT, /** * The currency format for the current locale. */ CURRENCY } }
34.45
100
0.689115
3b3e6b5586b0d50e3d7bead45d09e084da3938ba
404
package com.grokonez.jwtauthentication.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @AllArgsConstructor @NoArgsConstructor @Data public class Rented { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private User user; @ManyToOne private Car car; }
15.538462
55
0.752475
31ad56dbe4fa89dc1176e20e2a89eb44f4def996
1,103
package com.bluecodeltd.ecap.chw.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import com.bluecodeltd.ecap.chw.contract.ListContract; import com.bluecodeltd.ecap.chw.viewholder.ListableViewHolder; import com.bluecodeltd.ecap.chw.viewholder.MyCommunityActivityDetailsViewHolder; import com.bluecodeltd.ecap.chw.R; import com.bluecodeltd.ecap.chw.domain.EligibleChild; import java.util.List; public class MyCommunityActivityDetailsAdapter extends ListableAdapter<EligibleChild, ListableViewHolder<EligibleChild>> { public MyCommunityActivityDetailsAdapter(List<EligibleChild> items, ListContract.View<EligibleChild> view) { super(items, view); } @NonNull @Override public ListableViewHolder<EligibleChild> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_community_activity_details_fragment_item, parent, false); return new MyCommunityActivityDetailsViewHolder(view); } }
36.766667
138
0.807797
0878d5fd05807c3fb9d771b34ab1321837b40259
4,794
package com.ruoyi.system.service.impl; import java.util.List; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.exception.CustomException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; import javafx.scene.control.ListViewBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.system.mapper.SysAssetMapper; import com.ruoyi.system.domain.SysAsset; import com.ruoyi.system.service.ISysAssetService; /** * 车辆信息Service业务层处理 * * @author d * @date 2020-10-16 */ @Service public class SysAssetServiceImpl implements ISysAssetService { @Autowired private SysAssetMapper sysAssetMapper; private static final Logger log = LoggerFactory.getLogger(SysAssetServiceImpl.class); /** * 查询车辆信息 * * @param id 车辆信息ID * @return 车辆信息 */ @Override public SysAsset selectSysAssetById(Long id) { return sysAssetMapper.selectSysAssetById(id); } /** * 查询车辆信息列表 * * @param sysAsset 车辆信息 * @return 车辆信息 */ @Override public List<SysAsset> selectSysAssetList(SysAsset sysAsset) { return sysAssetMapper.selectSysAssetList(sysAsset); } /** * 新增车辆信息 * * @param sysAsset 车辆信息 * @return 结果 */ @Override public int insertSysAsset(SysAsset sysAsset) { sysAsset.setCreateTime(DateUtils.getNowDate()); return sysAssetMapper.insertSysAsset(sysAsset); } /** * 修改车辆信息 * * @param sysAsset 车辆信息 * @return 结果 */ @Override public int updateSysAsset(SysAsset sysAsset) { sysAsset.setUpdateTime(DateUtils.getNowDate()); return sysAssetMapper.updateSysAsset(sysAsset); } /** * 批量删除车辆信息 * * @param ids 需要删除的车辆信息ID * @return 结果 */ @Override public int deleteSysAssetByIds(Long[] ids) { return sysAssetMapper.deleteSysAssetByIds(ids); } /** * 删除车辆信息信息 * * @param id 车辆信息ID * @return 结果 */ @Override public int deleteSysAssetById(Long id) { return sysAssetMapper.deleteSysAssetById(id); } @Override public int addMysqlList(List<SysAsset> assets) { for(SysAsset asset:assets){ if(asset.getCreateTime() == null){ asset.setCreateTime(DateUtils.getNowDate()); } } return sysAssetMapper.addListMysql(assets); } @Override public String importData(List<SysAsset> assetList, boolean isUpdateSupport, String operName) { if (StringUtils.isNull(assetList) || assetList.size() == 0) { throw new CustomException("导入数据不能为空!"); } int successNum = 0; int failureNum = 0; StringBuilder successMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder(); // String password = configService.selectConfigByKey("sys.user.initPassword"); for (SysAsset asset : assetList) { try { // 验证是否存在这个用户 SysAsset a = sysAssetMapper.selectSysAssetById(asset.getId()); if (StringUtils.isNull(a)) { asset.setCreateBy(operName); this.insertSysAsset(asset); successNum++; successMsg.append("<br/>" + successNum + "、汽车 " + asset.getName() + " 导入成功"); } else if (isUpdateSupport) { asset.setUpdateBy(operName); this.updateSysAsset(asset); successNum++; successMsg.append("<br/>" + successNum + "、汽车 " + asset.getName() + " 更新成功"); } else { failureNum++; failureMsg.append("<br/>" + failureNum + "、汽车 " + asset.getName() + " 已存在"); } } catch (Exception e) { failureNum++; String msg = "<br/>" + failureNum + "、汽车 " + asset.getName() + " 导入失败:"; failureMsg.append(msg + e.getMessage()); log.error(msg, e); } } if (failureNum > 0) { failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); throw new CustomException(failureMsg.toString()); } else { successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); } return successMsg.toString(); } }
27.394286
98
0.570922
391c08fcf3c92a9b4f419a2ea4ea07e8222ac58b
837
package com.mtr.psn.service.orders; import java.util.List; import com.mtr.psn.model.orders.ComplaintForm; import com.mtr.psn.model.orders.QueryComplaintForm; public interface ComplaintFormService { public ComplaintForm selectById(Long id)throws Exception; public List<ComplaintForm> selectAll(ComplaintForm complaintForm)throws Exception; public List<ComplaintForm> selectMoneyByRider(QueryComplaintForm complaintForm)throws Exception; public int Count(QueryComplaintForm appealform)throws Exception; public List<ComplaintForm> selectComplaintFormList(QueryComplaintForm appealform)throws Exception; public int psn_insert(ComplaintForm complaintForm)throws Exception; public int psn_update(ComplaintForm complaintForm)throws Exception; public int psn_delete(ComplaintForm complaintForm)throws Exception; }
28.862069
99
0.837515
bf5acda949521636e6dde22376959772271ec667
1,098
import java.util.Scanner; import java.util.Arrays; public class exe2 { public static void main(String[] args) { /*2) em um vetor de numeros foi digitado a altura de 50 pessoas. Ao final imprima o vetor em ordem crescente.*/ Scanner ler = new Scanner (System.in); int i = 0; int j=0; int aux=0; int [] numeros = new int[5]; for (i=0; i<5; i++) { System.out.println("Digite a altura do usuario"+(1+i)+": "); numeros[i] = ler.nextInt(); } //processamento for (i=0; i<5; i++) { for (j=0; j<4; j++) { if (numeros[j]>numeros[j+1]){ aux=numeros[j]; numeros[j] = numeros[j+1]; numeros[j+1] = aux; } } } //impressao for (i=0; i<5; i++) { System.out.println("\n O valor: "+(1+i)+" : "+ numeros[i]); numeros[i] = ler.nextInt(); }}}
29.675676
75
0.413479
d72f127b44245db53a5d4f4619084899aff1babc
282
public class StackTest { public static void main(String args[]) { Stack1 st = new Stack1(); st.push("q"); st.push("a"); st.push("b"); System.out.println(st.pop()); System.out.println(st.peek()); System.out.println(st.pop()); System.out.println(st.pop()); } }
17.625
41
0.613475
259ef6ee66df00a2b7ffe89a9a0ce33033a987bb
1,269
package org.atomnuke.atom.model.builder; import org.atomnuke.atom.model.Source; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import static org.junit.Assert.*; import static org.atomnuke.atom.model.ModelTestUtil.*; /** * * @author zinic */ @RunWith(Enclosed.class) public class SourceBuilderTest { public static class WhenCopyingSourceObjects { @Test public void shouldCopyEmpty() { final SourceBuilder builder = new SourceBuilder(new SourceImpl()); final Source copy = builder.build(); assertNull(copy.base()); assertNull(copy.generator()); assertNull(copy.icon()); assertNull(copy.id()); assertNull(copy.logo()); assertNull(copy.rights()); assertNull(copy.subtitle()); assertNull(copy.title()); assertNull(copy.updated()); assertTrue(copy.authors().isEmpty()); assertTrue(copy.categories().isEmpty()); assertTrue(copy.links().isEmpty()); } @Test public void shouldCopy() { final Source original = newSource(); final Source copy = new SourceBuilder(original).build(); assertEquals(copy, original); } } }
26.4375
75
0.640662
be4102b5a3670a9b46f8cbfbc3d72e7813d789ad
1,176
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * */ package org.artifactory.security.mission.control; import org.artifactory.security.SimpleUser; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import java.util.Collection; /** * @author Gidi Shabat */ public class MissionControlAuthenticationToken extends UsernamePasswordAuthenticationToken { public MissionControlAuthenticationToken(SimpleUser principal, Collection<? extends GrantedAuthority> authorities) { super(principal, "", authorities); } }
37.935484
120
0.784864
a50b5cca15566399d90a60f008ed865bc2432b79
81,972
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: addsvc.proto package addsvc; public final class Addsvc { private Addsvc() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface SumRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:addsvc.SumRequest) com.google.protobuf.MessageOrBuilder { /** * <code>int64 a = 1;</code> */ long getA(); /** * <code>int64 b = 2;</code> */ long getB(); } /** * <pre> * The sum request contains two parameters. * </pre> * * Protobuf type {@code addsvc.SumRequest} */ public static final class SumRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:addsvc.SumRequest) SumRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SumRequest.newBuilder() to construct. private SumRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SumRequest() { a_ = 0L; b_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SumRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { a_ = input.readInt64(); break; } case 16: { b_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_SumRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_SumRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.SumRequest.class, addsvc.Addsvc.SumRequest.Builder.class); } public static final int A_FIELD_NUMBER = 1; private long a_; /** * <code>int64 a = 1;</code> */ public long getA() { return a_; } public static final int B_FIELD_NUMBER = 2; private long b_; /** * <code>int64 b = 2;</code> */ public long getB() { return b_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (a_ != 0L) { output.writeInt64(1, a_); } if (b_ != 0L) { output.writeInt64(2, b_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (a_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, a_); } if (b_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, b_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof addsvc.Addsvc.SumRequest)) { return super.equals(obj); } addsvc.Addsvc.SumRequest other = (addsvc.Addsvc.SumRequest) obj; boolean result = true; result = result && (getA() == other.getA()); result = result && (getB() == other.getB()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + A_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getA()); hash = (37 * hash) + B_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getB()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static addsvc.Addsvc.SumRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.SumRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.SumRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static addsvc.Addsvc.SumRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.SumRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.SumRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(addsvc.Addsvc.SumRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The sum request contains two parameters. * </pre> * * Protobuf type {@code addsvc.SumRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:addsvc.SumRequest) addsvc.Addsvc.SumRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_SumRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_SumRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.SumRequest.class, addsvc.Addsvc.SumRequest.Builder.class); } // Construct using addsvc.Addsvc.SumRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); a_ = 0L; b_ = 0L; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return addsvc.Addsvc.internal_static_addsvc_SumRequest_descriptor; } public addsvc.Addsvc.SumRequest getDefaultInstanceForType() { return addsvc.Addsvc.SumRequest.getDefaultInstance(); } public addsvc.Addsvc.SumRequest build() { addsvc.Addsvc.SumRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public addsvc.Addsvc.SumRequest buildPartial() { addsvc.Addsvc.SumRequest result = new addsvc.Addsvc.SumRequest(this); result.a_ = a_; result.b_ = b_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof addsvc.Addsvc.SumRequest) { return mergeFrom((addsvc.Addsvc.SumRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(addsvc.Addsvc.SumRequest other) { if (other == addsvc.Addsvc.SumRequest.getDefaultInstance()) return this; if (other.getA() != 0L) { setA(other.getA()); } if (other.getB() != 0L) { setB(other.getB()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { addsvc.Addsvc.SumRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (addsvc.Addsvc.SumRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long a_ ; /** * <code>int64 a = 1;</code> */ public long getA() { return a_; } /** * <code>int64 a = 1;</code> */ public Builder setA(long value) { a_ = value; onChanged(); return this; } /** * <code>int64 a = 1;</code> */ public Builder clearA() { a_ = 0L; onChanged(); return this; } private long b_ ; /** * <code>int64 b = 2;</code> */ public long getB() { return b_; } /** * <code>int64 b = 2;</code> */ public Builder setB(long value) { b_ = value; onChanged(); return this; } /** * <code>int64 b = 2;</code> */ public Builder clearB() { b_ = 0L; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:addsvc.SumRequest) } // @@protoc_insertion_point(class_scope:addsvc.SumRequest) private static final addsvc.Addsvc.SumRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new addsvc.Addsvc.SumRequest(); } public static addsvc.Addsvc.SumRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SumRequest> PARSER = new com.google.protobuf.AbstractParser<SumRequest>() { public SumRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SumRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SumRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SumRequest> getParserForType() { return PARSER; } public addsvc.Addsvc.SumRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SumReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:addsvc.SumReply) com.google.protobuf.MessageOrBuilder { /** * <code>int64 v = 1;</code> */ long getV(); /** * <code>string err = 2;</code> */ java.lang.String getErr(); /** * <code>string err = 2;</code> */ com.google.protobuf.ByteString getErrBytes(); } /** * <pre> * The sum response contains the result of the calculation. * </pre> * * Protobuf type {@code addsvc.SumReply} */ public static final class SumReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:addsvc.SumReply) SumReplyOrBuilder { private static final long serialVersionUID = 0L; // Use SumReply.newBuilder() to construct. private SumReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SumReply() { v_ = 0L; err_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SumReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { v_ = input.readInt64(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); err_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_SumReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_SumReply_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.SumReply.class, addsvc.Addsvc.SumReply.Builder.class); } public static final int V_FIELD_NUMBER = 1; private long v_; /** * <code>int64 v = 1;</code> */ public long getV() { return v_; } public static final int ERR_FIELD_NUMBER = 2; private volatile java.lang.Object err_; /** * <code>string err = 2;</code> */ public java.lang.String getErr() { java.lang.Object ref = err_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); err_ = s; return s; } } /** * <code>string err = 2;</code> */ public com.google.protobuf.ByteString getErrBytes() { java.lang.Object ref = err_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); err_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (v_ != 0L) { output.writeInt64(1, v_); } if (!getErrBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, err_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (v_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, v_); } if (!getErrBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, err_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof addsvc.Addsvc.SumReply)) { return super.equals(obj); } addsvc.Addsvc.SumReply other = (addsvc.Addsvc.SumReply) obj; boolean result = true; result = result && (getV() == other.getV()); result = result && getErr() .equals(other.getErr()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + V_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getV()); hash = (37 * hash) + ERR_FIELD_NUMBER; hash = (53 * hash) + getErr().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static addsvc.Addsvc.SumReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.SumReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.SumReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.SumReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.SumReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static addsvc.Addsvc.SumReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.SumReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.SumReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(addsvc.Addsvc.SumReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The sum response contains the result of the calculation. * </pre> * * Protobuf type {@code addsvc.SumReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:addsvc.SumReply) addsvc.Addsvc.SumReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_SumReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_SumReply_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.SumReply.class, addsvc.Addsvc.SumReply.Builder.class); } // Construct using addsvc.Addsvc.SumReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); v_ = 0L; err_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return addsvc.Addsvc.internal_static_addsvc_SumReply_descriptor; } public addsvc.Addsvc.SumReply getDefaultInstanceForType() { return addsvc.Addsvc.SumReply.getDefaultInstance(); } public addsvc.Addsvc.SumReply build() { addsvc.Addsvc.SumReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public addsvc.Addsvc.SumReply buildPartial() { addsvc.Addsvc.SumReply result = new addsvc.Addsvc.SumReply(this); result.v_ = v_; result.err_ = err_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof addsvc.Addsvc.SumReply) { return mergeFrom((addsvc.Addsvc.SumReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(addsvc.Addsvc.SumReply other) { if (other == addsvc.Addsvc.SumReply.getDefaultInstance()) return this; if (other.getV() != 0L) { setV(other.getV()); } if (!other.getErr().isEmpty()) { err_ = other.err_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { addsvc.Addsvc.SumReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (addsvc.Addsvc.SumReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long v_ ; /** * <code>int64 v = 1;</code> */ public long getV() { return v_; } /** * <code>int64 v = 1;</code> */ public Builder setV(long value) { v_ = value; onChanged(); return this; } /** * <code>int64 v = 1;</code> */ public Builder clearV() { v_ = 0L; onChanged(); return this; } private java.lang.Object err_ = ""; /** * <code>string err = 2;</code> */ public java.lang.String getErr() { java.lang.Object ref = err_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); err_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string err = 2;</code> */ public com.google.protobuf.ByteString getErrBytes() { java.lang.Object ref = err_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); err_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string err = 2;</code> */ public Builder setErr( java.lang.String value) { if (value == null) { throw new NullPointerException(); } err_ = value; onChanged(); return this; } /** * <code>string err = 2;</code> */ public Builder clearErr() { err_ = getDefaultInstance().getErr(); onChanged(); return this; } /** * <code>string err = 2;</code> */ public Builder setErrBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); err_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:addsvc.SumReply) } // @@protoc_insertion_point(class_scope:addsvc.SumReply) private static final addsvc.Addsvc.SumReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new addsvc.Addsvc.SumReply(); } public static addsvc.Addsvc.SumReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SumReply> PARSER = new com.google.protobuf.AbstractParser<SumReply>() { public SumReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SumReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SumReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SumReply> getParserForType() { return PARSER; } public addsvc.Addsvc.SumReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ConcatRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:addsvc.ConcatRequest) com.google.protobuf.MessageOrBuilder { /** * <code>string a = 1;</code> */ java.lang.String getA(); /** * <code>string a = 1;</code> */ com.google.protobuf.ByteString getABytes(); /** * <code>string b = 2;</code> */ java.lang.String getB(); /** * <code>string b = 2;</code> */ com.google.protobuf.ByteString getBBytes(); } /** * <pre> * The Concat request contains two parameters. * </pre> * * Protobuf type {@code addsvc.ConcatRequest} */ public static final class ConcatRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:addsvc.ConcatRequest) ConcatRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ConcatRequest.newBuilder() to construct. private ConcatRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ConcatRequest() { a_ = ""; b_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ConcatRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); a_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); b_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_ConcatRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_ConcatRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.ConcatRequest.class, addsvc.Addsvc.ConcatRequest.Builder.class); } public static final int A_FIELD_NUMBER = 1; private volatile java.lang.Object a_; /** * <code>string a = 1;</code> */ public java.lang.String getA() { java.lang.Object ref = a_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); a_ = s; return s; } } /** * <code>string a = 1;</code> */ public com.google.protobuf.ByteString getABytes() { java.lang.Object ref = a_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); a_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int B_FIELD_NUMBER = 2; private volatile java.lang.Object b_; /** * <code>string b = 2;</code> */ public java.lang.String getB() { java.lang.Object ref = b_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); b_ = s; return s; } } /** * <code>string b = 2;</code> */ public com.google.protobuf.ByteString getBBytes() { java.lang.Object ref = b_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); b_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getABytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, a_); } if (!getBBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, b_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getABytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, a_); } if (!getBBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, b_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof addsvc.Addsvc.ConcatRequest)) { return super.equals(obj); } addsvc.Addsvc.ConcatRequest other = (addsvc.Addsvc.ConcatRequest) obj; boolean result = true; result = result && getA() .equals(other.getA()); result = result && getB() .equals(other.getB()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + A_FIELD_NUMBER; hash = (53 * hash) + getA().hashCode(); hash = (37 * hash) + B_FIELD_NUMBER; hash = (53 * hash) + getB().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static addsvc.Addsvc.ConcatRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.ConcatRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.ConcatRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(addsvc.Addsvc.ConcatRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The Concat request contains two parameters. * </pre> * * Protobuf type {@code addsvc.ConcatRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:addsvc.ConcatRequest) addsvc.Addsvc.ConcatRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_ConcatRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_ConcatRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.ConcatRequest.class, addsvc.Addsvc.ConcatRequest.Builder.class); } // Construct using addsvc.Addsvc.ConcatRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); a_ = ""; b_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return addsvc.Addsvc.internal_static_addsvc_ConcatRequest_descriptor; } public addsvc.Addsvc.ConcatRequest getDefaultInstanceForType() { return addsvc.Addsvc.ConcatRequest.getDefaultInstance(); } public addsvc.Addsvc.ConcatRequest build() { addsvc.Addsvc.ConcatRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public addsvc.Addsvc.ConcatRequest buildPartial() { addsvc.Addsvc.ConcatRequest result = new addsvc.Addsvc.ConcatRequest(this); result.a_ = a_; result.b_ = b_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof addsvc.Addsvc.ConcatRequest) { return mergeFrom((addsvc.Addsvc.ConcatRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(addsvc.Addsvc.ConcatRequest other) { if (other == addsvc.Addsvc.ConcatRequest.getDefaultInstance()) return this; if (!other.getA().isEmpty()) { a_ = other.a_; onChanged(); } if (!other.getB().isEmpty()) { b_ = other.b_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { addsvc.Addsvc.ConcatRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (addsvc.Addsvc.ConcatRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object a_ = ""; /** * <code>string a = 1;</code> */ public java.lang.String getA() { java.lang.Object ref = a_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); a_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string a = 1;</code> */ public com.google.protobuf.ByteString getABytes() { java.lang.Object ref = a_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); a_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string a = 1;</code> */ public Builder setA( java.lang.String value) { if (value == null) { throw new NullPointerException(); } a_ = value; onChanged(); return this; } /** * <code>string a = 1;</code> */ public Builder clearA() { a_ = getDefaultInstance().getA(); onChanged(); return this; } /** * <code>string a = 1;</code> */ public Builder setABytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); a_ = value; onChanged(); return this; } private java.lang.Object b_ = ""; /** * <code>string b = 2;</code> */ public java.lang.String getB() { java.lang.Object ref = b_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); b_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string b = 2;</code> */ public com.google.protobuf.ByteString getBBytes() { java.lang.Object ref = b_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); b_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string b = 2;</code> */ public Builder setB( java.lang.String value) { if (value == null) { throw new NullPointerException(); } b_ = value; onChanged(); return this; } /** * <code>string b = 2;</code> */ public Builder clearB() { b_ = getDefaultInstance().getB(); onChanged(); return this; } /** * <code>string b = 2;</code> */ public Builder setBBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); b_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:addsvc.ConcatRequest) } // @@protoc_insertion_point(class_scope:addsvc.ConcatRequest) private static final addsvc.Addsvc.ConcatRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new addsvc.Addsvc.ConcatRequest(); } public static addsvc.Addsvc.ConcatRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ConcatRequest> PARSER = new com.google.protobuf.AbstractParser<ConcatRequest>() { public ConcatRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ConcatRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ConcatRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ConcatRequest> getParserForType() { return PARSER; } public addsvc.Addsvc.ConcatRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ConcatReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:addsvc.ConcatReply) com.google.protobuf.MessageOrBuilder { /** * <code>string v = 1;</code> */ java.lang.String getV(); /** * <code>string v = 1;</code> */ com.google.protobuf.ByteString getVBytes(); /** * <code>string err = 2;</code> */ java.lang.String getErr(); /** * <code>string err = 2;</code> */ com.google.protobuf.ByteString getErrBytes(); } /** * <pre> * The Concat response contains the result of the concatenation. * </pre> * * Protobuf type {@code addsvc.ConcatReply} */ public static final class ConcatReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:addsvc.ConcatReply) ConcatReplyOrBuilder { private static final long serialVersionUID = 0L; // Use ConcatReply.newBuilder() to construct. private ConcatReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ConcatReply() { v_ = ""; err_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ConcatReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); v_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); err_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_ConcatReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_ConcatReply_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.ConcatReply.class, addsvc.Addsvc.ConcatReply.Builder.class); } public static final int V_FIELD_NUMBER = 1; private volatile java.lang.Object v_; /** * <code>string v = 1;</code> */ public java.lang.String getV() { java.lang.Object ref = v_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); v_ = s; return s; } } /** * <code>string v = 1;</code> */ public com.google.protobuf.ByteString getVBytes() { java.lang.Object ref = v_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); v_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ERR_FIELD_NUMBER = 2; private volatile java.lang.Object err_; /** * <code>string err = 2;</code> */ public java.lang.String getErr() { java.lang.Object ref = err_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); err_ = s; return s; } } /** * <code>string err = 2;</code> */ public com.google.protobuf.ByteString getErrBytes() { java.lang.Object ref = err_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); err_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getVBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, v_); } if (!getErrBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, err_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getVBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, v_); } if (!getErrBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, err_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof addsvc.Addsvc.ConcatReply)) { return super.equals(obj); } addsvc.Addsvc.ConcatReply other = (addsvc.Addsvc.ConcatReply) obj; boolean result = true; result = result && getV() .equals(other.getV()); result = result && getErr() .equals(other.getErr()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + V_FIELD_NUMBER; hash = (53 * hash) + getV().hashCode(); hash = (37 * hash) + ERR_FIELD_NUMBER; hash = (53 * hash) + getErr().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static addsvc.Addsvc.ConcatReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static addsvc.Addsvc.ConcatReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static addsvc.Addsvc.ConcatReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.ConcatReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static addsvc.Addsvc.ConcatReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static addsvc.Addsvc.ConcatReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(addsvc.Addsvc.ConcatReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The Concat response contains the result of the concatenation. * </pre> * * Protobuf type {@code addsvc.ConcatReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:addsvc.ConcatReply) addsvc.Addsvc.ConcatReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return addsvc.Addsvc.internal_static_addsvc_ConcatReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return addsvc.Addsvc.internal_static_addsvc_ConcatReply_fieldAccessorTable .ensureFieldAccessorsInitialized( addsvc.Addsvc.ConcatReply.class, addsvc.Addsvc.ConcatReply.Builder.class); } // Construct using addsvc.Addsvc.ConcatReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); v_ = ""; err_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return addsvc.Addsvc.internal_static_addsvc_ConcatReply_descriptor; } public addsvc.Addsvc.ConcatReply getDefaultInstanceForType() { return addsvc.Addsvc.ConcatReply.getDefaultInstance(); } public addsvc.Addsvc.ConcatReply build() { addsvc.Addsvc.ConcatReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public addsvc.Addsvc.ConcatReply buildPartial() { addsvc.Addsvc.ConcatReply result = new addsvc.Addsvc.ConcatReply(this); result.v_ = v_; result.err_ = err_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof addsvc.Addsvc.ConcatReply) { return mergeFrom((addsvc.Addsvc.ConcatReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(addsvc.Addsvc.ConcatReply other) { if (other == addsvc.Addsvc.ConcatReply.getDefaultInstance()) return this; if (!other.getV().isEmpty()) { v_ = other.v_; onChanged(); } if (!other.getErr().isEmpty()) { err_ = other.err_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { addsvc.Addsvc.ConcatReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (addsvc.Addsvc.ConcatReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object v_ = ""; /** * <code>string v = 1;</code> */ public java.lang.String getV() { java.lang.Object ref = v_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); v_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string v = 1;</code> */ public com.google.protobuf.ByteString getVBytes() { java.lang.Object ref = v_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); v_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string v = 1;</code> */ public Builder setV( java.lang.String value) { if (value == null) { throw new NullPointerException(); } v_ = value; onChanged(); return this; } /** * <code>string v = 1;</code> */ public Builder clearV() { v_ = getDefaultInstance().getV(); onChanged(); return this; } /** * <code>string v = 1;</code> */ public Builder setVBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); v_ = value; onChanged(); return this; } private java.lang.Object err_ = ""; /** * <code>string err = 2;</code> */ public java.lang.String getErr() { java.lang.Object ref = err_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); err_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string err = 2;</code> */ public com.google.protobuf.ByteString getErrBytes() { java.lang.Object ref = err_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); err_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string err = 2;</code> */ public Builder setErr( java.lang.String value) { if (value == null) { throw new NullPointerException(); } err_ = value; onChanged(); return this; } /** * <code>string err = 2;</code> */ public Builder clearErr() { err_ = getDefaultInstance().getErr(); onChanged(); return this; } /** * <code>string err = 2;</code> */ public Builder setErrBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); err_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:addsvc.ConcatReply) } // @@protoc_insertion_point(class_scope:addsvc.ConcatReply) private static final addsvc.Addsvc.ConcatReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new addsvc.Addsvc.ConcatReply(); } public static addsvc.Addsvc.ConcatReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ConcatReply> PARSER = new com.google.protobuf.AbstractParser<ConcatReply>() { public ConcatReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ConcatReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ConcatReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ConcatReply> getParserForType() { return PARSER; } public addsvc.Addsvc.ConcatReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_addsvc_SumRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_addsvc_SumRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_addsvc_SumReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_addsvc_SumReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_addsvc_ConcatRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_addsvc_ConcatRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_addsvc_ConcatReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_addsvc_ConcatReply_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\014addsvc.proto\022\006addsvc\"\"\n\nSumRequest\022\t\n\001" + "a\030\001 \001(\003\022\t\n\001b\030\002 \001(\003\"\"\n\010SumReply\022\t\n\001v\030\001 \001(" + "\003\022\013\n\003err\030\002 \001(\t\"%\n\rConcatRequest\022\t\n\001a\030\001 \001" + "(\t\022\t\n\001b\030\002 \001(\t\"%\n\013ConcatReply\022\t\n\001v\030\001 \001(\t\022" + "\013\n\003err\030\002 \001(\t2l\n\003Add\022-\n\003Sum\022\022.addsvc.SumR" + "equest\032\020.addsvc.SumReply\"\000\0226\n\006Concat\022\025.a" + "ddsvc.ConcatRequest\032\023.addsvc.ConcatReply" + "\"\000b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_addsvc_SumRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_addsvc_SumRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_addsvc_SumRequest_descriptor, new java.lang.String[] { "A", "B", }); internal_static_addsvc_SumReply_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_addsvc_SumReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_addsvc_SumReply_descriptor, new java.lang.String[] { "V", "Err", }); internal_static_addsvc_ConcatRequest_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_addsvc_ConcatRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_addsvc_ConcatRequest_descriptor, new java.lang.String[] { "A", "B", }); internal_static_addsvc_ConcatReply_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_addsvc_ConcatReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_addsvc_ConcatReply_descriptor, new java.lang.String[] { "V", "Err", }); } // @@protoc_insertion_point(outer_class_scope) }
32.221698
105
0.625958
794d853c84d6e0aa3abc1888baa9aa1eff5f7070
1,844
package com.cognifide.cq.includefilter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.sling.SlingFilter; import org.apache.felix.scr.annotations.sling.SlingFilterScope; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SlingFilter(scope = SlingFilterScope.REQUEST, order = 0) public class CacheControlFilter implements Filter { private static final String HEADER_CACHE_CONTROL = "Cache-Control"; private static final Logger LOG = LoggerFactory.getLogger(CacheControlFilter.class); @Reference private ConfigurationWhiteboard configurationWhiteboard; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; final String resourceType = slingRequest.getResource().getResourceType(); final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType); if (config != null && config.hasTtlSet()) { SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response; slingResponse.setHeader(HEADER_CACHE_CONTROL, "max-age=" + config.getTtl()); LOG.debug("set \"{}: max-age={}\" to {}", HEADER_CACHE_CONTROL, config.getTtl(), resourceType); } chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
34.148148
100
0.804772