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
854af7f0b89e59f849ec17ed5b1846e2995023d8
5,294
/* * Copyright 2012-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.glowroot.agent.ui.sandbox; import java.io.File; import java.util.concurrent.Executors; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import org.glowroot.agent.it.harness.AppUnderTest; import org.glowroot.agent.it.harness.Container; import org.glowroot.agent.it.harness.impl.JavaagentContainer; import org.glowroot.agent.it.harness.impl.LocalContainer; import static com.google.common.base.Charsets.UTF_8; import static java.util.concurrent.TimeUnit.SECONDS; public class UiSandboxMain { private static final boolean useJavaagent = Boolean.getBoolean("glowroot.sandbox.javaagent"); private static final boolean useGlowrootCentral = Boolean.getBoolean("glowroot.sandbox.central"); private UiSandboxMain() {} public static void main(String[] args) throws Exception { Container container; File testDir = new File("target"); File configFile = new File(testDir, "config.json"); if (!configFile.exists()) { Files.write( "{\"transactions\":{\"profilingIntervalMillis\":100}," + "\"ui\":{\"defaultTransactionType\":\"Sandbox\"}}", configFile, UTF_8); } if (useJavaagent && useGlowrootCentral) { container = new JavaagentContainer(testDir, false, ImmutableList.of("-Dglowroot.agent.id=UI Sandbox", "-Dglowroot.collector.address=localhost:8181")); } else if (useJavaagent) { container = new JavaagentContainer(testDir, true, ImmutableList.<String>of()); } else if (useGlowrootCentral) { container = new LocalContainer(testDir, false, ImmutableMap.of("glowroot.agent.id", "UI Sandbox", "glowroot.collector.address", "localhost:8181")); } else { container = new LocalContainer(testDir, true, ImmutableMap.<String, String>of()); } container.executeNoExpectedTrace(GenerateTraces.class); } public static class GenerateTraces implements AppUnderTest { @Override public void executeApp() throws Exception { startDeadlockingThreads(); startDeadlockingThreads(); while (true) { Stopwatch stopwatch = Stopwatch.createStarted(); while (stopwatch.elapsed(SECONDS) < 300) { // a very short trace that will have an empty profile new NestableCall(1, 10, 100).execute(); // a trace that will have profile tree with only a single leaf new NestableCall(1, 100, 100).execute(); new NestableCall(new NestableCall(10, 50, 5000), 20, 50, 5000).execute(); new NestableCall(new NestableCall(5, 50, 5000), 5, 50, 5000).execute(); new NestableCall(new NestableCall(10, 50, 5000), 10, 50, 5000).execute(); new NestableCall(new NestableCall(20, 50, 5000), 5, 50, 5000).execute(); } new NestableCall(new NestableCall(5000, 50, 5000), 100, 50, 5000).execute(); Thread.sleep(1000); } } private void startDeadlockingThreads() { final Object lock1 = new Object(); final Object lock2 = new Object(); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { synchronized (lock1) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } synchronized (lock2) { // should never gets here } } } }); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { synchronized (lock2) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } synchronized (lock1) { // should never gets here } } } }); } } }
42.352
97
0.567057
e4de94ecba0c682ef331607a85ceef9ac0c61b39
1,995
/** * Copyright 2011-2019 Asakusa Framework Team. * * 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.asakusafw.lang.utils.common; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; import java.util.concurrent.Callable; import org.junit.Test; /** * Test for {@link Lang}. */ public class LangTest { /** * safe w/o exception. */ @Test public void safe_ok() { assertThat(Lang.safe(() -> 0), is(0)); } /** * safe w/ exception. */ @Test public void safe_raise() { boolean thrown = false; try { Lang.safe((Callable<?>) () -> { throw new IOException(); }); } catch (AssertionError e) { thrown = true; } assertThat(thrown, is(true)); } /** * safe w/o exception. */ @Test public void safe_runnable_ok() { Lang.safe(() -> { return; }); } /** * safe w/ exception. */ @Test public void safe_runnable_raise() { boolean thrown = false; try { Lang.safe((RunnableWithException<?>) () -> { throw new IOException(); }); } catch (AssertionError e) { thrown = true; } assertThat(thrown, is(true)); } /** * let w/ action. */ @Test public void let_action() { assertThat(Lang.let(new StringBuffer(), b -> { b.append("A"); }).toString(), is("A")); } }
24.036145
94
0.585464
e7316da5a18c4fe584363125d1397e4481d4a507
1,113
package org.bovinegenius.kurgan.types; import static java.lang.String.format; import java.util.regex.Pattern; import org.bovinegenius.kurgan.ConfigTypeErrorException; import org.bovinegenius.kurgan.yaml.YamlUtils; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; public class ConfigPattern implements ConfigType { public static final ConfigPattern value = new ConfigPattern(); @Override public Object coerce(Node node) { try { String value = YamlUtils.getValue((ScalarNode)node); return Pattern.compile(value); } catch (Exception e) { throw new ConfigTypeErrorException(node, format("Invalid regex - %s", value), e); } } @Override public void typeCheck(Node node) throws ConfigTypeErrorException { if (!(node instanceof ScalarNode)) { throw new ConfigTypeErrorException(node, String.format("Expected %s, found %s", this.toString(), node.getNodeId())); } coerce(node); } @Override public String toString() { return "Pattern"; } }
29.289474
128
0.678347
62df69fa68726e11f277a82c51fd74fcd1eed6fd
3,150
package de.upb.recalys.helper; import java.awt.Color; /** * The Class CSSColorExtractor provides static methods to extract specific * colors from a css file. * * @author Roman Kober */ public class CSSColorExtractor { /** * Gets the fill-colors from a CSS File that defines a node element. * * @param path * the path to a CSS File in the BuildPath * @return the fill-colors of the node element */ public static Color[] getPieChartFillColors(String path) { Color[] fillColors; StringBuffer css = new StringBuffer(ResourceHandler.getDataAsString(path)); css.delete(0, css.indexOf("node {") + 7); css.delete(css.indexOf("}"), css.length()); css.delete(0, css.indexOf("fill-color")); css.delete(css.indexOf(";"), css.length()); css.delete(0, css.indexOf(":") + 1); String colorsString = css.toString(); colorsString = colorsString.trim(); String[] colors = colorsString.split(","); fillColors = new Color[colors.length]; for (int i = 0; i < colors.length; i++) { colors[i] = colors[i].trim(); if (colors[i].startsWith("#")) { fillColors[i] = Color.decode(colors[i]); } else { try { fillColors[i] = (Color) Color.class.getField(colors[i]).get(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { e.printStackTrace(); } } } return fillColors; } /** * Gets the fill-colors from the edges in a CSS-File that defines an edge * element in a Pie Graph. * * @param path * the path to a CSS File in the BuildPath. * @return the fill-colors of the edge element. The first element is the * fill-color for a Simple Path edge and the second is the fill-color * for a normal edge. */ public static Color[] getEdgeColors(String path) { Color[] fillColors = new Color[3]; boolean isUserPath = false; StringBuffer css = new StringBuffer(ResourceHandler.getDataAsString(path)); while (css.indexOf("edge") != -1) { isUserPath = false; css.delete(0, css.indexOf("edge") + 4); int index = -1; if (css.indexOf(" {") == 0) { // normal edge index = 1; } else if (css.indexOf(".simplePath") == 0) { // Simple Path edge index = 0; } else if (css.indexOf(".userPath") == 0) { index = 2; isUserPath = true; } if (css.indexOf("fill-color") == -1 && !isUserPath || css.indexOf("shadow-color") == -1 && isUserPath) { continue; } if (isUserPath) { css.delete(0, css.indexOf("shadow-color")); } else { css.delete(0, css.indexOf("fill-color")); } css.delete(0, css.indexOf(":") + 1); String fillcolor = css.substring(0, css.indexOf(";")); fillcolor = fillcolor.trim(); if (index != -1) { if (fillcolor.startsWith("#")) { fillColors[index] = Color.decode(fillcolor); } else { try { fillColors[index] = (Color) Color.class.getField(fillcolor).get(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { e.printStackTrace(); } } } } return fillColors; } }
27.876106
107
0.629841
3022956ab090d4cbc8e49ed3d40e3f69e3dd5c67
4,964
package nicta.com.au.failureanalysis.SectionOverlap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import nicta.com.au.failureanalysis.search.CollectionReader; import nicta.com.au.patent.document.P; import nicta.com.au.patent.document.PatentDocument; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Bits; public class DescSectionsOverlap { private static IndexReader ir; static String indexDir = "data/INDEX/indexWithoutSW-Vec-CLEF-IP2010"; // private final int topK; public DescSectionsOverlap(String indexDir/*, String similarity, int topK*/) throws IOException { ir = DirectoryReader.open(FSDirectory.open(new File(indexDir))); } public HashSet<String> LoopOverIndexedDocs() throws IOException{ DescSectionsOverlap dsoverlap = new DescSectionsOverlap(indexDir); // HashSet<String> patents = dsoverlap.LoopOverIndexedDocs(); String docName; HashSet<String> indexedpataents= new HashSet<>(); Bits liveDocs = MultiFields.getLiveDocs(ir); System.out.println(ir.maxDoc()); System.out.println("----------------------"); for (int i=0; i<ir.maxDoc(); i++) { if (liveDocs != null && !liveDocs.get(i)) continue; Document doc = ir.document(i); docName = doc.get(PatentDocument.FileName); dsoverlap.CalculateSecOverlap(docName); // System.out.println(doc.get(PatentDocument.FileName).substring(3)); indexedpataents.add(docName); } return indexedpataents; } public void CalculateSecOverlap(String docName) throws IOException{ /*--------------------------- Write in output file. ------------------------*/ String outputfile = "./output/SecOverlap/secoverlp.txt"; FileOutputStream out = new FileOutputStream(outputfile); PrintStream ps = new PrintStream(out); /*--------------------------------------------------------------------------*/ String titlefield = PatentDocument.Title; String absfield = PatentDocument.Abstract; String descfield = PatentDocument.Description; String claimsfield = PatentDocument.Claims; int titlexists = 0; int absexists = 0; int descexists = 0; int claimsexists = 0; int notexists = 0; CollectionReader reader = new CollectionReader(indexDir); // System.out.println(reader.getDocTerms(docName, titlefield)); HashSet<String> titleterms = reader.getDocTerms(docName, titlefield); HashSet<String> absterms = reader.getDocTerms(docName, absfield); HashSet<String> descterms = reader.getDocTerms(docName, descfield); HashSet<String> claimsterms = reader.getDocTerms(docName, claimsfield); int titlesize; int abssize; int descsize; int claimssize; if(titleterms!=null){titlesize = titleterms.size();}else{titlesize=-1;} if(absterms!=null){abssize = absterms.size();}else{abssize=-1;} if(descterms!=null){descsize = descterms.size();}else{descsize=-1;} if(claimsterms!=null){claimssize = claimsterms.size();}else{claimssize=-1;} System.out.println(titlesize +"\t"+ abssize + "\t" + descsize + "\t" + claimssize); if(descterms!=null){ // System.out.println(descterms); if(titleterms!=null){ for(String t : titleterms){ if(descterms.contains(t)){ titlexists++; } // System.out.println(t + "\t"+ descterms.contains(t)); }}else{absexists = 2;} if(absterms!=null){ for(String a : absterms){ if(descterms.contains(a)){ absexists++; } // System.out.println(a + "\t"+ descterms.contains(a)); }}else{absexists = 2;} if(claimsterms!=null){ for(String c : claimsterms){ if(descterms.contains(c)){ claimsexists++; } // System.out.println(a + "\t"+ descterms.contains(a)); }}else{claimsexists = 2;} System.out.println((titlexists + "\t" + absexists + "\t" + claimsexists)); System.out.println(docName+ "\t"+(float)titlexists/titlesize + "\t" + (float)absexists/abssize + "\t" + (float)claimsexists/claimssize); ps.println(docName+ "\t"+(float)titlexists/titlesize + "\t" + (float)absexists/abssize + "\t" + (float)claimsexists/claimssize); System.out.println("----------------------------------------------------"); }else{System.out.println(docName + "\t"+"no desc"); ps.println(docName + "\t"+"no desc"); System.out.println("-----------------------------------------------------");} /*System.out.println(patents.size());*/ /*for (String p:patents){System.out.println(p);}*/ } public static void main(String[] args) throws IOException { String docName = "UN-EP-0802230"; DescSectionsOverlap dsoverlap = new DescSectionsOverlap(indexDir); // HashSet<String> patents = dsoverlap.LoopOverIndexedDocs(); dsoverlap.CalculateSecOverlap(docName); } }
34.713287
138
0.670427
61d77be49c105a8fbc160837ec487f70ab616bf6
785
package com.shipc.demo.test.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * @author shipc 2019/11/4 11:43 * @version 1.0 */ @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { /** * 解决:No mapping for GET /swagger-ui.html */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
32.708333
114
0.763057
1159010f8a33a676d468e03b8fced7d34b31975f
458
package toyrobot.client.command.factory.impl; import toyrobot.client.command.command.IGameCommand; import toyrobot.client.command.command.impl.PlaceGameCommand; import toyrobot.client.command.factory.GameCommandFactory; import toyrobot.domains.game.IGame; public class PlaceGameCommandFactory extends GameCommandFactory { public IGameCommand createGameCommand(IGame game, String[] params) { return new PlaceGameCommand(game, params); } }
30.533333
72
0.810044
9f902a72867c80f22ffaee4bb6c41a05223451f7
1,831
/** * */ package com.quikj.mw.service.framework; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * @author amit * */ public class ServiceExceptionHandler implements HandlerExceptionResolver { protected final Log logger = LogFactory.getLog(getClass()); private int order; public ServiceExceptionHandler() { } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse rsp, Object handler, Exception e) { String msg = getRootExceptionMessage(e); String session = req.getSession(true).getId(); String user = req.getUserPrincipal() == null ? "(not logged in)" : req.getUserPrincipal().getName(); logger.error( "Exception occured for user " + user + ", session: " + session + " (" + req.getRemoteAddr() + "). Exception: " + e.getClass().getName() + " thrown by object " + (handler == null ? "NULL" : handler + ". The error message is - " + msg), e); com.quikj.mw.core.value.Error error = new com.quikj.mw.core.value.Error(); error.setAdditionalInformation(msg); error.setSessionCode(session); ModelAndView mav = new ModelAndView("exceptionView"); mav.addObject(error); return mav; } private String getRootExceptionMessage(Throwable e) { if (e.getCause() != null) { return getRootExceptionMessage(e.getCause()); } else { return e.getMessage(); } } }
25.788732
103
0.669033
b5c93e7a5a0e3f8eab36bade679e092bea027910
9,079
package com.roselism.callpp.activity; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.roselism.callpp.R; import com.roselism.callpp.util.LogUtil; import com.roselism.callpp.util.convert.InStream2OutStream; import com.roselism.callpp.util.convert.InStream2String; import com.roselism.callpp.util.net.HttpConnectionHelper; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import butterknife.Bind; import butterknife.ButterKnife; public class SplashActivity extends AppCompatActivity { private final static int CODE_ENTER_HOME = 1; // 进入主界面 private final static int CODE_JSON_ERROR = 2; // json解析错误 private final static int CODE_IO_ERROR = 3; // private final static int CODE_READ_FINISHED = 4; // 读取完毕 @Bind(R.id.bg_image) ImageView mBgImage; @Bind(R.id.splash_tv_versionname) TextView mSplashTvVersionname; @Bind(R.id.splash_progress_loading) ProgressBar mSplashProgressLoading;// private int serverVersionCode; // 版本号 private String serverVersionName; // 版本名字 private String downloadUrl; // 下载url private String desc; //新版本描述 private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // 到达这里一定是程序已经运行了两秒之后的 switch (msg.what) { case CODE_ENTER_HOME: // 进入主界面 enterHome(); break; case CODE_JSON_ERROR: // json 解析错误 enterHome(); break; case CODE_IO_ERROR: // 网络链接错误 enterHome(); break; case CODE_READ_FINISHED: // 读取完毕 checkUpdate(); break; } } }; // json //{"versionCode":"1", "versionName":"1.52.52","desc":"新增NB功能,赶快下载","downloadLink":"www.asdjfiosdf.sdfasd"} @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initEvent(); initData(); } /** * 创一个dialog */ void buildDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("发现新版本" + serverVersionName). setMessage(desc). setPositiveButton("立即更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 开始下载 try { download(); } catch (IOException e) { e.printStackTrace(); } } }). setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { enterHome(); // 取消时进入home } }). setNegativeButton("一会儿再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { enterHome(); // 进入主页 } }).show(); } /** * 开始下载 * * @throws IOException */ private void download() throws IOException { HttpConnectionHelper.Builder builder = new HttpConnectionHelper.Builder(); HttpConnectionHelper helper = builder.setPath(downloadUrl).build(); File out = new File(getFilesDir(), serverVersionName + ".apk"); InStream2OutStream convert = new InStream2OutStream(out); // 输入输出流互考 convert.convert(helper.getConnection().getInputStream()); // 跳转到系统下载页面 Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setDataAndType(Uri.fromFile(out), "application/vnd.android.package-archive"); // startActivity(intent); startActivityForResult(intent, 0);// 如果用户取消安装的话,会返回结果,回调方法onActivityResult } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { enterHome(); } /** * 初始化view */ void initView() { setContentView(R.layout.activity_splash); ButterKnife.bind(this); readServerVersionInfo(); LogUtil.i("initview"); } /** * 初始化事件 */ void initEvent() { } /** * 初始化数据 */ void initData() { } /** * 进入主界面 */ public void enterHome() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } /** * 检验是否能够更新 */ public void checkUpdate() { if (serverVersionCode > readVersionCode()) { // 有更新版本 buildDialog(); // 创建一个dialog } else { // 当前版本号与服务器相同,直接进入主界面 enterHome(); } } /** * 读取本地的版本号 * * @return 有则返回无则返回-1 */ protected int readVersionCode() { PackageManager manager = getPackageManager(); int versionCode = -1; try { PackageInfo info = manager.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES); versionCode = info.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 读取当前app的版本名字 * * @return 如果有则返回当前的版本名字,如果没有,则返回"" */ protected String readVersionName() { PackageManager manager = getPackageManager(); String versionName = ""; try { PackageInfo info = manager.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES); versionName = info.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionName; } /** * 读取服务器端的版本信息 */ void readServerVersionInfo() { LogUtil.i("readServerVersionInfo"); final long startTime = System.currentTimeMillis(); new Thread() { @Override public void run() { LogUtil.i("run"); Message msg = mHandler.obtainMessage(); String url = "url"; HttpConnectionHelper.Builder builder = new HttpConnectionHelper.Builder(); HttpConnectionHelper helper = builder.setPath(url).build(); // url try { if (helper.isResponseOk()) { // 回应200 链接正常 parseJson(helper); // 解析Json数据 msg.what = CODE_READ_FINISHED; } else { // 回应其他 what设置为进入主界面 LogUtil.i(helper.responseCode() + ""); msg.what = CODE_ENTER_HOME; } } catch (IOException e) { // 网络连接错误 msg.what = CODE_IO_ERROR; e.printStackTrace(); } catch (JSONException e) { // json 解析错误 msg.what = CODE_JSON_ERROR; e.printStackTrace(); } finally { long endTime = System.currentTimeMillis(); long useTime = endTime - startTime; if (useTime < 2000) { // 加载时间小于两秒 try { Thread.sleep(2000 - useTime); // 睡够两秒 进行跳转 } catch (InterruptedException e) { e.printStackTrace(); } } mHandler.sendMessage(msg); // handler 发送message } } /** * 解析 从网络得到的json数据 * @param helper 网络链接帮助器 * @throws IOException * @throws JSONException */ private void parseJson(HttpConnectionHelper helper) throws IOException, JSONException { InStream2String inStream2String = new InStream2String(); // 声明一个转换器 String context = inStream2String.convert(helper.getConnection().getInputStream()); // 转换成String JSONObject jsonObject = new JSONObject(context); // json解析对象 serverVersionName = jsonObject.getString("versionName"); // 版本名 serverVersionCode = jsonObject.getInt("versionCode"); // 版本号 desc = jsonObject.getString("desc"); // 版本描述 downloadUrl = jsonObject.getString("downloadLink"); // 下载链接 } }.start(); } }
32.541219
111
0.559863
d22d2474d440274077a976ac5d2111baa21d2a85
105
package com.fasterxml.jackson.core.util; public interface Instantiatable<T> { T createInstance(); }
17.5
40
0.752381
fd1b28d48ea84a88ef8175de6fa8d2995f01bd72
347
package com.lambdaschool.starthere.repository; import com.lambdaschool.starthere.models.Author; import org.springframework.data.repository.PagingAndSortingRepository; public interface AuthorRepository extends PagingAndSortingRepository<Author, Long> { Author findByLastname(String lastname); Author findByFirstname(String firstname); }
28.916667
82
0.838617
ef0c9165d0ad15d35a9cd6959fa975bce3b517a3
3,272
/* * Copyright (c) 2011 Matthew Francis * * 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 nsis.compression.bzip2; /** * BZip2 constants shared between the compressor and decompressor */ interface BZip2Constants { /** * First three bytes of the block header marker */ static final int BLOCK_HEADER_MARKER_1 = 0x314159; /** * Last three bytes of the block header marker */ static final int BLOCK_HEADER_MARKER_2 = 0x265359; /** * Number of symbols decoded after which a new Huffman table is selected */ static final int HUFFMAN_GROUP_RUN_LENGTH = 50; /** * Maximum possible Huffman alphabet size */ static final int HUFFMAN_MAXIMUM_ALPHABET_SIZE = 258; /** * The longest Huffman code length created by the encoder */ static final int HUFFMAN_ENCODE_MAXIMUM_CODE_LENGTH = 20; /** * The longest Huffman code length accepted by the decoder */ static final int HUFFMAN_DECODE_MAXIMUM_CODE_LENGTH = 23; /** * Minimum number of alternative Huffman tables */ static final int HUFFMAN_MINIMUM_TABLES = 2; /** * Maximum number of alternative Huffman tables */ static final int HUFFMAN_MAXIMUM_TABLES = 6; /** * Maximum possible number of Huffman table selectors */ static final int HUFFMAN_MAXIMUM_SELECTORS = (900000 / HUFFMAN_GROUP_RUN_LENGTH) + 1; /** * Huffman symbol used for run-length encoding */ static final int HUFFMAN_SYMBOL_RUNA = 0; /** * Huffman symbol used for run-length encoding */ static final int HUFFMAN_SYMBOL_RUNB = 1; /** * First three bytes of the end of stream marker */ static final int STREAM_END_MARKER_1 = 0x177245; /** * Last three bytes of the end of stream marker */ static final int STREAM_END_MARKER_2 = 0x385090; /** * 'B' 'Z' that marks the start of a BZip2 stream */ static final int STREAM_START_MARKER_1 = 0x425a; /** * 'h' that distinguishes BZip from BZip2 */ static final int STREAM_START_MARKER_2 = 0x68; /** * Legacy beginning of block marker */ static final int NSIS_BLOCK_HEADER_MARKER = 0x31; /** * Legacy ending of block marker */ static final int NSIS_STREAM_END_MARKER = 0x17; /** * Legacy block size */ static final int NSIS_BLOCK_SIZE = 100000; }
27.041322
86
0.727689
789fc1f31b8449e971e1b98499fff1c049dd1d38
1,189
package com.medisafe.app.gui.user; import com.medisafe.app.classes.Medic; import com.medisafe.app.classes.MedicPatientList; import com.medisafe.app.classes.User; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class UserInfoLabel extends JLabel implements MouseListener { UserInfoLabel(){ this.setText("!"); this.setForeground(Color.BLACK); this.setFont(new Font("Arial", Font.BOLD, 32)); this.setHorizontalAlignment(JLabel.CENTER); this.setOpaque(true); this.setBackground(Color.white); this.setBounds(1200, 10, 30, 30); this.addMouseListener(this); } @Override public void mouseClicked(MouseEvent e) { System.out.println("test"); UserInfoFrame.userInfoFrame = new UserInfoFrame(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { this.setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { } }
23.78
68
0.673675
c503cf5784e33faaf6d04f0327f1a42a1ee0163c
1,770
package com.oneeyedmen.okeydoke.junit; import com.oneeyedmen.okeydoke.Name; import org.junit.runner.Description; import java.lang.reflect.Method; public class StandardTestNamer implements TestNamer { @Override public String nameFor(Description description) { return nameFromClass(description) + suffixFromMethod(description); } private String suffixFromMethod(Description description) { String override = nameFromMethodAnnotation(description); if (override != null) return "." + override; String methodNameFromDescription = description.getMethodName(); return methodNameFromDescription == null ? "" : ("." + methodNameFromDescription); } private String nameFromMethodAnnotation(Description description) { Method method = methodFrom(description); if (method == null) return null; Name annotation = method.getAnnotation(Name.class); return annotation == null ? null : annotation.value(); } private Method methodFrom(Description description) { Class<?> testClass = description.getTestClass(); String methodName = description.getMethodName(); if (testClass == null || methodName == null) return null; try { return testClass.getMethod(methodName); } catch (NoSuchMethodException e) { return null; } } private String nameFromClass(Description description) { Class<?> testClass = description.getTestClass(); if (testClass == null) return description.getClassName(); Name annotation = testClass.getAnnotation(Name.class); return annotation == null ? testClass.getSimpleName() : annotation.value(); } }
34.705882
90
0.666102
c30bed7bcb8b54cf14331b498bd36799e2a50c1f
381
package snacks; /** * One of the more specialized snack objects. * @author Kevin Kirkham * */ public class Popcorn extends Snack { public static double price = 1.45; public Popcorn() { super("Popcorn", price); } public Popcorn(double price) { super("Popcorn", price); } public void setPrice(double price) { this.price = price; } }
15.24
46
0.619423
b0c977a45d19964123ba3eae84ed5abb0158a0f5
4,990
package edu.emich.honors.testconnect; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Created by Jordan on 4/15/2015. * * */ public class DB_Handler { private HttpClient client; private final String DESTINATION = "http://db2.emich.edu/~201501_cosc481_group01/ajax_handler.php"; private Context context; //constructor public DB_Handler(Context context){ this.context = context; this.client = new DefaultHttpClient(); } //method every time we need to send to remote DB //many methods below are using sendToRemote() private JSONObject sendToRemote(String request, JSONObject obj){ String result = ""; HttpPost post = new HttpPost(DESTINATION); try { List dict = new ArrayList(); dict.add(new BasicNameValuePair("content", obj.toString())); dict.add(new BasicNameValuePair("request", request)); post.setEntity(new UrlEncodedFormEntity(dict)); HttpResponse response = client.execute(post); result += EntityUtils.toString(response.getEntity()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("result",result); JSONObject jsonResult = null; try { jsonResult = new JSONObject(result); // jsonResult = new JSONObject( "{"+result+"}"); } catch (JSONException e) { e.printStackTrace(); } return jsonResult; } public JSONObject login(String user_name, String password){ JSONObject object = new JSONObject(); try { object.put("username", user_name); object.put("password", password); } catch (JSONException e) { e.printStackTrace(); } return sendToRemote("login", object); } //public JSONObject newUser(JSONObject user_data) //public JSONObject update_user(JSONObject user_data) //insert into table public boolean addLocalHandbook(JSONObject handbook){ boolean isFinished = false; try { JSONArray yearAndType = handbook.optJSONArray("requirements"); /*********** Process each JSON Node ************/ int lengthJsonArr = yearAndType.length(); for(int i=0; i < lengthJsonArr; i++) { /****** Get Object for each JSON node.***********/ JSONObject jsonChildNode = yearAndType.getJSONObject(i); /******* Fetch node values **********/ int dispNumber = Integer.parseInt(jsonChildNode.optString("display_number").toString()); String name = jsonChildNode.optString("requirement_name").toString(); String component = jsonChildNode.optString("name").toString(); int totalNeeded = Integer.parseInt(jsonChildNode.optString("total").toString()); String description = jsonChildNode.optString("description").toString(); SQLiteHelper localDB = new SQLiteHelper(this.context); localDB.insertRequirement("2007", "deparmental", dispNumber, name, component, totalNeeded, description); isFinished = true; } } catch (JSONException e) { e.printStackTrace(); //isFinished = false; -> already false } return isFinished; } //check if we have using SQLite query public boolean isLocalHandbook(String handbook_year, String honors_type){ JSONObject object = new JSONObject(); try { object.put("handbook_year", handbook_year); object.put("honors_type", honors_type); } catch (JSONException e) { e.printStackTrace(); } return true; //true if handbook of this year and type exists } public JSONObject handbookRequest(String year, String type){ JSONObject object = new JSONObject(); try { object.put("year", year); object.put("type", type); } catch (JSONException e) { e.printStackTrace(); } return sendToRemote("handbook", object); } //create }
31.582278
120
0.62505
538fc2cd84684ff3a1f08c98944f77a5921d3af5
4,466
package com.rethinkdb.net; import com.rethinkdb.gen.ast.Datum; import com.rethinkdb.gen.exc.ReqlDriverError; import com.rethinkdb.model.GroupedResult; import com.rethinkdb.model.MapObject; import com.rethinkdb.model.OptArgs; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.stream.Collectors; public class Converter { private static final Base64.Decoder b64decoder = Base64.getMimeDecoder(); private static final Base64.Encoder b64encoder = Base64.getMimeEncoder(); public static final String PSEUDOTYPE_KEY = "$reql_type$"; public static final String TIME = "TIME"; public static final String GROUPED_DATA = "GROUPED_DATA"; public static final String GEOMETRY = "GEOMETRY"; public static final String BINARY = "BINARY"; /* Compact way of keeping these flags around through multiple recursive passes */ public static class FormatOptions{ public final boolean rawTime; public final boolean rawGroups; public final boolean rawBinary; public FormatOptions(OptArgs args){ this.rawTime = ((Datum)args.getOrDefault("time_format", new Datum("native"))).datum.equals("raw"); this.rawBinary = ((Datum)args.getOrDefault("binary_format", new Datum("native"))).datum.equals("raw"); this.rawGroups = ((Datum)args.getOrDefault("group_format", new Datum("native"))).datum.equals("raw"); } } @SuppressWarnings("unchecked") public static Object convertPseudotypes(Object obj, FormatOptions fmt){ if(obj instanceof List) { return ((List<Object>) obj).stream() .map(item -> convertPseudotypes(item, fmt)) .collect(Collectors.toList()); } else if(obj instanceof Map) { Map<String, Object> mapobj = (Map<String, Object>) obj; if(mapobj.containsKey(PSEUDOTYPE_KEY)){ return convertPseudo(mapobj, fmt); } return mapobj.entrySet().stream() .collect( LinkedHashMap::new, (map, entry) -> map.put( entry.getKey(), convertPseudotypes(entry.getValue(), fmt) ), LinkedHashMap<String, Object>::putAll ); } else { return obj; } } public static Object convertPseudo(Map<String, Object> value, FormatOptions fmt) { if(value == null){ return null; } String reqlType = (String) value.get(PSEUDOTYPE_KEY); switch (reqlType) { case TIME: return fmt.rawTime ? value : getTime(value); case GROUPED_DATA: return fmt.rawGroups ? value : getGrouped(value); case BINARY: return fmt.rawBinary ? value : getBinary(value); case GEOMETRY: // Nothing specific here return value; default: // Just leave unknown pseudo-types alone return value; } } @SuppressWarnings("unchecked") private static List<GroupedResult<?,?>> getGrouped(Map<String, Object> value) { return ((List<List<Object>>) value.get("data")).stream() .map(g -> new GroupedResult<>(g.remove(0), g)) .collect(Collectors.toList()); } private static OffsetDateTime getTime(Map<String, Object> obj) { try { ZoneOffset offset = ZoneOffset.of((String) obj.get("timezone")); double epochTime = ((Number) obj.get("epoch_time")).doubleValue(); Instant timeInstant = Instant.ofEpochMilli(((Double) (epochTime * 1000.0)).longValue()); return OffsetDateTime.ofInstant(timeInstant, offset); } catch (Exception ex) { throw new ReqlDriverError("Error handling date", ex); } } private static byte[] getBinary(Map<String, Object> value) { return b64decoder.decode((String) value.get("data")); } public static Map<String,Object> toBinary(byte[] data){ return new MapObject<String, Object>() .with("$reql_type$", BINARY) .with("data", b64encoder.encodeToString(data)); } }
37.847458
100
0.585759
ee0d3bbd719814e678dfeb3f237c9d9f5d11d315
4,090
/* Class194_Sub16_Sub1 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; public class Class194_Sub16_Sub1 extends Class194_Sub16 { int anInt11393; int anInt11394; int anInt11395; Class194_Sub16_Sub1(RSBuffer class523_sub34) { super(class523_sub34); int i = class523_sub34.readUnsignedInt((byte) -114); anInt11395 = -10807497 * (i >>> 16); anInt11393 = -274772717 * (i & 0xffff); anInt11394 = class523_sub34.readUnsignedByte(379913976) * -1046073583; } public void method3648(int i) { int i_0_ = anInt11395 * 2023558656 + 256; int i_1_ = anInt11393 * 1896494592 + 256; int i_2_ = anInt11394 * -1481334287; if (i_2_ < 3 && (client.aClass505_11019.method8243(2079762921).method7282(anInt11395 * -2093199737, -650607333 * anInt11393, -638715901))) i_2_++; Class647_Sub1_Sub3_Sub4 class647_sub1_sub3_sub4 = (new Class647_Sub1_Sub3_Sub4(client.aClass505_11019.method8241((byte) -87), anInt9938 * -1290676097, 0, anInt11394 * -1481334287, i_2_, i_0_, Class53_Sub17.method17220(i_0_, i_1_, anInt11394 * -1481334287, -151355447) - anInt9937 * -148075917, i_1_, anInt11395 * -2093199737, anInt11395 * -2093199737, anInt11393 * -650607333, anInt11393 * -650607333, anInt9939 * -241063875, false, 0)); client.aClass14_11174.method738(new Class523_Sub27_Sub9(class647_sub1_sub3_sub4), (long) (anInt11395 * -2093199737 << 16 | anInt11393 * -650607333)); } public void method3651() { int i = anInt11395 * 2023558656 + 256; int i_3_ = anInt11393 * 1896494592 + 256; int i_4_ = anInt11394 * -1481334287; if (i_4_ < 3 && (client.aClass505_11019.method8243(485887938).method7282(anInt11395 * -2093199737, -650607333 * anInt11393, -638715901))) i_4_++; Class647_Sub1_Sub3_Sub4 class647_sub1_sub3_sub4 = (new Class647_Sub1_Sub3_Sub4(client.aClass505_11019.method8241((byte) -30), anInt9938 * -1290676097, 0, anInt11394 * -1481334287, i_4_, i, Class53_Sub17.method17220(i, i_3_, anInt11394 * -1481334287, 1318078801) - anInt9937 * -148075917, i_3_, anInt11395 * -2093199737, anInt11395 * -2093199737, anInt11393 * -650607333, anInt11393 * -650607333, anInt9939 * -241063875, false, 0)); client.aClass14_11174.method738(new Class523_Sub27_Sub9(class647_sub1_sub3_sub4), (long) (anInt11395 * -2093199737 << 16 | anInt11393 * -650607333)); } public void method3656() { int i = anInt11395 * 2023558656 + 256; int i_5_ = anInt11393 * 1896494592 + 256; int i_6_ = anInt11394 * -1481334287; if (i_6_ < 3 && (client.aClass505_11019.method8243(474037021).method7282(anInt11395 * -2093199737, -650607333 * anInt11393, -638715901))) i_6_++; Class647_Sub1_Sub3_Sub4 class647_sub1_sub3_sub4 = (new Class647_Sub1_Sub3_Sub4(client.aClass505_11019.method8241((byte) -68), anInt9938 * -1290676097, 0, anInt11394 * -1481334287, i_6_, i, Class53_Sub17.method17220(i, i_5_, anInt11394 * -1481334287, -152833974) - anInt9937 * -148075917, i_5_, anInt11395 * -2093199737, anInt11395 * -2093199737, anInt11393 * -650607333, anInt11393 * -650607333, anInt9939 * -241063875, false, 0)); client.aClass14_11174.method738(new Class523_Sub27_Sub9(class647_sub1_sub3_sub4), (long) (anInt11395 * -2093199737 << 16 | anInt11393 * -650607333)); } public void method3657() { int i = anInt11395 * 2023558656 + 256; int i_7_ = anInt11393 * 1896494592 + 256; int i_8_ = anInt11394 * -1481334287; if (i_8_ < 3 && (client.aClass505_11019.method8243(402457385).method7282(anInt11395 * -2093199737, -650607333 * anInt11393, -638715901))) i_8_++; Class647_Sub1_Sub3_Sub4 class647_sub1_sub3_sub4 = (new Class647_Sub1_Sub3_Sub4(client.aClass505_11019.method8241((byte) -94), anInt9938 * -1290676097, 0, anInt11394 * -1481334287, i_8_, i, Class53_Sub17.method17220(i, i_7_, anInt11394 * -1481334287, -931466797) - anInt9937 * -148075917, i_7_, anInt11395 * -2093199737, anInt11395 * -2093199737, anInt11393 * -650607333, anInt11393 * -650607333, anInt9939 * -241063875, false, 0)); client.aClass14_11174.method738(new Class523_Sub27_Sub9(class647_sub1_sub3_sub4), (long) (anInt11395 * -2093199737 << 16 | anInt11393 * -650607333)); } }
69.322034
439
0.748166
e2f720950f780fe9da2c721964cbdefc105d7b3f
12,528
// 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 android.support.design.widget; import android.support.v4.math.MathUtils; import android.support.v4.view.ViewCompat; import android.support.v4.widget.ViewDragHelper; import android.view.View; import java.lang.ref.WeakReference; // Referenced classes of package android.support.design.widget: // BottomSheetBehavior class BottomSheetBehavior$2 extends android.support.v4.widget.k { public int clampViewPositionHorizontal(View view, int i, int j) { return view.getLeft(); // 0 0:aload_1 // 1 1:invokevirtual #24 <Method int View.getLeft()> // 2 4:ireturn } public int clampViewPositionVertical(View view, int i, int j) { int k = mMinOffset; // 0 0:aload_0 // 1 1:getfield #12 <Field BottomSheetBehavior this$0> // 2 4:getfield #29 <Field int BottomSheetBehavior.mMinOffset> // 3 7:istore 4 if(mHideable) //* 4 9:aload_0 //* 5 10:getfield #12 <Field BottomSheetBehavior this$0> //* 6 13:getfield #33 <Field boolean BottomSheetBehavior.mHideable> //* 7 16:ifeq 30 j = mParentHeight; // 8 19:aload_0 // 9 20:getfield #12 <Field BottomSheetBehavior this$0> // 10 23:getfield #36 <Field int BottomSheetBehavior.mParentHeight> // 11 26:istore_3 else //* 12 27:goto 38 j = mMaxOffset; // 13 30:aload_0 // 14 31:getfield #12 <Field BottomSheetBehavior this$0> // 15 34:getfield #39 <Field int BottomSheetBehavior.mMaxOffset> // 16 37:istore_3 return MathUtils.clamp(i, k, j); // 17 38:iload_2 // 18 39:iload 4 // 19 41:iload_3 // 20 42:invokestatic #45 <Method int MathUtils.clamp(int, int, int)> // 21 45:ireturn } public int getViewVerticalDragRange(View view) { if(mHideable) //* 0 0:aload_0 //* 1 1:getfield #12 <Field BottomSheetBehavior this$0> //* 2 4:getfield #33 <Field boolean BottomSheetBehavior.mHideable> //* 3 7:ifeq 26 return mParentHeight - mMinOffset; // 4 10:aload_0 // 5 11:getfield #12 <Field BottomSheetBehavior this$0> // 6 14:getfield #36 <Field int BottomSheetBehavior.mParentHeight> // 7 17:aload_0 // 8 18:getfield #12 <Field BottomSheetBehavior this$0> // 9 21:getfield #29 <Field int BottomSheetBehavior.mMinOffset> // 10 24:isub // 11 25:ireturn else return mMaxOffset - mMinOffset; // 12 26:aload_0 // 13 27:getfield #12 <Field BottomSheetBehavior this$0> // 14 30:getfield #39 <Field int BottomSheetBehavior.mMaxOffset> // 15 33:aload_0 // 16 34:getfield #12 <Field BottomSheetBehavior this$0> // 17 37:getfield #29 <Field int BottomSheetBehavior.mMinOffset> // 18 40:isub // 19 41:ireturn } public void onViewDragStateChanged(int i) { if(i == 1) //* 0 0:iload_1 //* 1 1:iconst_1 //* 2 2:icmpne 13 setStateInternal(1); // 3 5:aload_0 // 4 6:getfield #12 <Field BottomSheetBehavior this$0> // 5 9:iconst_1 // 6 10:invokevirtual #52 <Method void BottomSheetBehavior.setStateInternal(int)> // 7 13:return } public void onViewPositionChanged(View view, int i, int j, int k, int l) { dispatchOnSlide(j); // 0 0:aload_0 // 1 1:getfield #12 <Field BottomSheetBehavior this$0> // 2 4:iload_3 // 3 5:invokevirtual #57 <Method void BottomSheetBehavior.dispatchOnSlide(int)> // 4 8:return } public void onViewReleased(View view, float f, float f1) { byte byte0 = 4; // 0 0:iconst_4 // 1 1:istore 5 if(f1 >= 0.0F) goto _L2; else goto _L1 // 2 3:fload_3 // 3 4:fconst_0 // 4 5:fcmpg // 5 6:ifge 24 _L1: int i = mMinOffset; // 6 9:aload_0 // 7 10:getfield #12 <Field BottomSheetBehavior this$0> // 8 13:getfield #29 <Field int BottomSheetBehavior.mMinOffset> // 9 16:istore 4 _L4: byte0 = 3; // 10 18:iconst_3 // 11 19:istore 5 break MISSING_BLOCK_LABEL_135; // 12 21:goto 135 _L2: if(mHideable && shouldHide(view, f1)) //* 13 24:aload_0 //* 14 25:getfield #12 <Field BottomSheetBehavior this$0> //* 15 28:getfield #33 <Field boolean BottomSheetBehavior.mHideable> //* 16 31:ifeq 61 //* 17 34:aload_0 //* 18 35:getfield #12 <Field BottomSheetBehavior this$0> //* 19 38:aload_1 //* 20 39:fload_3 //* 21 40:invokevirtual #63 <Method boolean BottomSheetBehavior.shouldHide(View, float)> //* 22 43:ifeq 61 { i = mParentHeight; // 23 46:aload_0 // 24 47:getfield #12 <Field BottomSheetBehavior this$0> // 25 50:getfield #36 <Field int BottomSheetBehavior.mParentHeight> // 26 53:istore 4 byte0 = 5; // 27 55:iconst_5 // 28 56:istore 5 break MISSING_BLOCK_LABEL_135; // 29 58:goto 135 } if(f1 != 0.0F) break; /* Loop/switch isn't completed */ // 30 61:fload_3 // 31 62:fconst_0 // 32 63:fcmpl // 33 64:ifne 126 i = view.getTop(); // 34 67:aload_1 // 35 68:invokevirtual #66 <Method int View.getTop()> // 36 71:istore 4 if(Math.abs(i - mMinOffset) < Math.abs(i - mMaxOffset)) //* 37 73:iload 4 //* 38 75:aload_0 //* 39 76:getfield #12 <Field BottomSheetBehavior this$0> //* 40 79:getfield #29 <Field int BottomSheetBehavior.mMinOffset> //* 41 82:isub //* 42 83:invokestatic #72 <Method int Math.abs(int)> //* 43 86:iload 4 //* 44 88:aload_0 //* 45 89:getfield #12 <Field BottomSheetBehavior this$0> //* 46 92:getfield #39 <Field int BottomSheetBehavior.mMaxOffset> //* 47 95:isub //* 48 96:invokestatic #72 <Method int Math.abs(int)> //* 49 99:icmpge 114 { i = mMinOffset; // 50 102:aload_0 // 51 103:getfield #12 <Field BottomSheetBehavior this$0> // 52 106:getfield #29 <Field int BottomSheetBehavior.mMinOffset> // 53 109:istore 4 } else //* 54 111:goto 18 { i = mMaxOffset; // 55 114:aload_0 // 56 115:getfield #12 <Field BottomSheetBehavior this$0> // 57 118:getfield #39 <Field int BottomSheetBehavior.mMaxOffset> // 58 121:istore 4 break MISSING_BLOCK_LABEL_135; // 59 123:goto 135 } if(true) goto _L4; else goto _L3 _L3: i = mMaxOffset; // 60 126:aload_0 // 61 127:getfield #12 <Field BottomSheetBehavior this$0> // 62 130:getfield #39 <Field int BottomSheetBehavior.mMaxOffset> // 63 133:istore 4 if(mViewDragHelper.settleCapturedViewAt(view.getLeft(), i)) //* 64 135:aload_0 //* 65 136:getfield #12 <Field BottomSheetBehavior this$0> //* 66 139:getfield #76 <Field ViewDragHelper BottomSheetBehavior.mViewDragHelper> //* 67 142:aload_1 //* 68 143:invokevirtual #24 <Method int View.getLeft()> //* 69 146:iload 4 //* 70 148:invokevirtual #82 <Method boolean ViewDragHelper.settleCapturedViewAt(int, int)> //* 71 151:ifeq 181 { setStateInternal(2); // 72 154:aload_0 // 73 155:getfield #12 <Field BottomSheetBehavior this$0> // 74 158:iconst_2 // 75 159:invokevirtual #52 <Method void BottomSheetBehavior.setStateInternal(int)> ViewCompat.postOnAnimation(view, ((Runnable) (new ttleRunnable(BottomSheetBehavior.this, view, ((int) (byte0)))))); // 76 162:aload_1 // 77 163:new #84 <Class BottomSheetBehavior$SettleRunnable> // 78 166:dup // 79 167:aload_0 // 80 168:getfield #12 <Field BottomSheetBehavior this$0> // 81 171:aload_1 // 82 172:iload 5 // 83 174:invokespecial #87 <Method void BottomSheetBehavior$SettleRunnable(BottomSheetBehavior, View, int)> // 84 177:invokestatic #93 <Method void ViewCompat.postOnAnimation(View, Runnable)> return; // 85 180:return } else { setStateInternal(((int) (byte0))); // 86 181:aload_0 // 87 182:getfield #12 <Field BottomSheetBehavior this$0> // 88 185:iload 5 // 89 187:invokevirtual #52 <Method void BottomSheetBehavior.setStateInternal(int)> return; // 90 190:return } } public boolean tryCaptureView(View view, int i) { if(mState == 1) //* 0 0:aload_0 //* 1 1:getfield #12 <Field BottomSheetBehavior this$0> //* 2 4:getfield #98 <Field int BottomSheetBehavior.mState> //* 3 7:iconst_1 //* 4 8:icmpne 13 return false; // 5 11:iconst_0 // 6 12:ireturn if(mTouchingScrollingChild) //* 7 13:aload_0 //* 8 14:getfield #12 <Field BottomSheetBehavior this$0> //* 9 17:getfield #101 <Field boolean BottomSheetBehavior.mTouchingScrollingChild> //* 10 20:ifeq 25 return false; // 11 23:iconst_0 // 12 24:ireturn if(mState == 3 && mActivePointerId == i) //* 13 25:aload_0 //* 14 26:getfield #12 <Field BottomSheetBehavior this$0> //* 15 29:getfield #98 <Field int BottomSheetBehavior.mState> //* 16 32:iconst_3 //* 17 33:icmpne 75 //* 18 36:aload_0 //* 19 37:getfield #12 <Field BottomSheetBehavior this$0> //* 20 40:getfield #104 <Field int BottomSheetBehavior.mActivePointerId> //* 21 43:iload_2 //* 22 44:icmpne 75 { View view1 = (View)mNestedScrollingChildRef.get(); // 23 47:aload_0 // 24 48:getfield #12 <Field BottomSheetBehavior this$0> // 25 51:getfield #108 <Field WeakReference BottomSheetBehavior.mNestedScrollingChildRef> // 26 54:invokevirtual #114 <Method Object WeakReference.get()> // 27 57:checkcast #20 <Class View> // 28 60:astore_3 if(view1 != null && view1.canScrollVertically(-1)) //* 29 61:aload_3 //* 30 62:ifnull 75 //* 31 65:aload_3 //* 32 66:iconst_m1 //* 33 67:invokevirtual #118 <Method boolean View.canScrollVertically(int)> //* 34 70:ifeq 75 return false; // 35 73:iconst_0 // 36 74:ireturn } return mViewRef != null && mViewRef.get() == view; // 37 75:aload_0 // 38 76:getfield #12 <Field BottomSheetBehavior this$0> // 39 79:getfield #121 <Field WeakReference BottomSheetBehavior.mViewRef> // 40 82:ifnull 101 // 41 85:aload_0 // 42 86:getfield #12 <Field BottomSheetBehavior this$0> // 43 89:getfield #121 <Field WeakReference BottomSheetBehavior.mViewRef> // 44 92:invokevirtual #114 <Method Object WeakReference.get()> // 45 95:aload_1 // 46 96:if_acmpne 101 // 47 99:iconst_1 // 48 100:ireturn // 49 101:iconst_0 // 50 102:ireturn } final BottomSheetBehavior this$0; BottomSheetBehavior$2() { this$0 = BottomSheetBehavior.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #12 <Field BottomSheetBehavior this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #15 <Method void android.support.v4.widget.ViewDragHelper$Callback()> // 5 9:return } }
38.666667
118
0.557471
d3c62ad54e89f9fa2718efdefcb31698a2810361
418
package com.extracraftx.minecraft.extradoors.tags; import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.block.Block; import net.minecraft.tag.Tag; import net.minecraft.util.Identifier; public class Tags{ public static Tag<Block> INTERACTABLE_DOORS; public static void registerTags(){ INTERACTABLE_DOORS = TagRegistry.block(new Identifier("extradoors", "interactable_doors")); } }
29.857143
99
0.77512
2f3e6be74b653c77fa2faa3f4aba81ab7ee090c0
756
/* * 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 bin.game; import bin.game.dungeon.shop.ShopFactory; import bin.game.panels.ScreenControl; import bin.game.resources.GameResources; import bin.game.resources.GraphicResources; /** * * @author gbeljajew */ public class GameStart { public static void main(String[] args) { long t = System.currentTimeMillis(); GraphicResources.init(); GameResources.init(); ShopFactory.init(); ScreenControl.init(); System.out.println("loaded in " + (System.currentTimeMillis() - t)); } }
22.909091
79
0.662698
f5020c7ecfe26b1eabc1ab0f4eaee14318ce919d
3,855
package example.controllers; import example.models.Post; import example.models.UserAccount; import example.services.PostService; import example.services.PostServiceImpl; import example.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.List; /** * Controller for the Posts model. This class defines the * endpoints for a webapp to get information from the database. * in this case we will use the post controller for when a user * wants to create, update and/or delete a posts. Also we will be * getting all of the posts to fill out the main feed. * TODO: create, get, getall, update and delete */ @RestController @RequestMapping("/posts") @CrossOrigin(originPatterns = "*", allowCredentials = "true") //@SessionAttributes("loggedInUser") public class PostController { private PostService postService; private UserService userService; /** * Create new post. This endpoint will receive a post * from a user. * * @param incomingPost json request */ @PostMapping(value = "/create-post") @ResponseStatus(value = HttpStatus.CREATED) public void createNewPost(@RequestBody Post incomingPost, HttpSession session) { System.out.println("creating a new post"); UserAccount author = (UserAccount) session.getAttribute("loggedInUser"); incomingPost.setAuthor(author); postService.addPost(incomingPost); } /** * Return all of the posts for every registered user * that has posted something. will be used in the * regular feed where a user can see other users * posts * * @return list of all posts */ @GetMapping(value = "/getAllPosts") @ResponseStatus(value = HttpStatus.OK) public @ResponseBody List<Post> getAllPosts() { System.out.println("getting all posts"); return postService.getAllPosts(); } /** * Return all of the posts related to a specific user posts * by using their id. This will be used to populate a user * profile feed where they can see all of their posts. * * @param id userID * @return list of post */ @GetMapping(value = "/getAllUserPost") @ResponseStatus(value = HttpStatus.OK) public @ResponseBody List<Post> getAllUsersPosts(@RequestParam("id") int id) { return postService.getAllUserPosts(id); } /** * Delete a post. TODO: flesh out more * @param deletePost */ @DeleteMapping(value = "/deletePost") @ResponseStatus(value = HttpStatus.OK) public void deletePost(@RequestBody Post deletePost) { postService.deletePosts(deletePost); } /** * No args constructors */ public PostController() { } /** * Initialize a post service implementation * * @param postService PostsServiceImpl */ public PostController(PostServiceImpl postService) { this.postService = postService; } /** * Get post service impl * * @return PostServiceImpl */ public PostService getPostService() { return postService; } /** * Set post service implementation * * @param postService PostServiceImpl */ @Autowired public void setPostService(PostService postService) { this.postService = postService; } /** * Get user service * * @return UserService */ public UserService getUserService() { return userService; } /** * Set user service * * @param userService UserService */ @Autowired public void setUserService(UserService userService) { this.userService = userService; } }
26.22449
84
0.66537
424cde9b1f9066d7c1ca389ca82b87a2f1158d9b
2,548
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild package io.kaitai.struct.testformats; import io.kaitai.struct.ByteBufferKaitaiStream; import io.kaitai.struct.KaitaiStruct; import io.kaitai.struct.KaitaiStream; import java.io.IOException; /** * Another one-liner * @see <a href="http://www.example.com/some/path/?even_with=query&amp;more=2">Source</a> */ public class DocstringsDocref extends KaitaiStruct { public static DocstringsDocref fromFile(String fileName) throws IOException { return new DocstringsDocref(new ByteBufferKaitaiStream(fileName)); } public DocstringsDocref(KaitaiStream _io) { this(_io, null, null); } public DocstringsDocref(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public DocstringsDocref(KaitaiStream _io, KaitaiStruct _parent, DocstringsDocref _root) { super(_io); this._parent = _parent; this._root = _root == null ? this : _root; _read(); } private void _read() { this.one = this._io.readU1(); this.two = this._io.readU1(); this.three = this._io.readU1(); } private Boolean foo; /** * @see "Doc ref for instance, a plain one" */ public Boolean foo() { if (this.foo != null) return this.foo; boolean _tmp = (boolean) (true); this.foo = _tmp; return this.foo; } private Integer parseInst; /** * @see "Now this is a really * long document ref that * spans multiple lines. * " */ public Integer parseInst() { if (this.parseInst != null) return this.parseInst; long _pos = this._io.pos(); this._io.seek(0); this.parseInst = this._io.readU1(); this._io.seek(_pos); return this.parseInst; } private int one; private int two; private int three; private DocstringsDocref _root; private KaitaiStruct _parent; /** * @see "Plain text description of doc ref, page 42" */ public int one() { return one; } /** * Both doc and doc-ref are defined * @see <a href="http://www.example.com/with/url/again">Source</a> */ public int two() { return two; } /** * @see <a href="http://www.example.com/three">Documentation name</a> */ public int three() { return three; } public DocstringsDocref _root() { return _root; } public KaitaiStruct _parent() { return _parent; } }
27.695652
99
0.620879
38a929e1c40cbc0dfb7bdb615ff7e87f5a9dac4c
454
package com.matheusicaro.course.fullstack.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.matheusicaro.course.fullstack.domain.Client; @Repository public interface ClientRepository extends JpaRepository<Client, Integer> { @Transactional(readOnly = true) Client findByEmail (String email); }
28.375
74
0.837004
b53101534c8820a8f440de1406a29d70b25cf003
126
class LambdaExpression { public void foo() { new ArrayList<String>().forEach((x) -> System.out.<caret>println(x)); } }
25.2
73
0.650794
f002606cf6c4d8cf38f1d57ff4307a8546955733
236
package tgits.random.dice; import javax.inject.Singleton; @Singleton public final class D12 extends Dice { public D12() { super(); } @Override public int numberOfPossibleValues() { return 12; } }
13.882353
41
0.627119
5eb1f0b36deb986540158073886a5809242974cc
829
package me.j360.dubbo.modules.util.base; import org.apache.commons.lang3.EnumUtils; import java.util.EnumSet; /** * 枚举工具集 * * @author calvin * */ public class EnumUtil { /** * 将若干个枚举值转换为long,用于使用long保存多个选项的情况. */ public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final Iterable<? extends E> values) { return EnumUtils.generateBitVector(enumClass, values); } /** * 将若干个枚举值转换为long,用于使用long保存多个选项的情况. */ public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final E... values) { return EnumUtils.generateBitVector(enumClass, values); } /** * long重新解析为若干个枚举值,用于使用long保存多个选项的情况. */ public static <E extends Enum<E>> EnumSet<E> processBits(final Class<E> enumClass, final long value) { return EnumUtils.processBitVector(enumClass, value); } }
22.405405
116
0.721351
c98200f7462cd72b409acfc3a048de9339b2c10f
2,934
package seedu.address.ui; import java.util.Objects; import java.util.function.Consumer; import java.util.logging.Logger; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.Region; import seedu.address.commons.core.LogsCenter; import seedu.address.model.ClassForPrinting; import seedu.address.model.moduletaken.ModuleTaken; /** * Panel containing the list of persons. */ public class ModuleTakenListPanel extends UiPart<Region> { private static final String FXML = "ModuleTakenListPanel.fxml"; private final Logger logger = LogsCenter.getLogger(ModuleTakenListPanel.class); @FXML private ListView<ModuleTaken> moduleTakenListView; public ModuleTakenListPanel(ObservableList<ModuleTaken> moduleTakenList, ObservableValue<ClassForPrinting> selectedModuleTaken, Consumer<ClassForPrinting> onSelectedModuleTakenChange) { super(FXML); moduleTakenListView.setItems(moduleTakenList); moduleTakenListView.setCellFactory(listView -> new ModuleTakenListViewCell()); moduleTakenListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { logger.fine("Selection in moduleTaken list panel changed to : '" + newValue + "'"); onSelectedModuleTakenChange.accept(newValue); }); selectedModuleTaken.addListener((observable, oldValue, newValue) -> { logger.fine("Selected moduleTaken changed to: " + newValue); // Don't modify selection if we are already selecting the selected moduleTaken, // otherwise we would have an infinite loop. if (Objects.equals(moduleTakenListView.getSelectionModel().getSelectedItem(), newValue)) { return; } if (newValue == null) { moduleTakenListView.getSelectionModel().clearSelection(); } else { int index = moduleTakenListView.getItems().indexOf(newValue); moduleTakenListView.scrollTo(index); moduleTakenListView.getSelectionModel().clearAndSelect(index); } }); } /** * Custom {@code ListCell} that displays the graphics of a {@code ModuleTaken} using a {@code ModuleTakenCard}. */ class ModuleTakenListViewCell extends ListCell<ModuleTaken> { @Override protected void updateItem(ModuleTaken moduleTaken, boolean empty) { super.updateItem(moduleTaken, empty); if (empty || moduleTaken == null) { setGraphic(null); setText(null); } else { setGraphic(new ModuleTakenCard(moduleTaken, getIndex() + 1).getRoot()); } } } }
39.648649
120
0.668371
3f5db7f36f8b447d6a095241e3c6f2bc2c808647
2,365
package com.ridebuddy.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.annotation.PostConstruct; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import com.ridebuddy.util.models.MailMessage; @Component public class SendMail { private static final Logger logger = Logger.getLogger(SendMail.class); private Session session; @PostConstruct private void init() { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); InputStream is = this.getClass().getResourceAsStream("/mail.properties"); Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { logger.error(e); } final String username = properties.getProperty("username"); final String password = properties.getProperty("password"); if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { throw new RuntimeException( "Could not instantiate SendMail component. Username/password not found"); } session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } public boolean sendMail(MailMessage mailMessage) { Message message = new MimeMessage(session); logger.info("Sending message: " + mailMessage); try { message.setFrom(new InternetAddress(mailMessage.getFrom())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailMessage.getTo())); message.setSubject(mailMessage.getSubject()); message.setText(mailMessage.getBody()); message.setContent(mailMessage.getBody(), "text/html; charset=UTF-8"); Transport.send(message); } catch (MessagingException e) { logger.error("Exception while sending mail message: " + mailMessage, e); return false; } return true; } }
29.5625
78
0.75222
950fab1c504330173bf0855a9a709c9c52c48616
1,248
package com.su.controller; import com.su.service.IShortUrlService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.hibernate.validator.constraints.URL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author hejian */ @Api(tags = "短链接") @RestController @RequestMapping("/url") @Validated public class ShortUrlController { @Autowired private IShortUrlService shortUrlService; @ApiOperation("获取短链接") @GetMapping("/shortUrl") public String getShortUrl(@URL @ApiParam(value = "长连接") @RequestParam("url") String url) { return shortUrlService.getShortUrl(url); } @ApiOperation("获取长链接") @GetMapping("/longUrl") public String getLongUrl(@URL @ApiParam(value = "短连接") @RequestParam("url") String url) { return shortUrlService.getLongUrl(url); } }
32
95
0.742788
52f199d55f71763a77871502e8c764d92e5ff816
6,762
/* * COPYRIGHT NOTICE * Copyright (C) 2015, ticktick <[email protected]> * https://github.com/Jhuster/ImageCropper * * @license under the Apache License, Version 2.0 * * @file CropImageActivity.java * @brief Image Cropper Activity * * @version 1.0 * @author ticktick * @date 2015/01/09 */ package com.wudebin.bicyclerental.imagecropper; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.afollestad.materialdialogs.MaterialDialog; import java.io.Closeable; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.wudebin.bicyclerental.R; public class CropImageActivity extends Activity { private Bitmap mBitmap; private Uri mInputPath = null; private Uri mOutputPath = null; private CropImageView mCropImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_cropimage); mCropImageView = (CropImageView)findViewById(R.id.CropWindow); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras == null) { setResult(RESULT_CANCELED); return; } mInputPath = intent.getData(); mOutputPath = extras.getParcelable(MediaStore.EXTRA_OUTPUT); if( mInputPath == null || mOutputPath == null ) { setResult(RESULT_CANCELED); finish(); return; } mBitmap = loadBitmapWithInSample(mInputPath); if( mBitmap == null ) { setResult(RESULT_CANCELED); finish(); return; } mCropImageView.initialize(mBitmap,getCropParam(intent)); } @Override protected void onDestroy() { if( mBitmap != null ) { mBitmap.recycle(); } mCropImageView.destroy(); super.onDestroy(); } public void onClickRotate(View v) { mCropImageView.rotate(); mCropImageView.invalidate(); } public void onClickReset(View v) { setResult(RESULT_CANCELED); finish(); } public void onClickCrop(View v) { mCropImageView.crop(); new SaveImageTask().execute(mCropImageView.getCropBitmap()); } private class SaveImageTask extends AsyncTask<Bitmap,Void,Boolean> { private MaterialDialog mDialog; private SaveImageTask() { mDialog = new MaterialDialog.Builder(CropImageActivity.this) .progress(true,0) .content("正在上传") .build(); } @Override protected void onPreExecute() { mDialog.show(); } @Override protected void onPostExecute(Boolean result) { if(mDialog.isShowing()){ mDialog.dismiss(); } setResult(RESULT_OK, new Intent().putExtra(MediaStore.EXTRA_OUTPUT,mOutputPath)); finish(); } @Override protected Boolean doInBackground(Bitmap... params) { OutputStream outputStream = null; try { outputStream = getContentResolver().openOutputStream(mOutputPath); if (outputStream != null) { params[0].compress(Bitmap.CompressFormat.JPEG, 90, outputStream); } } catch (IOException e) { } finally { closeSilently(outputStream); } return Boolean.TRUE; } } protected Bitmap loadBitmapWithInSample( Uri uri ) { final int MAX_VIEW_SIZE = 1024; InputStream in = null; try { in = getContentResolver().openInputStream(uri); BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(in, null, o); in.close(); int scale = 1; if (o.outHeight > MAX_VIEW_SIZE || o.outWidth > MAX_VIEW_SIZE ) { scale = (int) Math.pow(2, (int) Math.round(Math.log(MAX_VIEW_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; in = getContentResolver().openInputStream(uri); Bitmap b = BitmapFactory.decodeStream(in, null, o2); in.close(); return b; } catch (FileNotFoundException e) { } catch (IOException e) { } return null; } protected static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { } } public static CropParam getCropParam(Intent intent) { CropParam params = new CropParam(); Bundle extras = intent.getExtras(); if (extras != null) { if( extras.containsKey(CropIntent.ASPECT_X) && extras.containsKey(CropIntent.ASPECT_Y) ) { params.mAspectX = extras.getInt(CropIntent.ASPECT_X); params.mAspectY = extras.getInt(CropIntent.ASPECT_Y); } if( extras.containsKey(CropIntent.OUTPUT_X) && extras.containsKey(CropIntent.OUTPUT_Y) ) { params.mOutputX = extras.getInt(CropIntent.OUTPUT_X); params.mOutputY = extras.getInt(CropIntent.OUTPUT_Y); } if( extras.containsKey(CropIntent.MAX_OUTPUT_X) && extras.containsKey(CropIntent.MAX_OUTPUT_Y) ) { params.mMaxOutputX = extras.getInt(CropIntent.MAX_OUTPUT_X); params.mMaxOutputY = extras.getInt(CropIntent.MAX_OUTPUT_Y); } } return params; } }
32.825243
147
0.565957
7f6c852b25b0045ba88dfaf51c924ea865780727
9,424
package org.riversun.d6.core; import static org.junit.Assert.assertEquals; import java.sql.Time; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TestName; /** * * Test for WhereCondition class * * @author Tom Misawa ([email protected]) */ public class TestWhereCondition { @Rule public TestName name = new TestName(); @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public void method() { WhereCondition w1 = new WhereCondition().Col("user_id").Equals().Val("?").AND().Col("user_name").Equals().Val("bluemane"); WhereCondition w2 = new WhereCondition().Col("aid").Equals().Val("?").AND().Col("bid").Equals().Val("bluemane"); // w1.AND(); // w1.WHERE(w2); WhereCondition w = new WhereCondition(); w.WHERE(w1).AND().WHERE(w2); } @Test public void test_whereCondition_00_basic() throws Exception { // basic where SQL final int userId = 1; final WhereCondition whereCondition = new WhereCondition().Col("user_id").Equals().Val(userId); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE user_id='1'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_01_basic_use_AND() throws Exception { // use 'AND' condition final int userId = 1; final String userName = "blackman"; final WhereCondition whereCondition = new WhereCondition().Col("user_id").Equals().Val(userId).AND().Col("user_name").Equals().Val(userName); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE user_id='1' AND user_name='blackman'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_02_basic_use_OR() throws Exception { // use 'OR' condition final int userId1 = 1; final int userId2 = 2; final WhereCondition whereCondition = new WhereCondition().Col("user_id").Equals().Val(userId1).OR().Col("user_id").Equals().Val(userId2); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE user_id='1' OR user_id='2'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_03_basic_use_WILD_CARD() throws Exception { // use wild card for prepared statement final WhereCondition whereCondition = new WhereCondition().Col("user_id").Equals().Val("?"); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE user_id= ?"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_03_basic_use_WILD_CARD_02() throws Exception { // use wild card for prepared statement final WhereCondition whereCondition = new WhereCondition().Col("user_id").Equals().ValWildCard(); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE user_id= ?"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_10_operator_more_than() throws Exception { // uses operator '>' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").MoreThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time>'13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_11_operator_more_equals_than() throws Exception { // uses operator '>=' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").MoreEqualsThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time>='13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_12_operator_less_than() throws Exception { // uses operator '<' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").LessThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time<'13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_13_operator_less_than() throws Exception { // uses operator '<' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").LessThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time<'13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_14_operator_less_equals_than() throws Exception { // uses operator '<=' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").LessEqualsThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time<='13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_20_condition_less_equals_than() throws Exception { // uses operator '<=' final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").LessEqualsThan().Val(time); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time<='13:00:10'"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_30_composit_00() throws Exception { // composit = packaged where block final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").MoreThan().Val(time).AND().WHERE(new WhereCondition().Col("school_id").Equals().Val(1)); final String generatedSQL = whereCondition.toSql(); final String expectedSQL = "WHERE birth_time>'13:00:10' AND (school_id='1')"; assertEquals(expectedSQL, generatedSQL); } @Test public void test_whereCondition_31_composit_01() throws Exception { // composit = packaged where block final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition1 = new WhereCondition().Col("birth_time").MoreThan().Val(time).OR().Col("married_flag").Equals().Val(1); final WhereCondition whereCondition2 = new WhereCondition().Col("school_id").Equals().Val(1); final WhereCondition compositWhereCondition = new WhereCondition(); compositWhereCondition.WHERE(whereCondition1).AND().WHERE(whereCondition2); final String generatedSQL = compositWhereCondition.toSql(); final String expectedSQL = "WHERE (birth_time>'13:00:10' OR married_flag='1') AND (school_id='1')"; assertEquals(expectedSQL, generatedSQL); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void test_whereCondition_90_syntax_error_01() throws Exception { // check the where condition's method order is incorrect. expectedException.expect(D6RuntimeException.class); final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").Val(time); } @Test public void test_whereCondition_91_syntax_error_02() throws Exception { // check the where condition's method order is incorrect. expectedException.expect(D6RuntimeException.class); final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Col("birth_time").Equals().Val(time).Val(time); } @Test public void test_whereCondition_92_syntax_error_03() throws Exception { // check the where condition's method order is incorrect. expectedException.expect(D6RuntimeException.class); final java.sql.Time time = new Time(13, 00, 10); final WhereCondition whereCondition = new WhereCondition().Val(time); } @Test public void test_whereCondition_93_syntax_error_04() throws Exception { // Statement ends with half-baked state expectedException.expect(D6RuntimeException.class); final java.sql.Time time = new Time(13, 00, 10); final String SQL = new WhereCondition().Col("birth_time").Equals().Val(time).AND().toSql(); } }
32.608997
174
0.653969
c1f1316850a1522c678ba8a2db4a667b30160218
57
package io.github.suxil.dict.api.converter; // 业务数据转字典数据
19
43
0.789474
e140d6091ef402f837ae116e7ab3a9050f177749
785
package com.eloli.mbt.core.channel.clientPacket; import com.eloli.sodioncore.channel.ClientPacket; import com.eloli.sodioncore.channel.util.FieldWrapper; import com.eloli.sodioncore.channel.util.Priority; import java.util.List; public class DeeperTeleportPacket extends ClientPacket { public static List<FieldWrapper> fieldWrapperList = resolveFieldWrapperList(DeeperTeleportPacket.class); @Priority(0) public String destination; @Priority(1) public String token; public DeeperTeleportPacket() { } public DeeperTeleportPacket(String destination, String token) { this.destination = destination; this.token = token; } @Override public List<FieldWrapper> getFieldWrapperList() { return fieldWrapperList; } }
25.322581
108
0.742675
97eb0f1b89a00f2ba3e35922c5a032b4cf5a7942
8,478
package org.appng.application.scheduler.configuration; import java.io.IOException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Properties; import javax.sql.DataSource; import org.appng.api.Platform; import org.appng.api.ScheduledJob; import org.appng.application.scheduler.Constants; import org.appng.application.scheduler.job.IndexJob; import org.appng.application.scheduler.job.JobRecordHouseKeepingJob; import org.appng.application.scheduler.quartz.DriverDelegateWrapper; import org.appng.application.scheduler.quartz.SpringQuartzSchedulerFactory; import org.appng.application.scheduler.service.JobRecordService; import org.appng.scheduler.openapi.model.JobState.TimeunitEnum; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.jdbcjobstore.HSQLDBDelegate; import org.quartz.impl.jdbcjobstore.MSSQLDelegate; import org.quartz.impl.jdbcjobstore.PostgreSQLDelegate; import org.quartz.impl.jdbcjobstore.StdJDBCDelegate; import org.quartz.simpl.HostnameInstanceIdGenerator; import org.quartz.spi.JobFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import lombok.extern.slf4j.Slf4j; @Slf4j @Configuration public class SchedulerConfig { private static final String SCHEDULER_PREFIX = "Scheduler_"; private static final String JOBSTORE_PREFIX = "org.quartz.jobStore."; private static final String CLUSTER_CHECKIN_INTERVAL = JOBSTORE_PREFIX + "clusterCheckinInterval"; private static final String DRIVER_DELEGATE_CLASS = JOBSTORE_PREFIX + "driverDelegateClass"; private static final String DRIVER_DELEGATE_INIT_STRING = JOBSTORE_PREFIX + "driverDelegateInitString"; private static final String IS_CLUSTERED = JOBSTORE_PREFIX + "isClustered"; private static final String SELECT_WITH_LOCK_SQL = JOBSTORE_PREFIX + "selectWithLockSQL"; private static final String MSSQL_LOCK_SQL = "SELECT * FROM {0}LOCKS WITH (UPDLOCK,ROWLOCK) WHERE SCHED_NAME = {1} AND LOCK_NAME = ?"; private static final String MYSQL_LOCK_SQL = "SELECT * FROM {0}LOCKS WHERE SCHED_NAME = {1} AND LOCK_NAME = ? LOCK IN SHARE MODE;"; @Bean public DataSourceTransactionManager quartzTransactionManager(@Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean public SchedulerFactoryBean scheduler(JobFactory jobFactory, @Value("${quartzDriverDelegate}") String quartzDriverDelegate, @Value("${site.name}") String siteName, DataSourceTransactionManager quartzTransactionManager, Properties quartzProperties) throws SQLException { DataSource dataSource = quartzTransactionManager.getDataSource(); SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setSchedulerName(SCHEDULER_PREFIX + siteName); scheduler.setAutoStartup(false); scheduler.setOverwriteExistingJobs(true); scheduler.setDataSource(dataSource); scheduler.setTransactionManager(quartzTransactionManager); scheduler.setJobFactory(jobFactory); String driverDelegate = StdJDBCDelegate.class.getName(); String lockSql = null; if (!quartzProperties.contains(SELECT_WITH_LOCK_SQL)) { try (Connection connection = dataSource.getConnection()) { String databaseProductName = connection.getMetaData().getDatabaseProductName().toLowerCase(); if (databaseProductName.contains("mysql") || databaseProductName.contains("mariadb")) { lockSql = MYSQL_LOCK_SQL; } else if (databaseProductName.contains("mssql")) { lockSql = MSSQL_LOCK_SQL; driverDelegate = MSSQLDelegate.class.getName(); } else if (databaseProductName.contains("postgres")) { driverDelegate = PostgreSQLDelegate.class.getName(); } else if (databaseProductName.contains("hsql")) { // http://www.hsqldb.org/doc/2.0/guide/sessions-chapt.html#snc_tx_mvcc try (CallableStatement stmt = connection.prepareCall("SET DATABASE TRANSACTION CONTROL MVCC")) { stmt.execute(); } driverDelegate = HSQLDBDelegate.class.getName(); } } } if (null != lockSql) { quartzProperties.put(SELECT_WITH_LOCK_SQL, lockSql); } quartzProperties.put(DRIVER_DELEGATE_INIT_STRING, "delegate=" + driverDelegate); if (log.isDebugEnabled()) { log.debug("Quartz properties: {}", quartzProperties); } scheduler.setQuartzProperties(quartzProperties); return scheduler; } @Bean public JobFactory jobFactory() { return new SpringQuartzSchedulerFactory(); } @Bean Properties quartzProperties(@Value("${site.name}") String siteName, @Value("${platform.messagingEnabled:false}") boolean clustered, @Value("${quartzClusterCheckinInterval:20000}") String clusterCheckinInterval) { Properties props = new Properties(); props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, SCHEDULER_PREFIX + siteName); props.put(StdSchedulerFactory.PROP_SCHED_THREAD_NAME, SCHEDULER_PREFIX + siteName); props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_ID, "AUTO"); props.put(StdSchedulerFactory.PROP_SCHED_INTERRUPT_JOBS_ON_SHUTDOWN, "true"); props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS, HostnameInstanceIdGenerator.class.getName()); props.put("org.quartz.threadPool.threadCount", "3"); props.put("org.quartz.scheduler.skipUpdateCheck", "true"); props.put(IS_CLUSTERED, String.valueOf(clustered)); props.put(CLUSTER_CHECKIN_INTERVAL, clusterCheckinInterval); props.put(DRIVER_DELEGATE_CLASS, DriverDelegateWrapper.class.getName()); return props; } @Bean public ScheduledJob indexJob(@Value("${indexEnabled}") boolean indexEnabled, @Value("${indexExpression}") String indexExpression, @Value("${platform.jspFileType}") String jspFileType) { IndexJob indexJob = new IndexJob(); indexJob.setJobDataMap(new HashMap<>()); indexJob.setDescription("Indexing of JSPs and static content"); indexJob.getJobDataMap().put(Constants.JOB_ENABLED, indexEnabled); indexJob.getJobDataMap().put(Constants.JOB_CRON_EXPRESSION, indexExpression); indexJob.getJobDataMap().put(Platform.Property.JSP_FILE_TYPE, jspFileType); indexJob.getJobDataMap().put(Constants.THRESHOLD_TIMEUNIT, TimeunitEnum.DAY.name()); indexJob.getJobDataMap().put(Constants.THRESHOLD_ERROR, 1); return indexJob; } @Bean public ScheduledJob houseKeepingJob(JobRecordService jobRecordService, @Value("${houseKeepingEnabled}") boolean houseKeepingEnabled, @Value("${houseKeepingExpression}") String houseKeepingExpression) { JobRecordHouseKeepingJob houseKeepingJob = new JobRecordHouseKeepingJob(jobRecordService); houseKeepingJob.setJobDataMap(new HashMap<>()); houseKeepingJob.getJobDataMap().put(Constants.JOB_ENABLED, houseKeepingEnabled); houseKeepingJob.getJobDataMap().put(Constants.JOB_CRON_EXPRESSION, houseKeepingExpression); houseKeepingJob.getJobDataMap().put(Constants.JOB_RUN_ONCE, true); return houseKeepingJob; } @Bean public ObjectMapper objectMapper() { Module dateModule = new SimpleModule().addSerializer(OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() { public void serialize(OffsetDateTime value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { if (value != null) { jsonGenerator.writeString(DateTimeFormatter.ISO_DATE_TIME.format(value)); } } }); return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).registerModule(dateModule); } @Bean public MappingJackson2HttpMessageConverter jsonConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } }
44.857143
135
0.801958
80b2d9698649e9365eebc7e764e8d2fb37030ad1
662
package pokecube.core.world.gen.jigsaw; import java.util.Random; import com.mojang.serialization.Codec; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ISeedReader; import net.minecraft.world.gen.ChunkGenerator; import net.minecraft.world.gen.feature.Feature; public class CustomJigsawFeature extends Feature<JigsawConfig> { public CustomJigsawFeature(final Codec<JigsawConfig> codec) { super(codec); } @Override public boolean place(final ISeedReader reader, final ChunkGenerator generator, final Random rand, final BlockPos pos, final JigsawConfig config) { return false; } }
22.827586
121
0.744713
2c90a3a7b44724bdb5124a0431b93776fcb09141
4,960
package io.onedev.server.git; import java.io.IOException; import java.net.InetAddress; import java.util.Enumeration; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.util.ThreadContext; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.RefUpdate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.onedev.launcher.loader.ListenerRegistry; import io.onedev.server.event.RefUpdated; import io.onedev.server.manager.ProjectManager; import io.onedev.server.model.Project; import io.onedev.server.model.User; import io.onedev.server.persistence.UnitOfWork; import io.onedev.utils.StringUtils; import com.google.common.base.Preconditions; @SuppressWarnings("serial") @Singleton public class GitPostReceiveCallback extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(GitPostReceiveCallback.class); public static final String PATH = "/git-postreceive-callback"; private final ProjectManager projectManager; private final ListenerRegistry listenerRegistry; private final UnitOfWork unitOfWork; @Inject public GitPostReceiveCallback(ProjectManager projectManager, UnitOfWork unitOfWork, ListenerRegistry listenerRegistry) { this.projectManager = projectManager; this.unitOfWork = unitOfWork; this.listenerRegistry = listenerRegistry; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientIp = request.getHeader("X-Forwarded-For"); if (clientIp == null) clientIp = request.getRemoteAddr(); if (!InetAddress.getByName(clientIp).isLoopbackAddress()) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Git hook callbacks can only be accessed from localhost."); return; } List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/"); Preconditions.checkState(fields.size() == 2); Long projectId = Long.valueOf(fields.get(0)); Long userId = Long.valueOf(fields.get(1)); String refUpdateInfo = null; Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (paramName.contains(" ")) { refUpdateInfo = paramName; } } Preconditions.checkState(refUpdateInfo != null, "Git ref update information is not available"); /* * If multiple refs are updated, the hook stdin will put each ref update info into * a separate line, however the line breaks is omitted when forward the hook stdin * to curl via "@-", below logic is used to parse these info correctly even * without line breaks. */ refUpdateInfo = StringUtils.reverse(StringUtils.remove(refUpdateInfo, '\n')); fields.clear(); fields.addAll(StringUtils.splitAndTrim(refUpdateInfo, " ")); unitOfWork.doAsync(new Runnable() { @Override public void run() { ThreadContext.bind(User.asSubject(userId)); try { Project project = projectManager.load(projectId); int pos = 0; while (true) { String refName = StringUtils.reverse(fields.get(pos)); pos++; ObjectId newObjectId = ObjectId.fromString(StringUtils.reverse(fields.get(pos))); pos++; String field = fields.get(pos); ObjectId oldObjectId = ObjectId.fromString(StringUtils.reverse(field.substring(0, 40))); if (!newObjectId.equals(ObjectId.zeroId())) { project.cacheObjectId(refName, newObjectId); } else { newObjectId = ObjectId.zeroId(); project.cacheObjectId(refName, null); } String branch = GitUtils.ref2branch(refName); if (branch != null && project.getDefaultBranch() == null) { RefUpdate refUpdate = GitUtils.getRefUpdate(project.getRepository(), "HEAD"); GitUtils.linkRef(refUpdate, refName); } listenerRegistry.post(new RefUpdated(project, refName, oldObjectId, newObjectId)); field = field.substring(40); if (field.length() == 0) break; else fields.set(pos, field); } } catch (Exception e) { logger.error("Error executing post-receive callback", e); } finally { ThreadContext.unbindSubject(); } } }); } }
35.683453
124
0.652823
e986359c92418878f0d3b2052c66b6eda80213bd
7,339
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2017 The ZAP Development Team * * 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.zaproxy.zap.extension.jxbrowser; import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserContext; import com.teamdev.jxbrowser.chromium.BrowserContextParams; import com.teamdev.jxbrowser.chromium.CustomProxyConfig; import com.teamdev.jxbrowser.chromium.events.ConsoleEvent; import com.teamdev.jxbrowser.chromium.events.ConsoleListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.nio.file.Files; import javax.swing.ImageIcon; import javax.swing.JButton; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.model.SiteNode; import org.parosproxy.paros.view.View; import org.zaproxy.zap.extension.help.ExtensionHelp; import org.zaproxy.zap.utils.DisplayUtils; import org.zaproxy.zap.view.NodeSelectDialog; public class ZapBrowserPanel extends BrowserPanel { private static final ImageIcon BACK_ICON = DisplayUtils.getScaledIcon( new ImageIcon( ZapBrowserPanel.class.getResource( ExtensionJxBrowser.RESOURCES + "/arrow-180-medium.png"))); private static final ImageIcon FORWARD_ICON = DisplayUtils.getScaledIcon( new ImageIcon( ZapBrowserPanel.class.getResource( ExtensionJxBrowser.RESOURCES + "/arrow-000-medium.png"))); private static final ImageIcon SITES_ICON = DisplayUtils.getScaledIcon( new ImageIcon( View.class.getResource("/resource/icon/16/094.png"))); // Globe icon private static final Logger LOGGER = Logger.getLogger(ZapBrowserPanel.class); private static final long serialVersionUID = 1L; private BrowserFrame frame; private JButton[] extraButtons; public ZapBrowserPanel(BrowserFrame frame, boolean incToolbar) { super(frame, incToolbar); this.frame = frame; } public ZapBrowserPanel(BrowserFrame frame, boolean incToolbar, Browser browser) { super(frame, incToolbar, browser); this.frame = frame; } @Override public Browser getBrowser() { if (browser == null) { try { // Always proxy through ZAP File dataFile = Files.createTempDirectory("zap-jxbrowser").toFile(); dataFile.deleteOnExit(); BrowserContextParams contextParams = new BrowserContextParams(dataFile.getAbsolutePath()); String hostPort = Model.getSingleton().getOptionsParam().getProxyParam().getProxyIp() + ":" + Model.getSingleton() .getOptionsParam() .getProxyParam() .getProxyPort(); String proxyRules = "http=" + hostPort + ";https=" + hostPort; contextParams.setProxyConfig(new CustomProxyConfig(proxyRules)); browser = new Browser(new BrowserContext(contextParams)); } catch (IOException e) { LOGGER.error(e.getMessage(), e); browser = new Browser(); } browser.addConsoleListener( new ConsoleListener() { @Override public void onMessage(ConsoleEvent event) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "jxBrowser Console Event - Level: " + event.getLevel() + " - Message: " + event.getMessage()); } } }); } return browser; } @Override protected JButton getBackButton() { if (backButton == null) { backButton = new JButton(); backButton.setIcon(BACK_ICON); backButton.setToolTipText(Constant.messages.getString("jxbrowser.browser.button.back")); } return backButton; } @Override protected JButton getForwardButton() { if (forwardButton == null) { forwardButton = new JButton(); forwardButton.setIcon(FORWARD_ICON); forwardButton.setToolTipText( Constant.messages.getString("jxbrowser.browser.button.fwds")); } return forwardButton; } @Override protected JButton[] getExtraButtons() { if (extraButtons == null) { JButton sitesButton = new JButton(); sitesButton.setIcon(SITES_ICON); sitesButton.setToolTipText( Constant.messages.getString("jxbrowser.browser.button.sites")); sitesButton.addActionListener( new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { NodeSelectDialog nsd = new NodeSelectDialog(frame); nsd.setAllowRoot(false); SiteNode node = nsd.showDialog((SiteNode) null); if (node != null && node.getHistoryReference() != null) { getBrowser() .loadURL(node.getHistoryReference().getURI().toString()); } } }); extraButtons = new JButton[] {sitesButton}; } return extraButtons; } @Override protected JButton getHelpButton() { if (helpButton == null) { helpButton = new JButton(); helpButton.setIcon(ExtensionHelp.getHelpIcon()); helpButton.setToolTipText(Constant.messages.getString("jxbrowser.browser.button.help")); helpButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ExtensionHelp.showHelp("jxbrowser"); } }); } return helpButton; } }
39.67027
100
0.56738
9f9430c7ba8a4906d6423df276de52898f953baf
3,334
package com.purvotara.airbnbmapexample.ui.activity; import android.graphics.Color; import android.graphics.PorterDuff; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.purvotara.airbnbmapexample.R; import com.purvotara.airbnbmapexample.constants.NetworkConstants; import com.purvotara.airbnbmapexample.controller.BaseInterface; import com.purvotara.airbnbmapexample.model.AddressModel; import com.purvotara.airbnbmapexample.ui.adapter.ListViewAdapter; import java.util.ArrayList; import java.util.List; public class ListViewActivity extends AppCompatActivity { ProgressBar mLoadingMoreDataProgress; private RecyclerView mRecyclerView; private ListViewAdapter mAdapter; private LinearLayoutManager mLayoutManager; // private Places mPlaces; private AddressModel mAddressModel; private int mPageNumber = 1; private boolean mHasMore = true; private List<AddressModel> mAddressList = new ArrayList<AddressModel>(); private SwipeRefreshLayout mSwipeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); getSupportActionBar().setTitle("List View"); mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); mRecyclerView = (RecyclerView) findViewById(R.id.rv_lisiting); mLoadingMoreDataProgress = (ProgressBar) findViewById(R.id.loading_progress); mLoadingMoreDataProgress.getIndeterminateDrawable().setColorFilter(0xff00b1c7, PorterDuff.Mode.MULTIPLY); mLoadingMoreDataProgress.setVisibility(View.GONE); mRecyclerView.setHasFixedSize(false); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new ListViewAdapter(mAddressList, this); mRecyclerView.setAdapter(mAdapter); mRecyclerView.requestLayout(); mSwipeLayout.setColorSchemeResources(R.color.gomalan_bule_bg); mAddressModel=new AddressModel(this, new BaseInterface() { @Override public void handleNetworkCall(Object object, int requestCode) { if (requestCode == NetworkConstants.ADDRESS_REQUEST) { if (object instanceof ArrayList) { mAddressList = new ArrayList<>(); mAddressList = (ArrayList) object; mAdapter = new ListViewAdapter(mAddressList, ListViewActivity.this); mRecyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } else{ Toast.makeText(ListViewActivity.this, (String)object,Toast.LENGTH_LONG).show(); } } } }); mAddressModel.fetchAddressFromServer(); } }
36.23913
113
0.713257
1dd6f51291fae11398203e926671142269db653b
648
package sonia.scm.plugin; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import java.util.HashSet; import java.util.Set; @Getter @ToString @NoArgsConstructor @EqualsAndHashCode @AllArgsConstructor @XmlAccessorType(XmlAccessType.FIELD) public class ExtensionElement { @XmlElement(name = "class") private String clazz; private String description; private Set<String> requires = new HashSet<>(); }
24
49
0.814815
a18f7e730e4e4979cded26572aac576b0745d559
2,003
/** */ package lasser.sketch; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Text Area</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link lasser.sketch.TextArea#getRows <em>Rows</em>}</li> * <li>{@link lasser.sketch.TextArea#getColumns <em>Columns</em>}</li> * </ul> * </p> * * @see lasser.sketch.SketchPackage#getTextArea() * @model * @generated */ public interface TextArea extends TextWidget { /** * Returns the value of the '<em><b>Rows</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Rows</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Rows</em>' attribute. * @see #setRows(int) * @see lasser.sketch.SketchPackage#getTextArea_Rows() * @model * @generated */ int getRows(); /** * Sets the value of the '{@link lasser.sketch.TextArea#getRows <em>Rows</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Rows</em>' attribute. * @see #getRows() * @generated */ void setRows(int value); /** * Returns the value of the '<em><b>Columns</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Columns</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Columns</em>' attribute. * @see #setColumns(int) * @see lasser.sketch.SketchPackage#getTextArea_Columns() * @model * @generated */ int getColumns(); /** * Sets the value of the '{@link lasser.sketch.TextArea#getColumns <em>Columns</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Columns</em>' attribute. * @see #getColumns() * @generated */ void setColumns(int value); } // TextArea
26.012987
97
0.606091
adc6deb1a525d173518ade28efb7f64b28fc4050
804
public class Magazine extends LibraryItem { /* FIELDS */ private String coverStory; private String issueDate; /* CONSTRUCTOR */ public Magazine(String title, String coverStory, String issueDate) { super(title); this.coverStory = coverStory; this.issueDate = issueDate; } /* METHODS */ public String getCoverStory() { return coverStory; } public void setCoverStory(String coverStory) { this.coverStory = coverStory; } public String getIssueDate() { return issueDate; } public void setIssueDate(String issueDate) { this.issueDate = issueDate; } @Override public String toString() { return "Item Number: " + this.getItemNumber() + " | Magazine Title: " + this.getTitle() + " | Magazine Cover Story: " + coverStory + " | Magazine Issue Date: " + issueDate; } }
21.72973
174
0.696517
b7d63ce1b5763254dc0935426249d55be366e13b
1,146
/** * Copyright (C) 2015 Stubhub. */ package io.bigdime.handler.webhdfs; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; public class HdfsFileNameBuilder { private String prefix; private String channelDesc; private String sourceFileName; private String extension; public HdfsFileNameBuilder withPrefix(String prefix) { this.prefix = prefix; return this; } public HdfsFileNameBuilder withChannelDesc(String channelDesc) { this.channelDesc = channelDesc; return this; } public HdfsFileNameBuilder withSourceFileName(String sourceFileName) { this.sourceFileName = sourceFileName; return this; } public HdfsFileNameBuilder withExtension(String extension) { this.extension = extension; return this; } public String build() { Preconditions.checkNotNull(prefix, "prefix can't be null"); Preconditions.checkNotNull(channelDesc, "channelDesc can't be null"); Preconditions.checkNotNull(extension, "extension can't be null"); if (StringUtils.isBlank(sourceFileName)) { return prefix + channelDesc + extension; } return prefix + sourceFileName + extension; } }
25.466667
71
0.767888
71e5d7ab393a6daf0256c5fd1f04c9e4699461ca
1,723
package fr.cla.wires.core.boxes; import fr.cla.wires.core.Clock; import fr.cla.wires.core.Delay; import fr.cla.wires.core.Wire; import java.util.List; import java.util.function.Function; import java.util.function.UnaryOperator; //@formatter:off /** * -->"Explaining the intention" approach to javadoc: * Does like its parent CollectHomogeneousInputs: " * Use a java.util.stream.Collector to compute the Signal to write to the target Wire * when a Signal on an observed Wires change. * ", * but since here the output type is the same as the the inputs type, * instead of the the more general approach of returning a Collector, * we can simplify to just * returning the {@code BinaryOperator<Boolean> combiner} used by the Collector. * * -->"More formal / JDK style" approach to javadoc: * A CollectHomogeneousInputs whose T type (as in "target", output type) * is the same as its O type (as in "observed", input type). * @param <O> O like "observed". * The type of {@code Signal} that transits on both: * -the observed {@code Wire}s. * -the target {@code Wire} * This means this Box's input is N {@code Wire}s of type {@code O}, * and its output is 1 {@code Wire} of type {@code O}. */ public abstract class CollectHomogeneousInputsToOutputOfSameType<O> extends CollectHomogeneousInputs<O, O> { protected CollectHomogeneousInputsToOutputOfSameType(List<Wire<O>> ins, Wire<O> out, Clock clock) { this(ins, out, clock, DEFAULT_DELAY); } protected CollectHomogeneousInputsToOutputOfSameType(List<Wire<O>> ins, Wire<O> out, Clock clock, Delay delay) { super(ins, out, clock, delay); } } //@formatter:on
37.456522
116
0.692977
dfbeb5c4ce417c453c7612dfa09b19de21e1a6aa
1,144
package iterator.external; import iterator.Candidate; import iterator.internal.AllCandidates; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; public class CertificatedCandidates implements Iterator<Candidate> { private AllCandidates1 alls; private Enumeration<Candidate> ec; private String certType; private Candidate nextCandidate; public CertificatedCandidates(AllCandidates1 alls, String certType) { // TODO Auto-generated constructor stub this.alls = alls; this.certType = certType; this.ec = this.alls.getAllCandidates(); } @Override public boolean hasNext() { // TODO Auto-generated method stub nextCandidate = null; while (ec.hasMoreElements()){ Candidate can = ec.nextElement(); if (certType.equals(can.getCertificate())){ nextCandidate = can; break; } } return (nextCandidate != null); } @Override public Candidate next() { // TODO Auto-generated method stub if (nextCandidate == null) throw new NoSuchElementException(); return nextCandidate; } @Override public void remove() { // TODO Auto-generated method stub } }
24.340426
70
0.743881
f85b7a708e1e9af470f93446b7e127fcf321c0d8
5,277
/* * Copyright by 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 wallettemplate; import javafx.scene.layout.HBox; import org.beyondcoinj.core.*; import org.beyondcoinj.wallet.SendRequest; import org.beyondcoinj.wallet.Wallet; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import org.spongycastle.crypto.params.KeyParameter; import wallettemplate.controls.BitcoinAddressValidator; import wallettemplate.utils.TextFieldValidator; import wallettemplate.utils.WTUtils; import static com.google.common.base.Preconditions.checkState; import static wallettemplate.utils.GuiUtils.*; import javax.annotation.Nullable; public class SendMoneyController { public Button sendBtn; public Button cancelBtn; public TextField address; public Label titleLabel; public TextField amountEdit; public Label btcLabel; public Main.OverlayUI overlayUI; private Wallet.SendResult sendResult; private KeyParameter aesKey; // Called by FXMLLoader public void initialize() { Coin balance = Main.bitcoin.wallet().getBalance(); checkState(!balance.isZero()); new BitcoinAddressValidator(Main.params, address, sendBtn); new TextFieldValidator(amountEdit, text -> !WTUtils.didThrow(() -> checkState(Coin.parseCoin(text).compareTo(balance) <= 0))); amountEdit.setText(balance.toPlainString()); } public void cancel(ActionEvent event) { overlayUI.done(); } public void send(ActionEvent event) { // Address exception cannot happen as we validated it beforehand. try { Coin amount = Coin.parseCoin(amountEdit.getText()); Address destination = Address.fromBase58(Main.params, address.getText()); SendRequest req; if (amount.equals(Main.bitcoin.wallet().getBalance())) req = SendRequest.emptyWallet(destination); else req = SendRequest.to(destination, amount); req.aesKey = aesKey; sendResult = Main.bitcoin.wallet().sendCoins(req); Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() { @Override public void onSuccess(@Nullable Transaction result) { checkGuiThread(); overlayUI.done(); } @Override public void onFailure(Throwable t) { // We died trying to empty the wallet. crashAlert(t); } }); sendResult.tx.getConfidence().addEventListener((tx, reason) -> { if (reason == TransactionConfidence.Listener.ChangeReason.SEEN_PEERS) updateTitleForBroadcast(); }); sendBtn.setDisable(true); address.setDisable(true); ((HBox)amountEdit.getParent()).getChildren().remove(amountEdit); ((HBox)btcLabel.getParent()).getChildren().remove(btcLabel); updateTitleForBroadcast(); } catch (InsufficientMoneyException e) { informationalAlert("Could not empty the wallet", "You may have too little money left in the wallet to make a transaction."); overlayUI.done(); } catch (ECKey.KeyIsEncryptedException e) { askForPasswordAndRetry(); } } private void askForPasswordAndRetry() { Main.OverlayUI<WalletPasswordController> pwd = Main.instance.overlayUI("wallet_password.fxml"); final String addressStr = address.getText(); final String amountStr = amountEdit.getText(); pwd.controller.aesKeyProperty().addListener((observable, old, cur) -> { // We only get here if the user found the right password. If they don't or they cancel, we end up back on // the main UI screen. By now the send money screen is history so we must recreate it. checkGuiThread(); Main.OverlayUI<SendMoneyController> screen = Main.instance.overlayUI("send_money.fxml"); screen.controller.aesKey = cur; screen.controller.address.setText(addressStr); screen.controller.amountEdit.setText(amountStr); screen.controller.send(null); }); } private void updateTitleForBroadcast() { final int peers = sendResult.tx.getConfidence().numBroadcastPeers(); titleLabel.setText(String.format("Broadcasting ... seen by %d peers", peers)); } }
40.282443
117
0.662877
f22b6acede0664cf81fbea08e34ab8c93a9a4f6b
962
package Week1; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Week1Exercise3 { private static long nthFibo(long a0, long a1, long a2, int n) { if (n == 0) return a0; if (n == 1) return a1; if (n == 2) return a2; for (int i = 1; i <= n - 2; ++i) { long temp = a2 + a1 - a0; a0 = a1; a1 = a2; a2 = temp; } return a2; } public static void main(String[] args) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) { BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); String[] inputs = br.readLine().trim().split(" "); long a0 = Long.parseLong(inputs[0]); long a1 = Long.parseLong(inputs[1]); long a2 = Long.parseLong(inputs[2]); int n = Integer.parseInt(inputs[3]); bw.write(nthFibo(a0, a1, a2, n) + "\n"); bw.close(); } } }
22.904762
77
0.633056
1e842c5986747e8eb4ff0c1f2e23cc2db8c94287
1,961
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.htrace.core; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class TestTracerId { private void testTracerIdImpl(String expected, String fmt) { assertEquals(expected, new TracerId( HTraceConfiguration.fromKeyValuePairs(TracerId.TRACER_ID_KEY, fmt), "TracerName").get()); } @Test public void testSimpleTracerIds() { testTracerIdImpl("abc", "abc"); testTracerIdImpl("abc", "a\\bc"); testTracerIdImpl("abc", "ab\\c"); testTracerIdImpl("abc", "\\a\\b\\c"); testTracerIdImpl("a\\bc", "a\\\\bc"); } @Test public void testSubstitutionVariables() throws IOException { testTracerIdImpl("myTracerName", "my%{tname}"); testTracerIdImpl(TracerId.getProcessName(), "%{pname}"); testTracerIdImpl("my." + TracerId.getProcessName(), "my.%{pname}"); testTracerIdImpl(TracerId.getBestIpString() + ".str", "%{ip}.str"); testTracerIdImpl("%{pname}", "\\%{pname}"); testTracerIdImpl("%cash%money{}", "%cash%money{}"); testTracerIdImpl("Foo." + Long.valueOf(TracerId.getOsPid()).toString(), "Foo.%{pid}"); } }
37
75
0.703723
6fd65bdca0de644113c9df16c3e15aa08ac4a130
372
package ftblag.lagslib.interfaces; import net.minecraft.client.renderer.tileentity.TileEntityRenderer; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.tileentity.TileEntity; public interface ITileEntityRendererFactory<T extends TileEntity> { TileEntityRenderer<T> create(TileEntityRendererDispatcher dispatcher); }
37.2
77
0.860215
e5227bf01d99274da6e57ebc292e05977ded6981
4,800
package loon; import static org.lwjgl.opengl.EXTFramebufferObject.GL_FRAMEBUFFER_EXT; import static org.lwjgl.opengl.EXTFramebufferObject.glBindFramebufferEXT; import static org.lwjgl.opengl.EXTFramebufferObject.glCheckFramebufferStatusEXT; import static org.lwjgl.opengl.EXTFramebufferObject.glDeleteFramebuffersEXT; import static org.lwjgl.opengl.EXTFramebufferObject.glFramebufferTexture2DEXT; import static org.lwjgl.opengl.EXTFramebufferObject.glGenFramebuffersEXT; import static org.lwjgl.opengl.GL30.GL_COLOR_ATTACHMENT0; import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER; import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_COMPLETE; import static org.lwjgl.opengl.GL30.glDeleteFramebuffers; import java.util.HashMap; import java.util.Map; import loon.core.event.Updateable; import loon.core.graphics.opengl.FrameBuffer; import loon.core.graphics.opengl.GL; import loon.core.graphics.opengl.GLEx; import loon.core.graphics.opengl.LTexture; import loon.core.graphics.opengl.LTexture.Format; import loon.utils.collection.Array; import org.lwjgl.opengl.GLContext; public class JavaSEFrameBuffer implements FrameBuffer { private final static Map<GLEx, Array<FrameBuffer>> buffers = new HashMap<GLEx, Array<FrameBuffer>>(); private LTexture texture; private int id; private int width, height; private boolean isLoaded; private static void addManagedFrameBuffer(GLEx app, FrameBuffer frameBuffer) { Array<FrameBuffer> managedResources = buffers.get(app); if (managedResources == null) { managedResources = new Array<FrameBuffer>(); } managedResources.add(frameBuffer); buffers.put(app, managedResources); } public static void invalidateAllFrameBuffers(GLEx app) { if (GLEx.gl == null) { return; } Array<FrameBuffer> bufferArray = buffers.get(app); if (bufferArray == null) { return; } for (int i = 0; i < bufferArray.size(); i++) { bufferArray.get(i).build(); } } public static void clearAllFrameBuffers(GLEx app) { buffers.remove(app); } public void build() { isLoaded = false; Updateable update = new Updateable() { @Override public void action(Object a) { if (!texture.isLoaded()) { texture.loadTexture(); } id = glGenFramebuffersEXT(); glBindFramebufferEXT(GL_FRAMEBUFFER, id); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, texture.getTextureID(), 0); int result = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER); if (result != GL_FRAMEBUFFER_COMPLETE) { glBindFramebufferEXT(GL_FRAMEBUFFER, 0); glDeleteFramebuffers(id); throw new RuntimeException("exception " + result + " when checking JavaSEFBO status"); } glBindFramebufferEXT(GL_FRAMEBUFFER, 0); isLoaded = true; } }; LSystem.load(update); } public JavaSEFrameBuffer(final LTexture texture) { if (!isSupported()) { throw new RuntimeException( "FBO extension not supported in hardware"); } this.texture = texture; this.width = texture.getWidth(); this.height = texture.getHeight(); this.build(); addManagedFrameBuffer(GLEx.self, this); } public JavaSEFrameBuffer(int width, int height, Format format) { this(new LTexture(width, height, format)); } public JavaSEFrameBuffer(int width, int height) { this(width, height, LTexture.Format.LINEAR); } public int getWidth() { return width; } public int getHeight() { return height; } public int getID() { return id; } public LTexture getTexture() { return texture; } public boolean isLoaded() { return isLoaded; } public boolean isSupported() { return GLContext.getCapabilities().GL_EXT_framebuffer_object; } public void bind() { if (!isLoaded) { return; } if (id == 0) { throw new IllegalStateException( "can't use FBO as it has been destroyed.."); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id); } public void unbind() { if (!isLoaded) { return; } if (id == 0) { return; } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } public void begin() { bind(); setFrameBufferViewport(); } protected void setFrameBufferViewport() { GLEx.gl.glViewport(0, 0, texture.getWidth(), texture.getHeight()); } public void end() { unbind(); setDefaultFrameBufferViewport(); } protected void setDefaultFrameBufferViewport() { GLEx.gl.glViewport(0, 0, GLEx.width(), GLEx.height()); } public void end(int x, int y, int width, int height) { unbind(); GLEx.gl.glViewport(x, y, width, height); } public void destroy() { if (isLoaded) { isLoaded = false; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(id); id = 0; } if (texture != null) { texture.destroy(); } if (buffers.get(GLEx.self) != null) { buffers.get(GLEx.self).remove(this); } } }
24.870466
102
0.723125
53d5c79f3a01dc32cee75b36a30a0a2ded0e68e9
10,075
/* * @(#)$Id$ * * Author : Michele Croci, [email protected] * * Purpose : Dialog for mapping a gesture to an action. * * ----------------------------------------------------------------------- * * Revision Information: * * Date Who Reason * * Nov 26, 2007 crocimi Initial Release * Jan 18, 2008 bsigner Cleanup * * ----------------------------------------------------------------------- * * Copyright 1999-2009 ETH Zurich. All Rights Reserved. * * This software is the proprietary information of ETH Zurich. * Use is subject to license terms. * */ package org.ximtec.igesture.geco.dialog; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.TitledBorder; import org.sigtec.graphix.GuiTool; import org.sigtec.graphix.widget.BasicDialog; import org.ximtec.igesture.core.GestureClass; import org.ximtec.igesture.geco.action.CommandExecutor; import org.ximtec.igesture.geco.action.KeyboardSimulation; import org.ximtec.igesture.geco.gui.CommandView; import org.ximtec.igesture.geco.gui.HotKeyView; import org.ximtec.igesture.geco.gui.MainView; import org.ximtec.igesture.geco.mapping.GestureToActionMapping; import org.ximtec.igesture.geco.util.Constant; import org.ximtec.igesture.geco.util.GuiBundleTool; /** * Dialog for mapping a gesture to an action * * @version 0.9, Nov 26, 2007 * @author Michele Croci, [email protected] * @author Beat Signer, [email protected] */ public class MappingDialog extends BasicDialog { private GestureClass gestureClass; private GestureToActionMapping gestureMapping; private MainView view; // GUI elements private JTabbedPane tabbedPane = new JTabbedPane(); private JLabel gestureLabel = new JLabel(); private JButton addButton; private JTextField textField = GuiTool.createTextField(Constant.EMPTY_STRING, GuiBundleTool.getBundle()); private int DIALOG_WIDTH = 450; private int DIALOG_HEIGHT = 500; // views private HotKeyView hotkeyView; private CommandView commandView; // private JPanel labelPanel; // constants private final int HOTKEY = 0; private final int COMMAND = 1; private final int OPEN_FILE = 2; // models // private HotKeyModel hotkeyModel = new HotKeyModel(); public MappingDialog(MainView gmv) { view = gmv; setFocusable(false); setModal(true); initDialog(); tabbedPane.setFocusable(false); // this.addFocusListener(this); }// MappingDialog /** * Shows the dialog. * * @param gc the gesture to be mapped. */ public void showDialog(GestureClass gc) { gestureMapping = view.getModel().getMappings().get(gc); gestureClass = gc; initValues(); this.setVisible(true); }// showDialog /** * Hides the dialog. */ public void hideDialog() { this.setVisible(false); }// hideDialog /** * Initialises the state of the buttons. */ private void initValues() { gestureLabel.setText(gestureClass.getName()); if (gestureMapping == null) { commandView.init(); hotkeyView.initView(); tabbedPane.setSelectedIndex(COMMAND); tabbedPane.setSelectedIndex(HOTKEY); } else { if (gestureMapping.getAction() instanceof KeyboardSimulation) { KeyboardSimulation ks = (KeyboardSimulation)gestureMapping .getAction(); hotkeyView.updateView(ks.toString()); } else if (gestureMapping.getAction() instanceof CommandExecutor) { CommandExecutor cmd = (CommandExecutor)gestureMapping.getAction(); commandView.updateView(cmd.getCommand()); tabbedPane.setSelectedIndex(COMMAND); } } }// initButtonsState /** * Init the Dialog */ private void initDialog() { this.setResizable(false); this.setTitle(GuiBundleTool.getBundle().getName( Constant.GESTURE_MAPPING_TITLE)); this.setLayout(new GridBagLayout()); this.add(tabbedPane, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(20, 40, 20, 40), 0, 0)); Point p = new Point(view.getLocation().x + 200, view.getLocation().y + 100); this.setLocation(p); this.setSize(new Dimension(DIALOG_WIDTH, DIALOG_HEIGHT)); showGesture(); addButtonPanel(); addFirstTab(); addSecondTab(); addThirdTab(); // tabbedPane.addChangeListener(hotkeyView.getChangeListener()); } // initDialog private void showGesture() { JPanel topPanel = new JPanel(); topPanel.setBorder(new TitledBorder(new BevelBorder(0, Color.gray, Color.gray), Constant.GESTURE)); topPanel.add(gestureLabel); this.add(topPanel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 40, 10, 40), 0, 0)); } /** * Add the buttons * */ private void addButtonPanel() { JPanel buttonPanel = new JPanel(); addButton = GuiTool.createButton(Constant.ADD, GuiBundleTool.getBundle()); JButton cancelButton = GuiTool.createButton(Constant.CANCEL, GuiBundleTool .getBundle()); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // update model addGestureMappingToTable(); view.getModel().addMapping( MappingDialog.this.view.getModel().getMappings().get( gestureClass)); // update view view.updateLists(); view.enableSaveButton(); MappingDialog.this.dispose(); } }); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { MappingDialog.this.dispose(); } }); buttonPanel.add(addButton); buttonPanel.add(cancelButton); this.add(buttonPanel, new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 20, 0, 20), 0, 0)); } /** * Add the first tab to the dialog * */ private void addFirstTab() { hotkeyView = new HotKeyView(this); JPanel aPanel = new JPanel(); aPanel.setBorder(new TitledBorder(new BevelBorder(0, Color.gray, Color.gray), Constant.HOTKEY)); aPanel.setLayout(new GridLayout(1, 1)); aPanel.add(hotkeyView); tabbedPane.addTab(Constant.HOTKEY, aPanel); tabbedPane.setMnemonicAt(HOTKEY, KeyEvent.VK_1); } // addFirstTab /** * Add the second tab to the dialog * */ private void addSecondTab() { commandView = new CommandView(); tabbedPane.addTab(Constant.COMMAND, commandView); tabbedPane.setMnemonicAt(COMMAND, KeyEvent.VK_2); } /** * Add third tab to the dialog * */ private void addThirdTab() { JPanel aPanel = new JPanel(); aPanel.setLayout(new GridBagLayout()); tabbedPane.addTab(Constant.OPEN_FILE, aPanel); tabbedPane.setMnemonicAt(OPEN_FILE, KeyEvent.VK_3); JButton browse = GuiTool.createButton(Constant.BROWSE, GuiBundleTool .getBundle()); browse.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { textField.setText(fileChooser.getSelectedFile().getPath()); } } }); aPanel.add(textField, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(50, 20, 50, 20), 0, 0)); aPanel.add(browse, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(50, 50, 50, 50), 0, 0)); } /** * Add a Gesture-action map to the table of mappings * */ private void addGestureMappingToTable() { if (tabbedPane.getSelectedIndex() == HOTKEY) { GestureToActionMapping mapping = new GestureToActionMapping( gestureClass, new KeyboardSimulation(hotkeyView.getAllKeys())); view.getModel().getMappings().put(gestureClass, mapping); } else if (tabbedPane.getSelectedIndex() == COMMAND) { GestureToActionMapping mapping = new GestureToActionMapping( gestureClass, new CommandExecutor(commandView.getCommand())); view.getModel().getMappings().put(gestureClass, mapping); } else if (tabbedPane.getSelectedIndex() == OPEN_FILE) { GestureToActionMapping mapping = new GestureToActionMapping( gestureClass, new CommandExecutor(textField.getText())); view.getModel().getMappings().put(gestureClass, mapping); } }// addGestureMappingToTable public void setAddButtonEnabled(boolean b) { addButton.setEnabled(b); } }
30.438066
83
0.620744
7b882f001f9072caa81810822c132ac2b296d2e5
179
package ua.goit.dao; import java.util.List; public interface GenericDao<T> { List<T> findAll(); T create(T t); T delete(T t); T update(T t); T findById(Integer id); }
14.916667
32
0.653631
4e36ce5990837fec2b9ed86ab211dfc7d3ab079e
13,169
package seedu.address.logic.parser; import static java.util.Objects.requireNonNull; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.FileUtil; import seedu.address.commons.util.StringUtil; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.event.Date; import seedu.address.model.event.EventName; import seedu.address.model.event.Time; import seedu.address.model.eventContacts.EventContacts; import seedu.address.model.expense.ExpenseCategory; import seedu.address.model.expense.ExpenseDate; import seedu.address.model.expense.ExpenseValue; import seedu.address.model.person.Address; import seedu.address.model.person.Email; import seedu.address.model.person.Name; import seedu.address.model.person.Phone; import seedu.address.model.tag.Tag; import seedu.address.model.task.Body; import seedu.address.model.task.DateTime; import seedu.address.model.task.Priority; import seedu.address.model.task.TaskName; /** * Contains utility methods used for parsing strings in the various *Parser classes. */ public class ParserUtil { public static final String MESSAGE_INVALID_INDEX = "Index is not a non-zero unsigned integer."; public static final String MESSAGE_INVALID_PATH = "Path is not a valid file location"; /** * Parses {@code oneBasedIndex} into an {@code Index} and returns it. Leading and trailing whitespaces will be * trimmed. * @throws ParseException if the specified index is invalid (not non-zero unsigned integer). */ public static Index parseIndex(String oneBasedIndex) throws ParseException { String trimmedIndex = oneBasedIndex.trim(); if (!StringUtil.isNonZeroUnsignedInteger(trimmedIndex)) { throw new ParseException(MESSAGE_INVALID_INDEX); } return Index.fromOneBased(Integer.parseInt(trimmedIndex)); } /** * Parses a {@code String name} into a {@code Name}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static Name parseName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_NAME_CONSTRAINTS); } return new Name(trimmedName); } /** * Parses a {@code String phone} into a {@code Phone}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code phone} is invalid. */ public static Phone parsePhone(String phone) throws ParseException { requireNonNull(phone); String trimmedPhone = phone.trim(); if (!Phone.isValidPhone(trimmedPhone)) { throw new ParseException(Phone.MESSAGE_PHONE_CONSTRAINTS); } return new Phone(trimmedPhone); } /** * Parses a {@code String address} into an {@code Address}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code address} is invalid. */ public static Address parseAddress(String address) throws ParseException { requireNonNull(address); String trimmedAddress = address.trim(); if (!Address.isValidAddress(trimmedAddress)) { throw new ParseException(Address.MESSAGE_ADDRESS_CONSTRAINTS); } return new Address(trimmedAddress); } /** * Parses a {@code String email} into an {@code Email}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code email} is invalid. */ public static Email parseEmail(String email) throws ParseException { requireNonNull(email); String trimmedEmail = email.trim(); if (!Email.isValidEmail(trimmedEmail)) { throw new ParseException(Email.MESSAGE_EMAIL_CONSTRAINTS); } return new Email(trimmedEmail); } /** * Parses a {@code String tag} into a {@code Tag}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code tag} is invalid. */ public static Tag parseTag(String tag) throws ParseException { requireNonNull(tag); String trimmedTag = tag.trim(); if (!Tag.isValidTagName(trimmedTag)) { throw new ParseException(Tag.MESSAGE_TAG_CONSTRAINTS); } return new Tag(trimmedTag); } /** * Parses {@code Collection<String> tags} into a {@code Set<Tag>}. */ public static Set<Tag> parseTags(Collection<String> tags) throws ParseException { requireNonNull(tags); final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(parseTag(tagName)); } return tagSet; } /** * Parses {@code string} into a {@code Path}. */ public static Optional<Path> parsePath(String stringPath) throws ParseException { if (!FileUtil.isValidPath(stringPath.trim())) { throw new ParseException(MESSAGE_INVALID_PATH); } return Optional.ofNullable(Paths.get(stringPath)); } //@@author luhan02 /** * Parses a {@code String name} into a {@code TaskName}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static TaskName parseTaskName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_NAME_CONSTRAINTS); } return new TaskName(trimmedName); } /** * Parses a {@code String body} into a {@codeBody}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code body} is invalid. */ public static Body parseBody(String body) throws ParseException { return new Body(body); } /** * Parses a {@code String stareDateTime } into an {@code DateTime}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code startDateTime} is invalid. */ public static DateTime parseStartDateTime(String startDateTime) throws ParseException { requireNonNull(startDateTime); String trimmedStartDateTime = startDateTime.trim(); if (!DateTime.isValidStartDateTime(trimmedStartDateTime)) { throw new ParseException(DateTime.MESSAGE_START_DATETIME_CONSTRAINTS); } return new DateTime(trimmedStartDateTime); } /** * */ public static DateTime parseDateTimeAllowNull(String startDateTime) throws ParseException { if (startDateTime == null) { return null; } return ParserUtil.parseStartDateTime(startDateTime); } /** * Parses a {@code String endDateTime} into an {@code DateTime}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code endDateTime} is invalid. */ public static DateTime parseEndDateTime(String endDateTime) throws ParseException { requireNonNull(endDateTime); String trimmedEndDateTime = endDateTime.trim(); if (!DateTime.isValidEndDateTime(trimmedEndDateTime)) { throw new ParseException(DateTime.MESSAGE_END_DATETIME_CONSTRAINTS); } return new DateTime(trimmedEndDateTime); } /** * Parses a {@code String priority} into an {@code Priority}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code priority} is invalid. */ public static Priority parsePriority(String priority) throws ParseException { String trimmedPriority = priority.trim(); if (!Priority.isValidPriority(trimmedPriority)) { throw new ParseException(Priority.MESSAGE_PRIORITY_CONSTRAINTS); } return new Priority(trimmedPriority); } //@@author /** * Parses a {@code String name} into a {@code EventName}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static EventName parseEventName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_NAME_CONSTRAINTS); } return new EventName(trimmedName); } /** * Parses a {@code String eventDate} into an {@code Event Date}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code eventDate} is invalid. */ public static Date parseEventDate(String eventDate) throws ParseException { requireNonNull(eventDate); String trimmedEventDate = eventDate.trim(); if (!Date.isValidDate(trimmedEventDate)) { throw new ParseException(Date.MESSAGE_EVENT_DATE_CONSTRAINTS); } return new Date(trimmedEventDate); } /** * Parses a {@code String eventTime} into an {@code Event Time}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code eventTime} is invalid. */ public static Time parseEventTime(String eventTime) throws ParseException { requireNonNull(eventTime); String trimmedEventTime = eventTime.trim(); if (!Time.isValidTime(trimmedEventTime)) { throw new ParseException(Time.MESSAGE_EVENT_TIME_CONSTRAINTS); } return new Time(trimmedEventTime); } /** * Parses a {@code String eventContacts} into a {@code EventContacts}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code eventContacts} is invalid. */ public static EventContacts parseEventContacts(String eventContacts) throws ParseException { requireNonNull(eventContacts); String trimmedEventContacts = eventContacts.trim(); if (!Tag.isValidTagName(trimmedEventContacts)) { throw new ParseException(EventContacts.MESSAGE_EVENT_CONTACTS_CONSTRAINTS); } return new EventContacts(trimmedEventContacts); } /** * Parses {@code Collection<String> eventContacts} into a {@code Set<EventContacts>}. */ public static Set<EventContacts> parseEventContacts(Collection<String> eventContacts) throws ParseException { requireNonNull(eventContacts); final Set<EventContacts> eventContactsSet = new HashSet<>(); for (String eventContactsName : eventContacts) { eventContactsSet.add(parseEventContacts(eventContactsName)); } return eventContactsSet; } //@@author ChenSongJian /** * Parses a {@code String expenseValue} into a {@code expenseValue}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static ExpenseCategory parseExpenseCategory(String expenseCategory) throws ParseException { requireNonNull(expenseCategory); String trimmedExpenseCategory = expenseCategory.trim(); if (!ExpenseCategory.isValidExpenseCategory(trimmedExpenseCategory)) { throw new ParseException(ExpenseCategory.MESSAGE_EXPENSE_CATEGORY_CONSTRAINTS); } return new ExpenseCategory(trimmedExpenseCategory); } /** * Parses a {@code String expenseDate} into a {@code expenseDate}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static ExpenseDate parseExpenseDate(String expenseDate) throws ParseException { requireNonNull(expenseDate); String trimmedExpenseDate = expenseDate.trim(); if (!ExpenseDate.isValidDate(trimmedExpenseDate)) { throw new ParseException(ExpenseDate.MESSAGE_EXPENSE_DATE_CONSTRAINTS); } return new ExpenseDate(trimmedExpenseDate); } /** * Parses a {@code String expenseValue} into a {@code expenseValue}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static ExpenseValue parseExpenseValue(String expenseValue) throws ParseException { requireNonNull(expenseValue); String trimmedExpenseValue = expenseValue.trim(); if (!ExpenseValue.isValidExpenseValue(trimmedExpenseValue)) { throw new ParseException(ExpenseValue.MESSAGE_EXPENSE_VALUE_CONSTRAINTS); } return new ExpenseValue(trimmedExpenseValue); } //@@author }
37.625714
114
0.6775
6b4f180d58c84003593ba99bf9d87490c18bdd5f
17,825
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.coeus.common.framework.compliance.core; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.framework.compliance.exemption.SpecialReviewExemption; import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.iacuc.IacucProtocol; import org.kuali.kra.iacuc.IacucProtocolFinderDao; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.kra.irb.Protocol; import org.kuali.kra.irb.ProtocolFinderDao; import org.kuali.rice.krad.util.GlobalVariables; import org.springframework.util.CollectionUtils; import java.sql.Date; import java.util.*; /** * This class validates all rules associated with SpecialReview. * @param <T> Special Review */ public class SpecialReviewRuleBase<T extends SpecialReview<? extends SpecialReviewExemption>> extends KcTransactionalDocumentRuleBase { private static final String TYPE_CODE_FIELD = "specialReviewTypeCode"; private static final String APPROVAL_TYPE_CODE_FIELD = "approvalTypeCode"; private static final String PROTOCOL_NUMBER_FIELD = "protocolNumber"; private static final String PROTOCOL_NUMBER_TITLE = "Protocol Number"; private static final String APPLICATION_DATE_FIELD = "applicationDate"; private static final String APPLICATION_DATE_TITLE = "Application Date"; private static final String APPROVAL_DATE_FIELD = "approvalDate"; private static final String APPROVAL_DATE_TITLE = "Approval Date"; private static final String EXPIRATION_DATE_FIELD = "expirationDate"; private static final String EXPIRATION_DATE_TITLE = "Expiration Date"; private static final String EXEMPTION_TYPE_CODE_FIELD = "exemptionTypeCodes"; private static final String EXEMPTION_TYPE_CODE_TITLE = "Exemption #"; private static final String HUMAN_SUBJECTS_LINK_TO_IRB_ERROR_STRING = "Human Subjects/Link to IRB"; private static final String ANIMAL_USAGE_LINK_TO_IACUC_ERROR_STRING = "Animal Usage/Link to IACUC"; private ProtocolFinderDao protocolFinderDao; private IacucProtocolFinderDao iacucProtocolFinderDao; /** * Runs the rules for adding a specialReview. * * @param addSpecialReviewEvent The event invoking the add specialReview rules * @return True if the specialReview is valid, false otherwise */ protected boolean processAddSpecialReviewEvent(AddSpecialReviewEvent<T> addSpecialReviewEvent) { boolean rulePassed = true; T specialReview = addSpecialReviewEvent.getSpecialReview(); List<T> specialReviews = addSpecialReviewEvent.getSpecialReviews(); boolean validateProtocol = addSpecialReviewEvent.getIsIrbProtocolLinkingEnabled(); getDictionaryValidationService().validateBusinessObject(specialReview); rulePassed &= GlobalVariables.getMessageMap().hasNoErrors(); if (validateProtocol && SpecialReviewType.HUMAN_SUBJECTS.equals(specialReview.getSpecialReviewTypeCode())) { rulePassed &= validateProtocolNumber(specialReview, specialReviews, HUMAN_SUBJECTS_LINK_TO_IRB_ERROR_STRING); } else if (validateProtocol && SpecialReviewType.ANIMAL_USAGE.equals(specialReview.getSpecialReviewTypeCode()) ) { rulePassed &= validateProtocolNumber(specialReview, specialReviews, ANIMAL_USAGE_LINK_TO_IACUC_ERROR_STRING); } else { rulePassed &= validateSpecialReviewApprovalFields(specialReview); rulePassed &= validateDateFields(specialReview); } return rulePassed; } /** * Runs the rules for saving the special reviews that are currently linked to a protocol. * * @param saveSpecialReviewLinkEvent The event invoking the save specialReview rules * @return True if the specialReview is valid, false otherwise */ protected boolean processSaveSpecialReviewLinkEvent(SaveSpecialReviewLinkEvent<T> saveSpecialReviewLinkEvent) { boolean rulePassed = true; for (T specialReview : saveSpecialReviewLinkEvent.getSpecialReviews()) { if (SpecialReviewType.HUMAN_SUBJECTS.equals(specialReview.getSpecialReviewTypeCode())) { rulePassed &= validateLinkingDocument(specialReview.getProtocolNumber()); } } for (String linkedProtocolNumber : saveSpecialReviewLinkEvent.getLinkedProtocolNumbers()) { rulePassed &= validateLinkingDocument(linkedProtocolNumber); } return rulePassed; } /** * Runs the rules for saving specialReviews. * * @param saveSpecialReviewEvent The event invoking the save specialReview rules * @return True if the specialReviews are valid, false otherwise */ protected boolean processSaveSpecialReviewEvent(SaveSpecialReviewEvent<T> saveSpecialReviewEvent) { boolean rulePassed = true; List<T> specialReviews = saveSpecialReviewEvent.getSpecialReviews(); boolean validateIrbProtocol = saveSpecialReviewEvent.getValidateIrbProtocol(); boolean validateIacucProtocol = saveSpecialReviewEvent.getValidateIacucProtocol(); int i = 0; for (T specialReview : specialReviews) { String errorPath = saveSpecialReviewEvent.getArrayErrorPathPrefix() + Constants.LEFT_SQUARE_BRACKET + i++ + Constants.RIGHT_SQUARE_BRACKET; GlobalVariables.getMessageMap().addToErrorPath(errorPath); if (validateIrbProtocol && SpecialReviewType.HUMAN_SUBJECTS.equals(specialReview.getSpecialReviewTypeCode())) { rulePassed &= validateProtocolNumber(specialReview, specialReviews, HUMAN_SUBJECTS_LINK_TO_IRB_ERROR_STRING); } else if (validateIacucProtocol && SpecialReviewType.ANIMAL_USAGE.equals(specialReview.getSpecialReviewTypeCode())) { rulePassed &= validateProtocolNumber(specialReview, specialReviews, ANIMAL_USAGE_LINK_TO_IACUC_ERROR_STRING); } else { rulePassed &= validateSpecialReviewApprovalFields(specialReview); rulePassed &= validateDateFields(specialReview); } GlobalVariables.getMessageMap().removeFromErrorPath(errorPath); } return rulePassed; } /** * Validates whether the Protocol Document of the given protocol number is not locked. * * @param protocolNumber the protocol number * @return true if the specialReview is valid, false otherwise */ private boolean validateLinkingDocument(String protocolNumber) { boolean isValid = true; if (StringUtils.isNotBlank(protocolNumber)) { Protocol protocol = getProtocolFinderDao().findCurrentProtocolByNumber(protocolNumber); if (protocol != null && !protocol.getProtocolDocument().getPessimisticLocks().isEmpty()) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_PROTOCOL_LOCKED, protocolNumber); } } return isValid; } /** * Validates the rules surrounding the protocol number. * * @param specialReview The special review to validate * @param specialReviews The existing special reviews * @param errorString The error string for the type / approval of this special review * @return true if the specialReview is valid, false otherwise */ @SuppressWarnings("unchecked") private boolean validateProtocolNumber(T specialReview, List<T> specialReviews, String errorString) { boolean isValid = true; if (!StringUtils.equals(SpecialReviewApprovalType.NOT_YET_APPLIED, specialReview.getApprovalTypeCode())) { if (StringUtils.isBlank(specialReview.getProtocolNumber())) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_REQUIRED_FOR_VALID, PROTOCOL_NUMBER_TITLE, errorString); } else { if ( SpecialReviewType.HUMAN_SUBJECTS.equals(specialReview.getSpecialReviewTypeCode())) { Protocol protocol = getProtocolFinderDao().findCurrentProtocolByNumber(specialReview.getProtocolNumber()); if (protocol == null) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_PROTOCOL_NUMBER_INVALID); } else { List<T> existingSpecialReviews = ListUtils.subtract(specialReviews, Collections.singletonList(specialReview)); for (T existingSpecialReview : existingSpecialReviews) { if (StringUtils.equals(specialReview.getProtocolNumber(), existingSpecialReview.getProtocolNumber())) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_PROTOCOL_NUMBER_DUPLICATE); } } } } else if ( SpecialReviewType.ANIMAL_USAGE.equals(specialReview.getSpecialReviewTypeCode())) { IacucProtocol iacucProtocol = (IacucProtocol)getIacucProtocolFinderDao().findCurrentProtocolByNumber(specialReview.getProtocolNumber()); if (iacucProtocol == null) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_PROTOCOL_NUMBER_INVALID); } else { List<T> existingSpecialReviews = ListUtils.subtract(specialReviews, Collections.singletonList(specialReview)); for (T existingSpecialReview : existingSpecialReviews) { if (StringUtils.equals(specialReview.getProtocolNumber(), existingSpecialReview.getProtocolNumber())) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_PROTOCOL_NUMBER_DUPLICATE); } } } } } } return isValid; } /** * Validates the rules surrounding the ValidSpecialReviewApproval. * * @param specialReview The special review to validate * @return true if the specialReview is valid, false otherwise */ private boolean validateSpecialReviewApprovalFields(T specialReview) { boolean isValid = true; if (StringUtils.isNotBlank(specialReview.getSpecialReviewTypeCode()) && StringUtils.isNotBlank(specialReview.getApprovalTypeCode())) { Map<String, String> fieldValues = new HashMap<String, String>(); fieldValues.put(TYPE_CODE_FIELD, specialReview.getSpecialReviewTypeCode()); fieldValues.put(APPROVAL_TYPE_CODE_FIELD, specialReview.getApprovalTypeCode()); Collection<ValidSpecialReviewApproval> validApprovals = getBusinessObjectService().findMatching(ValidSpecialReviewApproval.class, fieldValues); for (ValidSpecialReviewApproval validApproval : validApprovals) { String validApprovalErrorString = getValidApprovalErrorString(validApproval); isValid &= validateApprovalFields(validApproval, specialReview, validApprovalErrorString); } } return isValid; } /** * Composes the String used when reporting specifics of a ValidSpecialReviewApproval error. * * @param approval The maintenance document that determines whether a field is required * @return the correct error string for this validSpecialReviewApproval */ private String getValidApprovalErrorString(ValidSpecialReviewApproval approval) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(approval.getSpecialReviewType().getDescription()); stringBuilder.append("/"); stringBuilder.append(approval.getSpecialReviewApprovalType().getDescription()); return stringBuilder.toString(); } /** * Validates the rules that determine whether certain fields are required in certain circumstances. * * @param approval The maintenance document that determines whether a field is required * @param specialReview The special review to validate * @param errorString The error string for the type / approval of this special review * @return true if the specialReview is valid, false otherwise */ private boolean validateApprovalFields(ValidSpecialReviewApproval approval, T specialReview, String errorString) { boolean isValid = true; if (approval.isProtocolNumberFlag() && StringUtils.isBlank(specialReview.getProtocolNumber())) { isValid = false; reportError(PROTOCOL_NUMBER_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_REQUIRED_FOR_VALID, PROTOCOL_NUMBER_TITLE, errorString); } if (approval.isApplicationDateFlag() && specialReview.getApplicationDate() == null) { isValid = false; reportError(APPLICATION_DATE_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_REQUIRED_FOR_VALID, APPLICATION_DATE_TITLE, errorString); } if (approval.isApprovalDateFlag() && specialReview.getApprovalDate() == null) { isValid = false; reportError(APPROVAL_DATE_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_REQUIRED_FOR_VALID, APPROVAL_DATE_TITLE, errorString); } if (approval.isExemptNumberFlag()) { if (CollectionUtils.isEmpty(specialReview.getExemptionTypeCodes())) { isValid = false; reportError(EXEMPTION_TYPE_CODE_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_REQUIRED_FOR_VALID, EXEMPTION_TYPE_CODE_TITLE, errorString); } } else { if (!CollectionUtils.isEmpty(specialReview.getExemptionTypeCodes())) { isValid = false; reportError(EXEMPTION_TYPE_CODE_FIELD, KeyConstants.ERROR_SPECIAL_REVIEW_CANNOT_SELECT_EXEMPTION_FOR_VALID, errorString); } } return isValid; } /** * Validates the interdependencies between the different date fields and the statuses. * * @param specialReview The special review object to validate * @return true if the specialReview is valid, false otherwise */ private boolean validateDateFields(T specialReview) { boolean isValid = true; isValid &= validateDateOrder(specialReview.getApplicationDate(), specialReview.getApprovalDate(), APPROVAL_DATE_FIELD, APPLICATION_DATE_TITLE, APPROVAL_DATE_TITLE); isValid &= validateDateOrder(specialReview.getApprovalDate(), specialReview.getExpirationDate(), EXPIRATION_DATE_FIELD, APPROVAL_DATE_TITLE, EXPIRATION_DATE_TITLE); isValid &= validateDateOrder(specialReview.getApplicationDate(), specialReview.getExpirationDate(), EXPIRATION_DATE_FIELD, APPLICATION_DATE_TITLE, EXPIRATION_DATE_TITLE); return isValid; } /** * Validates that the first date is before or the same as the second date. * * @param firstDate The first date * @param secondDate The second date * @param errorField The field on which to display the error * @param firstDateTitle The title of the first date field * @param secondDateTitle The title of the second date field * @return */ private boolean validateDateOrder(Date firstDate, Date secondDate, String errorField, String firstDateTitle, String secondDateTitle) { boolean isValid = true; if (firstDate != null && secondDate != null && secondDate.before(firstDate)) { isValid = false; reportError(errorField, KeyConstants.ERROR_SPECIAL_REVIEW_DATE_SAME_OR_LATER, secondDateTitle, firstDateTitle); } return isValid; } public ProtocolFinderDao getProtocolFinderDao() { if (protocolFinderDao == null) { protocolFinderDao = KcServiceLocator.getService(ProtocolFinderDao.class); } return protocolFinderDao; } public void setProtocolFinderDao(ProtocolFinderDao protocolFinderDao) { this.protocolFinderDao = protocolFinderDao; } public IacucProtocolFinderDao getIacucProtocolFinderDao() { if (iacucProtocolFinderDao == null) { iacucProtocolFinderDao = KcServiceLocator.getService(IacucProtocolFinderDao.class); } return iacucProtocolFinderDao; } public void setIacucProtocolFinderDao(IacucProtocolFinderDao iacucProtocolFinderDao) { this.iacucProtocolFinderDao = iacucProtocolFinderDao; } }
49.651811
156
0.69324
9c7913853e2870e9f8f76de7f8c2087db6fc8086
5,262
/* * Copyright Anatoliy Sablin [email protected] * * 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.github.ma1uta.matrix.client.model.auth; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import javax.json.bind.annotation.JsonbProperty; /** * Authenticates the user, and issues an access token they can use to authorize themself in subsequent requests. */ @Schema( description = "Authenticates the user, and issues an access token they can use to authorize themself in subsequent requests" ) public class LoginRequest { /** * Required. The login type being used. One of: ["m.login.password", "m.login.token"]. */ @Schema( description = "The login type being used" ) private String type; /** * Identification information for the user. */ @Schema( description = "Identification information for the user." ) private Identifier identifier; /** * The fully qualified user ID or just local part of the user ID, to log in. * <br> * @deprecated in favour of {@link LoginRequest#identifier}. */ @Schema( description = "he fully qualified user ID or just local part of the user ID, to log in." ) @Deprecated private String user; /** * When logging in using a third party identifier, the medium of the identifier. Must be 'email'. * <br> * @deprecated in favour of {@link LoginRequest#identifier}. */ @Schema( description = "When logging in using a third party identifier, the medium of the identifier. Must be 'email'." ) @Deprecated private String medium; /** * Third party identifier for the user. * <br> * @deprecated in favour of {@link LoginRequest#identifier}. */ @Schema( description = "Third party identifier for the user" ) @Deprecated private String address; /** * Required when type is m.login.password. The user's password. */ @Schema( description = "Required when type is m.login.password. The user's password." ) private char[] password; /** * Required when type is m.login.token. The login token. */ @Schema( description = "Required when type is m.login.token. The login token" ) private String token; /** * ID of the client device. If this does not correspond to a known client device, a new device will be created. * The server will auto-generate a device_id if this is not specified. */ @Schema( description = "ID of the client device. If this does not correspond to a known client device, a " + "new device will be created. The server will auto-generate a device_id if this is not specified" ) @JsonbProperty("device_id") private String deviceId; /** * A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device. */ @Schema( description = "A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device." ) @JsonbProperty("initial_device_display_name") private String initialDeviceDisplayName; public String getType() { return type; } public void setType(String type) { this.type = type; } public Identifier getIdentifier() { return identifier; } public void setIdentifier(Identifier identifier) { this.identifier = identifier; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getMedium() { return medium; } public void setMedium(String medium) { this.medium = medium; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public char[] getPassword() { return password; } public void setPassword(char[] password) { this.password = password; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } @JsonProperty("device_id") public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } @JsonProperty("initial_device_display_name") public String getInitialDeviceDisplayName() { return initialDeviceDisplayName; } public void setInitialDeviceDisplayName(String initialDeviceDisplayName) { this.initialDeviceDisplayName = initialDeviceDisplayName; } }
27.549738
129
0.655454
828a11f63035540cbd992572a1dc7e7983fc413e
682
package com.JStormLib.test; import com.JStormLib.MPQArchive; import java.io.File; import java.util.Arrays; /** * * @author Timo */ public class ArchiveTest { public static void main(String[] args){ try { File f = new File("poc.SC2Map"); File f2 = new File("test.png"); MPQArchive mpq = MPQArchive.openArchive(f); System.out.println(Arrays.toString(mpq.listFiles().toArray())); // mpq.renameFile("test-png","test.png"); System.out.println(Arrays.toString(mpq.listFiles().toArray())); mpq.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
25.259259
75
0.577713
44fd9d5d9d2688a67f8548eb10e0fb9cc6a01278
6,729
package edu.cornell.tech.foundry.sdl_rsx_rstbsupport; import android.graphics.Color; import android.support.annotation.Nullable; import com.google.gson.JsonObject; import org.apache.commons.lang3.StringUtils; import org.researchstack.backbone.answerformat.AnswerFormat; import org.researchstack.backbone.answerformat.ChoiceAnswerFormat; import org.researchstack.backbone.step.Step; import org.researchstack.backbone.utils.TextUtils; import org.researchsuite.rstb.DefaultStepGenerators.RSTBBaseStepGenerator; import org.researchsuite.rstb.RSTBStateHelper; import org.researchsuite.rstb.RSTBTaskBuilderHelper; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import edu.cornell.tech.foundry.sdl_rsx.answerformat.RSXImageChoiceAnswerFormat; import edu.cornell.tech.foundry.sdl_rsx.choice.RSXImageChoice; import edu.cornell.tech.foundry.sdl_rsx.choice.RSXTextChoiceWithColor; import edu.cornell.tech.foundry.sdl_rsx.model.RSXActivityItem; import edu.cornell.tech.foundry.sdl_rsx.model.RSXMultipleImageSelectionSurveyOptions; import edu.cornell.tech.foundry.sdl_rsx.model.YADLSpotAssessment; import edu.cornell.tech.foundry.sdl_rsx.step.RSXSingleImageClassificationSurveyStep; import edu.cornell.tech.foundry.sdl_rsx.step.YADLSpotAssessmentStep; /** * Created by jameskizer on 4/14/17. */ public class YADLSpotStepGenerator extends RSTBBaseStepGenerator { public YADLSpotStepGenerator() { super(); this.supportedTypes = Arrays.asList( "YADLSpotAssessment" ); } protected String generateImagePath(YADLSpotStepDescriptor yadlSpotStepDescriptor, YADLItemDescriptor itemDescriptor) { StringBuilder imageTitleStringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(yadlSpotStepDescriptor.imagePath)) { imageTitleStringBuilder.append(yadlSpotStepDescriptor.imagePath); imageTitleStringBuilder.append("/"); } imageTitleStringBuilder.append(itemDescriptor.imageTitle); if (!TextUtils.isEmpty(yadlSpotStepDescriptor.imageExtension)) { imageTitleStringBuilder.append("."); imageTitleStringBuilder.append(yadlSpotStepDescriptor.imageExtension); } return imageTitleStringBuilder.toString(); } @Nullable protected String generateOverlayImageTitle(YADLSpotStepDescriptor yadlSpotStepDescriptor) { if (yadlSpotStepDescriptor.itemCellSelectedOverlayImageTitle == null ) { return null; } StringBuilder imageTitleStringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(yadlSpotStepDescriptor.itemCellSelectedOverlayImagePath)) { imageTitleStringBuilder.append(yadlSpotStepDescriptor.itemCellSelectedOverlayImagePath); imageTitleStringBuilder.append("/"); } imageTitleStringBuilder.append(yadlSpotStepDescriptor.itemCellSelectedOverlayImageTitle); if (!TextUtils.isEmpty(yadlSpotStepDescriptor.itemCellSelectedOverlayImageExtension)) { imageTitleStringBuilder.append("."); imageTitleStringBuilder.append(yadlSpotStepDescriptor.itemCellSelectedOverlayImageExtension); } return imageTitleStringBuilder.toString(); } protected String[] excludedIdentifiers(List<YADLItemDescriptor> items, YADLSpotStepDescriptor yadlSpotStepDescriptor, RSTBTaskBuilderHelper helper) { String[] emptyArray = new String[0]; String filterKey = yadlSpotStepDescriptor.filterKey; if (StringUtils.isEmpty(filterKey)) { return emptyArray; } RSTBStateHelper stateHelper = helper.getStateHelper(); if (stateHelper == null){ return emptyArray; } byte[] filteredItemsBytes = stateHelper.valueInState(helper.getContext(), filterKey); if (filteredItemsBytes == null) { return emptyArray; } String joinedItems = new String(filteredItemsBytes); List<String> includedIdentifiers = Arrays.asList((android.text.TextUtils.split(joinedItems, ","))); if (includedIdentifiers.size() > 0) { ArrayList<String> excludedIdentifiers = new ArrayList<>(); for (YADLItemDescriptor item : items) { if (!includedIdentifiers.contains(item.identifier)) { excludedIdentifiers.add(item.identifier); } } String[] excludedIdentifierArray = new String[excludedIdentifiers.size()]; excludedIdentifierArray = excludedIdentifiers.toArray(excludedIdentifierArray); return excludedIdentifierArray; } else { return emptyArray; } } protected RSXImageChoice[] generateChoices(YADLSpotStepDescriptor yadlSpotStepDescriptor, List<YADLItemDescriptor> items) { RSXImageChoice[] choices = new RSXImageChoice[items.size()]; for(int i=0; i<items.size(); i++) { YADLItemDescriptor item = items.get(i); String imagePath = this.generateImagePath(yadlSpotStepDescriptor, item); RSXActivityItem activity = new RSXActivityItem( item.identifier, item.description, imagePath ); choices[i] = activity.getImageChoice(); } return choices; } @Override public List<Step> generateSteps(RSTBTaskBuilderHelper helper, String type, JsonObject jsonObject) { YADLSpotStepDescriptor yadlSpotStepDescriptor = helper.getGson().fromJson(jsonObject, YADLSpotStepDescriptor.class); if (yadlSpotStepDescriptor == null) { return null; } RSXImageChoice[] choices = this.generateChoices(yadlSpotStepDescriptor, yadlSpotStepDescriptor.items); AnswerFormat answerFormat = new RSXImageChoiceAnswerFormat(AnswerFormat.ChoiceAnswerStyle.MultipleChoice, choices); String[] excludedIdentifiers = this.excludedIdentifiers(yadlSpotStepDescriptor.items, yadlSpotStepDescriptor, helper); // String[] excludedIdentifiers = {"BedToChair", "Dressing"}; RSXMultipleImageSelectionSurveyOptions options = new RSXMultipleImageSelectionSurveyOptions(jsonObject, helper.getContext()); options.setItemCellSelectedOverlayImageTitle(this.generateOverlayImageTitle(yadlSpotStepDescriptor)); Step step = new YADLSpotAssessmentStep( yadlSpotStepDescriptor.identifier, yadlSpotStepDescriptor.title, answerFormat, options, excludedIdentifiers ); step.setOptional(yadlSpotStepDescriptor.optional); return Arrays.asList(step); } }
39.816568
153
0.713925
ecdc2379e89e38ab65fdee726dee604d70db0386
1,134
package precedent; import looked.PeriodWarden; import filmmaker.Commodity; public class FabricatorCommemoration extends TriathlonMark implements Comparable<FabricatorCommemoration> { public static double amphetamineConfine = 0.25564972554681176; public static final String WannaEndsPreclude = "WILL_FINISH_OBJECT"; public static final String TailResume = "CAN_START"; private Commodity proprietor = null; public FabricatorCommemoration(double year, String intel, Commodity property) { this.meter = year; this.pop = intel; this.proprietor = property; } public synchronized int compareTo(FabricatorCommemoration him) { String indicator = ""; if (this.meter < him.meter) return 1; else if (this.meter == him.meter) return 0; else return -1; } public synchronized void negotiationsCeremonies() { double confine = 0.7794718210684045; PeriodWarden.prepareNow(this.meter); this.proprietor.summonsAheadElement(); } public synchronized String toString() { int backTreated = 136328666; return "owner: " + proprietor + " info: " + pop + " chrono: " + meter; } }
29.842105
81
0.731041
852af841c756a08b8448fed6a036747a9f18e36e
1,573
package org.springframework.test.context.junit4; import org.springframework.test.context.ContextConfiguration; import org.springframework.util.ResourceUtils; /** * Extension of {@link SpringJUnit4ClassRunnerAppCtxTests}, which verifies that * we can specify multiple resource locations for our application context, each * configured differently. * * As of Spring 3.0, * {@code MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests} is also used * to verify support for the new {@code value} attribute alias for * {@code @ContextConfiguration}'s {@code locations} attribute. * </p> * * @author Sam Brannen * @since 2.5 * @see SpringJUnit4ClassRunnerAppCtxTests */ @ContextConfiguration( { MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.CLASSPATH_RESOURCE_PATH, MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.LOCAL_RESOURCE_PATH, MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.ABSOLUTE_RESOURCE_PATH }) public class MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests { public static final String CLASSPATH_RESOURCE_PATH = ResourceUtils.CLASSPATH_URL_PREFIX + "/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml"; public static final String LOCAL_RESOURCE_PATH = "MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml"; public static final String ABSOLUTE_RESOURCE_PATH = "/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context3.xml"; /* all tests are in the parent class. */ }
44.942857
161
0.835346
c2dd83eb3f2a4641a49b1bf8d9fe2c7130b6ddfd
4,257
package seedu.address.testutil; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import seedu.address.commons.core.UserType; import seedu.address.logic.commands.EditCommand.EditPersonDescriptor; import seedu.address.model.person.Company; import seedu.address.model.person.Name; import seedu.address.model.person.Nric; import seedu.address.model.person.Password; import seedu.address.model.person.Person; import seedu.address.model.person.Phone; import seedu.address.model.person.Rank; import seedu.address.model.person.Section; import seedu.address.model.tag.Tag; /** * A utility class to help with building EditPersonDescriptor objects. */ public class EditPersonDescriptorBuilder { private EditPersonDescriptor descriptor; public EditPersonDescriptorBuilder() { descriptor = new EditPersonDescriptor(); } public EditPersonDescriptorBuilder(EditPersonDescriptor descriptor) { this.descriptor = new EditPersonDescriptor(descriptor); } /** * Returns an {@code EditPersonDescriptor} with fields containing {@code person}'s details */ public EditPersonDescriptorBuilder(Person person) { descriptor = new EditPersonDescriptor(); descriptor.setNric(person.getNric()); descriptor.setCompany(person.getCompany()); descriptor.setSection(person.getSection()); descriptor.setRank(person.getRank()); descriptor.setName(person.getName()); descriptor.setPhone(person.getPhone()); descriptor.setTags(person.getTags()); descriptor.setPassword(person.getPassword()); descriptor.setUserType(person.getUserType()); } /** * Sets the {@code Nric} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withNric(String nric) { descriptor.setNric(new Nric(nric)); return this; } /** * Sets the {@code Company} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withCompany(String company) { descriptor.setCompany(new Company(company)); return this; } /** * Sets the {@code Section} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withSection(String section) { descriptor.setSection(new Section(section)); return this; } /** * Sets the {@code Rank} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withRank(String rank) { descriptor.setRank(new Rank(rank)); return this; } /** * Sets the {@code Name} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withName(String name) { descriptor.setName(new Name(name)); return this; } /** * Sets the {@code Phone} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withPhone(String phone) { descriptor.setPhone(new Phone(phone)); return this; } /** * Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code EditPersonDescriptor} * that we are building. */ public EditPersonDescriptorBuilder withTags(String... tags) { Set<Tag> tagSet = Stream.of(tags).map(Tag::new).collect(Collectors.toSet()); descriptor.setTags(tagSet); return this; } /** * Sets the {@code Password} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withPassword(String password) { descriptor.setPassword(new Password(password)); return this; } /** * Sets the {@code Phone} of the {@code EditPersonDescriptor} that we are building. */ public EditPersonDescriptorBuilder withUserType(String userType) { if ("A".equals(userType)) { descriptor.setUserType(UserType.ADMIN); } else if ("G".equals(userType)) { descriptor.setUserType(UserType.GENERAL); } return this; } public EditPersonDescriptor build() { return descriptor; } }
32.25
101
0.678882
bce7d3e2f07f22d415b6c6163bdf36ef51e07fb2
3,217
package za.ac.unisa.lms.tools.registrationstatus.forms; import java.util.ArrayList; public class StudyUnit { private String code; private String desc; private String regPeriod; private boolean regPeriod1 = false; private boolean regPeriod2 = false; private boolean regPeriod0 = false; private boolean regPeriod6 = false; // use this to determine wether display should be static private boolean regPeriodStatic = false; private boolean languageStatic = false; private String examPeriod; private String ndp; //non degree purposes private String language; private String status; /* Indicates which status description should be shown * TP : temporary registration, stuann=RG, awaiting payment * TN : temporary registration, stuann=TN, awaiting payment and/or doc's * A : application for */ private String statusIndicator; // Keeps track of all exam dates for a specific module private ArrayList examDates; private String supplCode; public String getSupplCode() { return supplCode; } public void setSupplCode(String supplCode) { this.supplCode = supplCode; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getNdp() { return ndp; } public void setNdp(String ndp) { this.ndp = ndp; } public String getRegPeriod() { return regPeriod; } public void setRegPeriod(String regPeriod) { this.regPeriod = regPeriod; } public ArrayList getExamDates() { return examDates; } public void setExamDates(ArrayList examDates) { this.examDates = examDates; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String toString() { return "Study unit: " + code + ", lang=" +language; } public String getExamPeriod() { return examPeriod; } public void setExamPeriod(String examPeriod) { this.examPeriod = examPeriod; } public String getStatusIndicator() { return statusIndicator; } public void setStatusIndicator(String statusIndicator) { this.statusIndicator = statusIndicator; } public boolean isRegPeriod0() { return regPeriod0; } public void setRegPeriod0(boolean regPeriod0) { this.regPeriod0 = regPeriod0; } public boolean isRegPeriod1() { return regPeriod1; } public void setRegPeriod1(boolean regPeriod1) { this.regPeriod1 = regPeriod1; } public boolean isRegPeriod2() { return regPeriod2; } public void setRegPeriod2(boolean regPeriod2) { this.regPeriod2 = regPeriod2; } public boolean isRegPeriod6() { return regPeriod6; } public void setRegPeriod6(boolean regPeriod6) { this.regPeriod6 = regPeriod6; } public boolean isLanguageStatic() { return languageStatic; } public void setLanguageStatic(boolean languageStatic) { this.languageStatic = languageStatic; } public boolean isRegPeriodStatic() { return regPeriodStatic; } public void setRegPeriodStatic(boolean regPeriodStatic) { this.regPeriodStatic = regPeriodStatic; } }
24.18797
73
0.742928
25ae1c64ce7e41a09a4b57b485ba8f56eb76fb02
3,921
package com.vrg.standalone; import com.google.common.net.HostAndPort; import com.vrg.rapid.Cluster; import com.vrg.rapid.NodeStatusChange; import com.vrg.rapid.Settings; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Brings up Rapid Cluster instances. */ class RapidRunner { @Nullable private static final Logger NETTY_LOGGER; @Nullable private static final Logger GRPC_LOGGER; private final Cluster cluster; private final HostAndPort listenAddress; static { GRPC_LOGGER = Logger.getLogger("io.grpc"); GRPC_LOGGER.setLevel(Level.WARNING); NETTY_LOGGER = Logger.getLogger("io.grpc.netty.NettyServerHandler"); NETTY_LOGGER.setLevel(Level.OFF); } RapidRunner(final HostAndPort listenAddress, final HostAndPort seedAddress, final String role, final int sleepDelayMsForNonSeed) throws IOException, InterruptedException { this.listenAddress = listenAddress; final Settings settings = new Settings(); settings.setGrpcJoinTimeoutMs(20000); if (listenAddress.equals(seedAddress)) { cluster = new Cluster.Builder(listenAddress) .useSettings(settings) .start(); } else { Thread.sleep(sleepDelayMsForNonSeed); cluster = new Cluster.Builder(listenAddress) .useSettings(settings) .join(seedAddress); } cluster.registerSubscription(com.vrg.rapid.ClusterEvents.VIEW_CHANGE_PROPOSAL, this::onViewChangeProposal); cluster.registerSubscription(com.vrg.rapid.ClusterEvents.VIEW_CHANGE, this::onViewChange); cluster.registerSubscription(com.vrg.rapid.ClusterEvents.VIEW_CHANGE_ONE_STEP_FAILED, this::onViewChangeOneStepFailed); cluster.registerSubscription(com.vrg.rapid.ClusterEvents.KICKED, this::onKicked); } /** * Executed whenever a Cluster VIEW_CHANGE_PROPOSAL event occurs. */ private void onViewChangeProposal(final Long configurationId, final List<NodeStatusChange> viewChange) { System.out.println("The condition detector has outputted a proposal: " + viewChange + " " + configurationId); } /** * Executed whenever a Cluster VIEW_CHANGE_ONE_STEP_FAILED event occurs. */ private void onViewChangeOneStepFailed(final Long configurationId, final List<NodeStatusChange> viewChange) { System.out.println("The condition detector had a conflict during one-step consensus: " + viewChange + " " + configurationId); } /** * Executed whenever a Cluster KICKED event occurs. */ private void onKicked(final Long configurationId, final List<NodeStatusChange> viewChange) { System.out.println("We got kicked from the network: " + viewChange + " " + configurationId); } /** * Executed whenever a Cluster VIEW_CHANGE event occurs. */ private void onViewChange(final Long configurationId, final List<NodeStatusChange> viewChange) { System.out.println("View change detected: " + viewChange + " " + configurationId); } /** * Wait inside a loop */ void run(final int maxTries, final int sleepIntervalMs) throws InterruptedException { int tries = maxTries; while (tries-- > 0) { System.out.println(System.currentTimeMillis() + " " + listenAddress + " Cluster size " + cluster.getMembershipSize() + " " + tries); Thread.sleep(sleepIntervalMs); } } String getClusterStatus() { return System.currentTimeMillis() + " " + listenAddress + " Cluster size " + cluster.getMembershipSize(); } }
38.441176
117
0.659526
df0b0697c4244861bb93e4bd492bcceef3b8db47
2,721
package com.ctrip.framework.cs; import com.ctrip.framework.cs.configuration.ConfigHandler; import com.google.gson.Gson; import com.google.gson.JsonPrimitive; import com.google.gson.reflect.TypeToken; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by jiang.j on 2016/6/20. */ public class ConfigHandlerTest { Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void testGetAll() throws Exception { ConfigHandler configHandler = new ConfigHandler(); Map<String,Map<String,String>> rtn = (Map<String, Map<String, String>>) configHandler.execute(configHandler.getStartPath()+"all","test",1,logger,new HashMap<String, Object>()); assertTrue(rtn.size() > 0); assertTrue(rtn.containsKey("test")); assertTrue(rtn.get("test").containsKey("test.chinese")); } @Test public void testUpdate() throws Exception { ConfigHandler configHandler = new ConfigHandler(); Map<String,Object> para = new HashMap<>(); String key="test.chinese"; String value = "good"; para.put(key,value); configHandler.execute(configHandler.getStartPath()+"update","test",1,logger,para); Map<String,Map<String,String>> rtn = (Map<String, Map<String, String>>) configHandler.execute(configHandler.getStartPath()+"all","test",1,logger,new HashMap<String, Object>()); assertTrue(rtn.size() > 0); assertTrue(rtn.containsKey("test")); assertTrue(rtn.get("test").containsKey(key)); assertEquals(value,rtn.get("test").get(key)); } @Test public void testJsonUpdate() throws Exception { ConfigHandler configHandler = new ConfigHandler(); Map<String,Object> paras = new HashMap<>(); String key="test.chinese"; String value = "good"; paras.put(key,value); Gson gson = new Gson(); Type paraMap = new TypeToken<Map<String, JsonPrimitive>>(){}.getType(); Map<String,Object> params = gson.fromJson(gson.toJson(paras),paraMap); configHandler.execute(configHandler.getStartPath()+"update","test",1,logger,params); Map<String,Map<String,String>> rtn = (Map<String, Map<String, String>>) configHandler.execute(configHandler.getStartPath()+"all","test",1,logger,new HashMap<String, Object>()); assertTrue(rtn.size() > 0); assertTrue(rtn.containsKey("test")); assertTrue(rtn.get("test").containsKey(key)); assertEquals(value,rtn.get("test").get(key)); } }
37.791667
184
0.676222
789fe75eed74bd632198e0bb44bcd9c02a374d1d
370
package net.vanvendeloo.collections.comics; import lombok.Builder; import lombok.Value; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document @Value @Builder public class ComicSeries { @Id String id; String seriesName; String author; Integer inceptionYear; String publisher; }
18.5
62
0.764865
fad68885939ae0eab77d366d6296bf125a20062a
642
package org.statesync.spring.demo.service.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.core.query.TextCriteria; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import org.statesync.spring.demo.entity.Task; @Repository public interface TaskRepository extends MongoRepository<Task, String> { Page<Task> findBy(Pageable pageable); Page<Task> findBy(TextCriteria criteria, Pageable pageable); Page<Task> findBySummaryStartsWith(String summary, Pageable pageable); }
32.1
71
0.833333
4fbae85dd884ed245fafcca1fbdba03397c9bead
1,017
package com.liemily.web.config; import org.apache.shiro.web.env.EnvironmentLoaderListener; import org.apache.shiro.web.servlet.ShiroFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.DispatcherType; import java.util.EnumSet; /** * Created by Emily Li on 20/07/2017. */ @Configuration public class ShiroConfig { @Bean EnvironmentLoaderListener environmentLoaderListener() { return new EnvironmentLoaderListener(); } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistration = new FilterRegistrationBean(); filterRegistration.setFilter(shiroFilter()); filterRegistration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); return filterRegistration; } @Bean ShiroFilter shiroFilter() { return new ShiroFilter(); } }
28.25
83
0.760079
8a2cf8d8bbd6bb70a6c08c23de5024b24dba782f
5,650
package lista2020.appmanager; import io.restassured.response.Response; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.*; import static io.restassured.RestAssured.given; public class ServiceVerificationRestHelper { CookieManager cookieManager; String key = "05a5cf06982ba7892ed2a6d38fe832d6"; String value; String status; String deleted_account; Response get_response; Response delete_response; Response post_response; Map<String, String> loginCookie = new HashMap<>(); List<String> cookies = new ArrayList<>(); Map<String, String> accounts = new HashMap<>(); String currentDate = LocalDate.now().toString(); LocalTime time = LocalTime.now(); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("HH:mm:ss"); String currentTime = time.format(dtf2); public String createAccountWithType(String type) { Random random = new Random(); int randomInt = random.nextInt(); String random_mail = "api_servicetest" + randomInt + "@gmail.com"; String password = "Pa$$w@rd"; System.out.println("============ CREATE RANDOM ACCOUNT WITH BUSINESS TYPE " + type + " AND VERIFY JSON ============"); System.out.println("==== CREATED " + random_mail + " WITH PASSWORD " + password); post_response = given(). header("Content-Type", "application/x-www-form-urlencoded"). header("user-agent", "alpalch-qpEzhaOvY0Ecb4e0"). header("X-Requested-With", "XMLHttpRequest"). formParam("added", currentDate + " " + currentTime). formParam("email", random_mail). formParam("pass", password). formParam("phone", "0547613154"). formParam("permit_ads", "true"). formParam("business_types", type). formParam("lang", "en"). formParam("timezone", "Asia/Jerusalem"). formParam("country", "IL"). formParam("city", "Tel Aviv"). when().log().all(). post("/signup-new-account").then(). extract().response(); System.out.println("STATUS POST CODE " + post_response.getStatusCode()); if (post_response.getStatusCode() == 201) { System.out.println("=== ACCOUNT: " + random_mail + " WAS CREATED ==="); loginCookie = post_response.getCookies(); for (Map.Entry<String, String> entry : loginCookie.entrySet()) { value = entry.getValue(); accounts.put(random_mail, value); } String serviceResponse = getServiceList(); return serviceResponse; } else { System.out.println("STATUS POST CODE:" + post_response.getStatusCode()); System.out.println("=== ACCOUNT " + random_mail + " NOT CREATED"); } String status = String.valueOf(post_response.getStatusCode() + " ACCOUNT CREATION STATUS"); return status; } public String getServiceList() { Response response = given().cookies(key, value). header("user-agent", "alpalch-qpEzhaOvY0Ecb4e0"). when().log().all(). get("/catalog/services/").then().extract().response(); String responseString; responseString = response.headers().toString() + "\n\n" + response.body().prettyPrint(); responseString = responseString.replaceAll("Set-Cookie.*", "###Set-Cookie##"); responseString = responseString.replaceAll("Expires=Sat, .*", "###Expires=Sat##"); responseString = responseString.replaceAll("Date=.*", "###Date##"); responseString = responseString.replaceAll("X-Request-Id.*", "###X-Request-Id##"); return responseString; } public Set<String> deleteAccount() { String value_delete; String accounts_for_deletion; System.out.println("//----------------------- DELETION ------------------------//"); System.out.println("== ACCOUNTS DESIGNED FOR REMOVAL - 20"); System.out.println("== ACCOUNTS RECEIVED FOR REMOVAL IN TEST: " + accounts.size()); accounts.forEach((k, v) -> System.out.println("//: " + k)); Set<String> removedAccounts = new HashSet<>(); for (Map.Entry<String, String> entry : accounts.entrySet()) { value_delete = entry.getValue(); accounts_for_deletion = entry.getKey(); delete_response = given().cookies(key, value_delete). header("content-type", "application/x-www-form-urlencoded"). header("user-agent", "alpalch-qpEzhaOvY0Ecb4e0"). header("X-Requested-With", "XMLHttpRequest"). when().log().all(). delete("/settings/business/account"). then().assertThat().statusCode(401).extract().response(); if (delete_response.getStatusCode() == 401) { System.out.println("DELETED ACCOUNT " + " = " + accounts_for_deletion + " = STATUS CODE: " + delete_response.getStatusCode()); deleted_account = accounts_for_deletion; deleted_account = "removed"; removedAccounts.add(deleted_account); } else { removedAccounts.add(accounts_for_deletion); } } removedAccounts.remove(deleted_account); System.out.println("LIST OF REMOVED ACCOUNTS MUST BE EMPTY, AND CONTAINS: " + removedAccounts); return removedAccounts; } }
42.80303
142
0.58885
330250950def2defe9c8a970d8882bdd40fb9025
1,276
package cz.active24.client.fred.data.common.nsset; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Nameserver data detail. * * <ul> * <li>{@link NameserverData#name} - a nameserver hostname</li> * <li>{@link NameserverData#addr} - a namesever’s IP address(es)</li> * </ul> * * @see <a href="https://fred.nic.cz/documentation/html/EPPReference/CommandStructure/Info/InfoNsset.html">FRED documentation</a> */ public class NameserverData implements Serializable { private String name; private List<String> addr; protected NameserverData() { } public NameserverData(String name) { this.setName(name); this.addr = new ArrayList<String>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getAddr() { return addr; } public void setAddr(List<String> addr) { this.addr = addr; } @Override public String toString() { final StringBuffer sb = new StringBuffer("NameserverData{"); sb.append("name='").append(name).append('\''); sb.append(", addr=").append(addr); sb.append('}'); return sb.toString(); } }
22.785714
129
0.626176
e3080339f6c8da0dc2112c7f4cea4580b2819d1b
2,386
package crc6477f0d89a9cfd64b1; public class GroupedListViewAdapter extends crc6477f0d89a9cfd64b1.ListViewAdapter implements mono.android.IGCUserPeer, android.widget.SectionIndexer { /** @hide */ public static final String __md_methods; static { __md_methods = "n_getPositionForSection:(I)I:GetGetPositionForSection_IHandler:Android.Widget.ISectionIndexerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + "n_getSectionForPosition:(I)I:GetGetSectionForPosition_IHandler:Android.Widget.ISectionIndexerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + "n_getSections:()[Ljava/lang/Object;:GetGetSectionsHandler:Android.Widget.ISectionIndexerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + ""; mono.android.Runtime.register ("Microsoft.Maui.Controls.Compatibility.Platform.Android.GroupedListViewAdapter, Microsoft.Maui.Controls.Compatibility", GroupedListViewAdapter.class, __md_methods); } public GroupedListViewAdapter () { super (); if (getClass () == GroupedListViewAdapter.class) mono.android.TypeManager.Activate ("Microsoft.Maui.Controls.Compatibility.Platform.Android.GroupedListViewAdapter, Microsoft.Maui.Controls.Compatibility", "", this, new java.lang.Object[] { }); } public GroupedListViewAdapter (android.content.Context p0) { super (); if (getClass () == GroupedListViewAdapter.class) mono.android.TypeManager.Activate ("Microsoft.Maui.Controls.Compatibility.Platform.Android.GroupedListViewAdapter, Microsoft.Maui.Controls.Compatibility", "Android.Content.Context, Mono.Android", this, new java.lang.Object[] { p0 }); } public int getPositionForSection (int p0) { return n_getPositionForSection (p0); } private native int n_getPositionForSection (int p0); public int getSectionForPosition (int p0) { return n_getSectionForPosition (p0); } private native int n_getSectionForPosition (int p0); public java.lang.Object[] getSections () { return n_getSections (); } private native java.lang.Object[] n_getSections (); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
32.243243
236
0.76907
f34ab381da6bbbb7ce0bb93dc8fafc277fdabe61
2,959
package es.uhu.mp.rpg; import es.uhu.mp.rpg.character.ICharacter; import es.uhu.mp.rpg.exception.GameException; import es.uhu.mp.rpg.exception.SceneException; import es.uhu.mp.rpg.scene.Scene; import java.util.HashMap; import java.util.Map; public class Game { private Map<String, Scene> scenes; private ICharacter player; private Scene currentScene; /** * Game constructor with the player character * @param player The new scene to add * @throws GameException If the player is null. */ public Game(ICharacter player) throws GameException { if (player == null) { throw new GameException("The player cannot be null"); } this.player = player; } /** * Sets the current scene with the loaded scene with the specified code * @param sceneCode The scene code * @throws SceneException If the scene code is null or empty. * @throws GameException If the game hasn't got a scene with the given code. */ public void setCurrentSceneByCode(String sceneCode) throws SceneException, GameException { if (sceneCode == null || "".equals(sceneCode.trim())) { throw new SceneException("The scene code is null or empty"); } if (!scenes.containsKey(sceneCode)) { throw new GameException("There is NO scene loaded in the game with the code: " + sceneCode); } this.currentScene = scenes.get(sceneCode); } /** * Adds a new Scene to the scenes map, using the scene name as the map key * @param scene The new scene to add * @throws GameException If the scene is null or there is already one with the same code. * @throws SceneException If the scene code is null or empty. */ public void addScene(Scene scene) throws GameException, SceneException { if (scenes == null) { scenes = new HashMap<String, Scene>(); } if (scene == null) { throw new GameException("Cannot add a null scene"); } String sceneCode = scene.getCode(); if (sceneCode == null || "".equals(sceneCode.trim())) { throw new SceneException("The scene must have a valid code"); } if (scenes.containsKey(sceneCode)) { throw new GameException("There is already a game scene with this code: " + sceneCode); } scenes.put(sceneCode, scene); } /** * Runs the game until there is no next scene to run. * @throws GameException If the first scene is null and the game cannot be started. */ public void run() throws GameException { String nextSceneCode = null; if (currentScene == null) { throw new GameException("The current scene is null"); } do { nextSceneCode = currentScene.play(player); currentScene = scenes.get(nextSceneCode); } while(currentScene != null); } }
32.516484
104
0.629267
f8fdc6975cfd9cb21a1fbae431dcb3c2d8aefe50
361
package com.bbva.hancock.sdk.models.socket; import com.google.gson.JsonObject; import lombok.Data; import java.io.Serializable; @Data public class HancockSocketMessage implements Serializable { private static final long serialVersionUID = -5868311404867886960L; private String kind; private JsonObject raw; private String matchedAddress; }
21.235294
71
0.786704
baf5a77334c9c36c271430da818eefba45b87469
18,607
package net.community.chest.io.test; import java.io.BufferedReader; import java.io.File; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Writer; import java.nio.ByteOrder; import javax.xml.transform.stream.StreamSource; import net.community.chest.Triplet; import net.community.chest.io.FileUtil; import net.community.chest.io.dom.PrettyPrintDocumentBuilder; import net.community.chest.io.encode.OutputDataEncoder; import net.community.chest.io.encode.hex.Hex; import net.community.chest.io.encode.hex.HexDumpOutputStream; import net.community.chest.io.file.FileAttributeType; import net.community.chest.io.file.FileIOUtils; import net.community.chest.lang.StringUtil; import net.community.chest.test.TestBase; import net.community.chest.xml.transform.TransformerUtil; import org.w3c.dom.Document; /** * <P>Copyright 2008 as per GPLv2</P> * * @author Lyor G. * @since Jun 17, 2008 7:47:52 AM */ public class IOTester extends TestBase { public static final ByteOrder toByteOrder (final String s) { if ("native".equalsIgnoreCase(s)) return ByteOrder.nativeOrder(); final ByteOrder[] orders={ ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }; for (final ByteOrder o : orders) { if (0 == StringUtil.compareDataStrings(s, String.valueOf(o), false)) return o; } return null; } /* -------------------------------------------------------------------- */ // arguments are written to the hex dump stream public static final int testHexDumpStream (final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; Writer w=null; StringBuilder sb=null; try { HexDumpOutputStream<StringBuilder> ds=null; for (int aIndex=0; ; aIndex++) { final String v=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "(S)how/string value/Quit"); if (isQuit(v)) break; try { if ("S".equalsIgnoreCase(v) || "Show".equalsIgnoreCase(v)) { if (w != null) w.flush(); out.println(sb); continue; } if (null == sb) sb = new StringBuilder(1024); if (null == ds) ds = new HexDumpOutputStream<StringBuilder>(sb, false); if (null == w) w = new OutputStreamWriter(ds); w.write(v); } catch(Exception e) { System.err.println(e.getClass().getName() + " while write val=" + v + ": " + e.getMessage()); } } return 0; } finally { try { FileUtil.closeAll(w); } catch(Exception e) { System.err.println(e.getClass().getName() + " while close writer: " + e.getMessage()); } out.println(sb); } } ////////////////////////////////////////////////////////////////////////// // args[i] a File path public static final int testFileProperties ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; aIndex++) { final String s=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "file path (or Quit)"); final int sLen=(null == s) ? 0 : s.length(); if (sLen <= 0) continue; if (isQuit(s)) break; out.println(s + " attributes:"); final File f=new File(s); for (final FileAttributeType a : FileAttributeType.VALUES) { try { final Object o=a.getValue(f); out.println("\t" + a + "=" + o); } catch(Exception e) { System.err.println(e.getClass().getName() + " while get " + s + " attribute=" + a + ": " + e.getMessage()); } } } return 0; } ////////////////////////////////////////////////////////////////////////// // args[i] even=src file, odd=dst file - if folder(s) then recursive test done public static final int testCompareFileContent ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; ) { File srcFile=null; for ( ; srcFile == null; aIndex++) { final String f=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "source file path (or Quit)"); final int sLen=(null == f) ? 0 : f.length(); if (sLen <= 0) continue; if (isQuit(f)) return 0; srcFile = new File(f); } File dstFile=null; for ( ; dstFile == null; aIndex++) { final String f=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "destination file path (or Quit)"); final int sLen=(null == f) ? 0 : f.length(); if (sLen <= 0) continue; if (isQuit(f)) return 0; dstFile = new File(f); } if (srcFile.exists() && dstFile.exists() && srcFile.isFile() && dstFile.isFile()) { for ( ; ; ) { out.print("Comparing " + srcFile + " / " + dstFile + " "); final long cmpStart=System.currentTimeMillis(); try { final Triplet<Long,Byte,Byte> cmpOffset= FileIOUtils.findDifference(srcFile, dstFile); final long cmpEnd=System.currentTimeMillis(), cmpDuration=cmpEnd - cmpStart; if (null == cmpOffset) out.print("same"); else out.print("found difference at offset " + cmpOffset.getV1() + ": src=" + Hex.toString(cmpOffset.getV2(), true) + "/dst=" + Hex.toString(cmpOffset.getV3(), true)); out.println(" after " + cmpDuration + " msec."); } catch(Exception e) { final long cmpEnd=System.currentTimeMillis(), cmpDuration=cmpEnd - cmpStart; System.err.println(e.getClass().getName() + " after " + cmpDuration + " msec.: " + e.getMessage()); } final String ans=getval(out, in, "again [y]/n"); if ((null == ans) || (ans.length() <= 0) || ('y' == Character.toLowerCase(ans.charAt(0)))) continue; else break; } } else System.err.println("Source(" + srcFile + ")/Destination(" + dstFile + ") file(s) does not exist/not a file"); } } ////////////////////////////////////////////////////////////////////////// // args[0]=charset, args[1]=byte order, args[2...]=arguments written as UTF to the encoder public static final int testDataOutputEncoder ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; final String[] tstArgs=resolveTestParameters(out, in, args, "charset", "byte order"); if ((null == tstArgs) || (tstArgs.length < 2)) return 0; final String charsetName=tstArgs[0], o=tstArgs[1]; final OutputDataEncoder enc=new EndianOutputEncoderTester(toByteOrder(o), out); for (int aIndex=2; ; aIndex++) { final String s=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "input string (or Quit)"); if (isQuit(s)) break; try { enc.writeString(s, charsetName); } catch(Exception e) { System.err.println(e.getClass().getName() + " while write string=" + s + "[" + charsetName + "]: " + e.getMessage()); } } return 0; } ////////////////////////////////////////////////////////////////////////// public static final int testPrettyPrintDocumentBuilder ( final PrintStream out, final BufferedReader in, final File xmlFile) { for ( ; ; ) { out.println("Processing " + xmlFile); Document doc=null; try { if (null == (doc=PrettyPrintDocumentBuilder.DEFAULT.parse(xmlFile))) throw new IllegalStateException("No document created"); } catch(Exception e) { System.err.println(e.getClass().getName() + " while processing file=" + xmlFile + ": " + e.getMessage()); } for ( ; ; ) { final String ans=getval(out, in, "run [a]gain/dump to (c)onsole/dump to file path/(Q)uit"); if ((null == ans) || (ans.length() <= 0) || "a".equalsIgnoreCase(ans) || "again".equalsIgnoreCase(ans)) break; if (isQuit(ans)) return 0; try { if ("c".equalsIgnoreCase(ans) || "console".equalsIgnoreCase(ans)) net.community.chest.io.dom.PrettyPrintTransformer.DEFAULT.transform(doc, out); else net.community.chest.io.dom.PrettyPrintTransformer.DEFAULT.transform(doc, new File(ans)); } catch(Exception e) { System.err.println(e.getClass().getName() + " while transforming to " + ans + ": " + e.getMessage()); } } } } // args[i]=XML file path public static final int testPrettyPrintDocumentBuilder ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; aIndex++) { final String xmlPath= (aIndex < numArgs) ? args[aIndex] : getval(out, in, "input XML file path (or Quit)"); if ((null == xmlPath) || (xmlPath.length() <= 0)) continue; if (isQuit(xmlPath)) break; testPrettyPrintDocumentBuilder(out, in, new File(xmlPath)); } return 0; } ////////////////////////////////////////////////////////////////////////// public static final int testSAXPrettyPrinter ( final PrintStream out, final BufferedReader in, final File xmlFile) { for ( ; ; ) { out.println("Processing " + xmlFile); for ( ; ; ) { final String ans=getval(out, in, "run [a]gain/dump to (c)onsole/dump to file path/(Q)uit"); if ((null == ans) || (ans.length() <= 0) || "a".equalsIgnoreCase(ans) || "again".equalsIgnoreCase(ans)) break; if (isQuit(ans)) return 0; try { final StreamSource src=new StreamSource(xmlFile); if ("c".equalsIgnoreCase(ans) || "console".equalsIgnoreCase(ans)) TransformerUtil.transform(src, out, net.community.chest.io.sax.PrettyPrintTransformer.DEFAULT); else TransformerUtil.transform(src, new File(ans), net.community.chest.io.sax.PrettyPrintTransformer.DEFAULT); } catch(Exception e) { System.err.println(e.getClass().getName() + " while transforming to " + ans + ": " + e.getMessage()); } } } } // args[i]=XML file path public static final int testSAXPrettyPrinter ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; aIndex++) { final String xmlPath= (aIndex < numArgs) ? args[aIndex] : getval(out, in, "input XML file path (or Quit)"); if ((null == xmlPath) || (xmlPath.length() <= 0)) continue; if (isQuit(xmlPath)) break; testSAXPrettyPrinter(out, in, new File(xmlPath)); } return 0; } ////////////////////////////////////////////////////////////////////////// private static final boolean extractDateValue (final String s, final String[] dv) { final String v=(s == null) ? null : s.trim(); final int vLen=(v == null) ? 0 : v.length(), sPos=(vLen >= 3) ? v.indexOf('.') : (-1); if ((sPos <= 0) || (sPos >= (vLen -1 ))) return false; dv[0] = v.substring(0, sPos); final String mthVal=v.substring(sPos + 1); final int xPos=mthVal.indexOf(' '); dv[1] = (xPos < 0) ? mthVal : mthVal.substring(0, xPos); try { for (final String vv : dv) { final byte bv=Byte.parseByte(vv); if ((bv <= 0) || (bv >= 32)) throw new NumberFormatException("Bad day/month value (" + vv + ") in " + s); } return true; } catch(NumberFormatException e) { return false; } } public static final int testRenamePaisFiles (final PrintStream out, final File fldr) { if ((fldr == null) || (!fldr.exists()) || (!fldr.isDirectory())) { System.err.println("Not a folder: " + fldr); return (-1); } final String fldrPath=fldr.getAbsolutePath(); final int pLen=(fldrPath == null) ? 0 : fldrPath.length(), sPos=(pLen <= 1) ? (-1) : fldrPath.lastIndexOf(File.separatorChar); if ((sPos <= 0) || (sPos >= (pLen -1))) { System.err.println("Bad folder path format: " + fldr); return (-2); } final String yearVal=fldrPath.substring(sPos + 1); try { final int yv=Integer.parseInt(yearVal); if ((yv <= 2000) || (yv >= 3000)) throw new NumberFormatException("Invalid range"); } catch(NumberFormatException e) { System.err.append("Bad year value (").append(yearVal) .append(")[").append(e.getMessage()) .append("] for folder=").append(fldrPath) .println() ; return (-3); } final File[] fa=fldr.listFiles(); if ((fa == null) || (fa.length <= 0)) { System.out.append("No files found in ").append(fldrPath).println(); return 0; } final String[] dVal=new String[2]; out.append("Processing ").append(fldrPath).println(); for (final File f : fa) { if (!f.isFile()) continue; final String fName=f.getName(); if (!StringUtil.endsWith(fName, ".eml", true, false)) continue; final int nLen=fName.length(), dPos=fName.lastIndexOf('-'); if ((dPos <= 0) || (dPos >= (nLen - 1))) continue; if (!extractDateValue(fName.substring(dPos + 1, nLen - 4), dVal)) continue; String newName=fName.substring(0, dPos + 1) + " " + yearVal + "." + dVal[1] + "." + dVal[0] + (fName.contains("(w)") ? " (w)" : "") + ".eml" ; final File newFile=new File(fldr, newName); if (!f.renameTo(newFile)) { System.err.println("Failed to rename " + fName + " => " + newName); continue; } out.append('\t').append(fName).append(" => ").append(newName).println(); } return 0; } // args[i]=root folder public static final int testRenamePaisFiles ( final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; aIndex++) { final String fldrPath= (aIndex < numArgs) ? args[aIndex] : getval(out, in, "files root folder (or Quit)"); if ((null == fldrPath) || (fldrPath.length() <= 0)) continue; if (isQuit(fldrPath)) break; testRenamePaisFiles(out, new File(fldrPath)); } return 0; } ////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { final BufferedReader in=getStdin(); // final int nErr=testHexDumpStream(System.out, in, args); // final int nErr=testFileProperties(System.out, in, args); // final int nErr=testCompareFileContent(System.out, in, args); // final int nErr=testDataOutputEncoder(System.out, in, args); // final int nErr=testPrettyPrintDocumentBuilder(System.out, in, args); // final int nErr=testSAXPrettyPrinter(System.out, in, args); final int nErr=testRenamePaisFiles(System.out, in, args); if (nErr != 0) System.err.println("test failed (err=" + nErr + ")"); else System.out.println("OK"); } }
36.700197
190
0.465792
b8ccc88390c199aa1f08b3f83d2eda8dba1ffc0c
1,330
package io.jenkins.plugins.sample; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Run; import hudson.model.TaskListener; import org.jenkinsci.plugins.github.extension.status.GitHubCommitShaSource; import org.jenkinsci.plugins.github.status.sources.BuildDataRevisionShaSource; import javax.annotation.Nonnull; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class MyBuildDataRevisionShaSource extends BuildDataRevisionShaSource { private static final Logger LOGGER = Logger.getLogger(MyBuildDataRevisionShaSource.class.getName()); public MyBuildDataRevisionShaSource() { super(); LOGGER.log(Level.FINER, "MyBuildDataRevisionShaSource(): {0}", new Object[]{ this }); } @Override public String get(@Nonnull Run<?, ?> run, @Nonnull TaskListener listener) throws IOException { LOGGER.log(Level.FINER, "MyBuildDataRevisionShaSource.get(): {0} {1}", new Object[]{ run, listener }); return super.get(run, listener); } @Extension public static class BuildDataRevisionShaSourceDescriptor extends Descriptor<GitHubCommitShaSource> { @Override public String getDisplayName() { return "my Latest build revision"; } } }
34.102564
104
0.723308
8112dc6a1fc4571db6aae09767e6ae864aed0eb8
8,314
/* * Copyright (c) 2014-2018, Draque Thompson, [email protected] * All rights reserved. * * Licensed under: Creative Commons Attribution-NonCommercial 4.0 International Public License * See LICENSE.TXT included with this code to read the full license agreement. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package PolyGlot.ManagersCollections; import PolyGlot.Nodes.ConWord; import PolyGlot.DictCore; import PolyGlot.Nodes.DictNode; import PolyGlot.PGTUtil; import PolyGlot.Nodes.TypeNode; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author draque */ public class TypeCollection extends DictionaryCollection { final DictCore core; public TypeNode getBufferType() { return (TypeNode) bufferNode; } @Override public void deleteNodeById(Integer _id) throws Exception { super.deleteNodeById(_id); // only push update if not core loading file if (!core.isCurLoading()) { core.pushUpdate(); } } @Override public int addNode(DictNode _addType) throws Exception { bufferNode = new TypeNode(); return super.addNode(_addType); } public TypeCollection(DictCore _core) { bufferNode = new TypeNode(); core = _core; } /** * Tests whether type based requirements met for word * * @param word word to check * @return empty if no problems, string with problem description otherwise */ public String typeRequirementsMet(ConWord word) { String ret = ""; TypeNode type = this.getNodeById(word.getWordTypeId()); // all requirements met if no type set at all. if (type != null) { String procVal; try { procVal = word.getPronunciation(); } catch (Exception e) { procVal = "<ERROR>"; } if (type.isDefMandatory() && word.getDefinition().length() == 0) { ret = type.getValue() + " requires a definition."; } else if (type.isProcMandatory() && procVal.length() == 0) { ret = type.getValue() + " requires a pronunciation."; } } return ret; } /** * This is a method used for finding nodes by name. Only for use when loading * old PolyGlot files. DO NOT rely on names for uniqueness moving forward. * @param name name of part of speech to search for * @return matching part of speech. Throws error otherwise * @throws java.lang.Exception if not found */ public TypeNode findByName(String name) throws Exception { TypeNode ret = null; for (Object n : nodeMap.values()) { TypeNode curNode = (TypeNode)n; if (curNode.getValue().toLowerCase().equals(name.toLowerCase())) { ret = curNode; break; } } if (ret == null) { throw new Exception("Unable to find part of speech: " + name); } return ret; } /** * Finds/returns type (if extant) by name * * @param _name * @return found type node, null otherwise */ public TypeNode findTypeByName(String _name) { TypeNode ret = null; if (_name.length() != 0) { Iterator<Entry<Integer, TypeNode>> it = nodeMap.entrySet().iterator(); Entry<Integer, TypeNode> curEntry; while (it.hasNext()) { curEntry = it.next(); if (curEntry.getValue().getValue().toLowerCase().equals(_name.toLowerCase())) { ret = curEntry.getValue(); break; } } } return ret; } /** * inserts current buffer word to conWord list based on id; blanks out * buffer * * @param _id * @return * @throws Exception */ public Integer insert(Integer _id) throws Exception { Integer ret; TypeNode insWord = new TypeNode(); insWord.setEqual(bufferNode); insWord.setId(_id); ret = super.insert(_id, bufferNode); bufferNode = new TypeNode(); // only push update if not due to a core file load if (!core.isCurLoading()) { core.pushUpdate(); } return ret; } /** * inserts current buffer to conWord list and generates id; blanks out * buffer * * @return ID of newly created node * @throws Exception */ public Integer insert() throws Exception { Integer ret; ret = super.insert(bufferNode); bufferNode = new TypeNode(); // only push update if not core loading file if (!core.isCurLoading()) { core.pushUpdate(); } return ret; } @Override public TypeNode getNodeById(Integer _id) { return (TypeNode) super.getNodeById(_id); } @Override public void clear() { bufferNode = new TypeNode(); } /** * returns iterator of nodes with their IDs as the entry key (ordered) * * @return */ public List<TypeNode> getNodes() { List<TypeNode> retList = new ArrayList<>(nodeMap.values()); Collections.sort(retList); return retList; } public boolean nodeExists(String findType) { boolean ret = false; Iterator<Map.Entry<Integer, TypeNode>> searchList = nodeMap.entrySet() .iterator(); while (searchList.hasNext()) { Map.Entry<Integer, TypeNode> curEntry = searchList.next(); TypeNode curType = curEntry.getValue(); if (curType.getValue().equals(findType)) { ret = true; break; } } return ret; } public boolean nodeExists(int id) { return nodeMap.containsKey(id); } public TypeNode findOrCreate(String name) throws Exception { TypeNode node = new TypeNode(); node.setValue(name); return findOrCreate(node); } public TypeNode findOrCreate(TypeNode node) throws Exception { TypeNode ret = null; for (Object n : nodeMap.values()) { TypeNode compNode = (TypeNode)n; if (compNode.getValue().equals(node.getValue()) && compNode.getGloss().equals(node.getGloss())) { ret = compNode; break; } } if (ret == null) { ret = getNodeById(insert(node)); } return ret; } /** * Writes all type information to XML document * @param doc Document to write to * @param rootElement root element of document */ public void writeXML(Document doc, Element rootElement) { Element typeContainer = doc.createElement(PGTUtil.typeCollectionXID); getNodes().forEach((curType) -> { curType.writeXML(doc, typeContainer); }); rootElement.appendChild(typeContainer); } @Override public Object notFoundNode() { TypeNode emptyNode = new TypeNode(); emptyNode.setValue("POS NOT FOUND"); emptyNode.setNotes("POT NOT FOUND"); return emptyNode; } }
28.375427
95
0.588285
bebb8c8a72db5f3a8e70ee667e9cb121b878608c
375
package org.fluentlenium.core.events; import org.openqa.selenium.WebDriver; /** * Listen to exceptions. */ public interface ExceptionListener { /** * Called when an exception is thrown. * * @param throwable thrown exception * @param driver selenium driver */ void on(Throwable throwable, WebDriver driver); // NOPMD ShortMethodName }
20.833333
76
0.682667
24890ecb9dedd35a039088ad3912e74ee738ff34
1,215
package jp.vmi.selenium.selenese.command; /** * Interface for beginning-of-loop commands. */ public interface StartLoop { /** Use NO_START_LOOP instaed of null. */ public static final StartLoop NO_START_LOOP = new StartLoop() { @Override public void setEndLoop(EndLoop endLoop) { // no operation. } @Override public void resetReachedCount() { // no operation. } @Override public void incrementReachedCount() { // no operation. } @Override public String getReachedCounts() { return ""; } }; /** The separator of reached counts. */ public static final String REACHED_COUNT_SEPARATOR = "-"; /** * Set end-of-loop command. * * @param endLoop end-of-loop command. */ void setEndLoop(EndLoop endLoop); /** * Reset reached count. */ void resetReachedCount(); /** * Increment reached count. */ void incrementReachedCount(); /** * Get nested reached counts separated by REACHED_COUNT_SEPARATOR. * * @return reached counts. */ String getReachedCounts(); }
20.59322
70
0.571193
71a1829b1fe7975ff166f439054b09d125f03688
5,248
package com.example.arv.Activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.arv.Adapters.RecyclerViewAdapter; import com.example.arv.ConnectionManager; import com.example.arv.R; import com.example.arv.model.Event; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class AllEvents extends AppCompatActivity { private final String JSON_URL = "http://192.168.8.204:1500/patientData" ; private JsonArrayRequest request ; private RequestQueue requestQueue ; private List<Event> lstevent ; private RecyclerView recyclerView ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_all_events); lstevent = new ArrayList<>() ; recyclerView = findViewById(R.id.recyclerviewid) ; jsonrequest(); } public void jsonrequest() { Log.i("Alok","Aya andar"); RequestQueue requestQueue = Volley.newRequestQueue(AllEvents.this); //Get the bundle // Bundle bundle = getIntent().getExtras(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("user", "1"); Log.i("vishal" , "In Home Json"); } catch (Exception e) { e.printStackTrace(); } ConnectionManager.sendData(jsonObject.toString(), requestQueue, JSON_URL, new ConnectionManager.VolleyCallback() { @Override public void onSuccessResponse(String result) { try { Log.i("vishal" , "In CM"); JSONArray jsonArray = new JSONArray(result); //System.out.println("Sirf array hai"+jsonArray); Log.i("vishal" , "In CM2"); for(int i =0; i<jsonArray.length();i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); // Patients patients = new Patients(); Event event = new Event(); event.setName(jsonObj.getString("id")); event.setAddress(jsonObj.getString("PatientName")); event.setCategory(jsonObj.getString("category")); event.setDescription(jsonObj.getString("description")); System.out.println(jsonObj.getString("id")); System.out.println(jsonObj.getString("PatientName")); Log.i("vishal" , "In CM loop"); lstevent.add(event); Log.i("vishal", String.valueOf(lstevent)); } // JSONObject jasonObject = new JSONObject(result); } catch (Exception e ) { Toast.makeText(AllEvents.this,""+e,Toast.LENGTH_SHORT).show(); Log.i("vishal",e.toString()); } // Toast.makeText(AllEvents.this,result,Toast.LENGTH_SHORT).show(); Log.i("vishal" , result) ; setuprecyclerview (lstevent); } @Override public void onErrorResponse(VolleyError error) { Log.i("vishal", String.valueOf(error)); } }); // request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() { // @Override // public void onResponse(JSONArray response) { // // JSONObject jasonObject = null ; // // for (int i=0 ; i<response.length() ; i++) { // // try { // jasonObject = response.getJSONObject(i); // Patients patients = new Patients(); // patients.setName(jasonObject.getString( "user")); // patients.setId(jasonObject.getString("pass")); // // // lstPatients.add(patients) ; // // // // } catch (JSONException e ) { // // e.printStackTrace(); // } // // // } // // // setuprecyclerview(lstPatients); // // // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // // } // }); // // // requestQueue = Volley.newRequestQueue(MyPatient.this) ; // requestQueue.add(request) ; // } private void setuprecyclerview(List<Event> lstevent){ RecyclerViewAdapter myadapter = new RecyclerViewAdapter(this ,lstevent); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(myadapter); } }
26.371859
122
0.553735
4098ff1d8c979bc69f4a88cb83f46801dfc806f1
488
package com.alibaba.datax.plugin.unstructuredstorage.util; public class HdfsUtil { private static final double SCALE_TWO = 2.0; private static final double SCALE_TEN = 10.0; private static final int BIT_SIZE = 8; public static int computeMinBytesForPrecision(int precision){ int numBytes = 1; while (Math.pow(SCALE_TWO, BIT_SIZE * numBytes - 1.0) < Math.pow(SCALE_TEN, precision)) { numBytes += 1; } return numBytes; } }
28.705882
97
0.663934
680517e5540a639ca0108d57a302fdf76271fa76
371
package hormone.annotation; import hormone.Model; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target(FIELD) public @interface OneToMany { String targetedBy(); Class<? extends Model> model(); }
21.823529
59
0.787062
0020cefdcca10f63c4aa158f14fe34678437ca80
8,385
/******************************************************************************* * Copyright (c) 2005 Contributors. * 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://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.patterns; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; /** * A visitor that turns a pointcut into a type pattern equivalent for a perthis or pertarget matching: - pertarget(target(Foo)) => * Foo+ (this one is a special case..) - pertarget(execution(* Foo.do()) => Foo - perthis(call(* Foo.do()) => * - perthis(!call(* * Foo.do()) => * (see how the ! has been absorbed here..) * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class PerThisOrTargetPointcutVisitor extends AbstractPatternNodeVisitor { /** A maybe marker */ private final static TypePattern MAYBE = new TypePatternMayBe(); private final boolean m_isTarget; private final ResolvedType m_fromAspectType; public PerThisOrTargetPointcutVisitor(boolean isTarget, ResolvedType fromAspectType) { m_isTarget = isTarget; m_fromAspectType = fromAspectType; } public TypePattern getPerTypePointcut(Pointcut perClausePointcut) { Object o = perClausePointcut.accept(this, perClausePointcut); if (o instanceof TypePattern) { return (TypePattern) o; } else { throw new BCException("perClausePointcut visitor did not return a typepattern, it returned " + o + (o == null ? "" : " of type " + o.getClass())); } } // -- visitor methods, all is like Identity visitor except when it comes to transform pointcuts public Object visit(WithinPointcut node, Object data) { if (m_isTarget) { // pertarget(.. && within(Foo)) => true // pertarget(.. && !within(Foo)) => true as well ! return MAYBE; } else { return node.getTypePattern(); } } public Object visit(WithincodePointcut node, Object data) { if (m_isTarget) { // pertarget(.. && withincode(* Foo.do())) => true // pertarget(.. && !withincode(* Foo.do())) => true as well ! return MAYBE; } else { return node.getSignature().getDeclaringType(); } } public Object visit(WithinAnnotationPointcut node, Object data) { if (m_isTarget) { return MAYBE; } else { return new AnyWithAnnotationTypePattern(node.getAnnotationTypePattern()); } } public Object visit(WithinCodeAnnotationPointcut node, Object data) { if (m_isTarget) { return MAYBE; } else { return MAYBE;// FIXME AV - can we optimize ? perthis(@withincode(Foo)) = hasmethod(..) } } public Object visit(KindedPointcut node, Object data) { if (node.getKind().equals(Shadow.AdviceExecution)) { return MAYBE;// TODO AV - can we do better ? } else if (node.getKind().equals(Shadow.ConstructorExecution) || node.getKind().equals(Shadow.Initialization) || node.getKind().equals(Shadow.MethodExecution) || node.getKind().equals(Shadow.PreInitialization) || node.getKind().equals(Shadow.StaticInitialization)) { SignaturePattern signaturePattern = node.getSignature(); boolean isStarAnnotation = signaturePattern.isStarAnnotation(); // For a method execution joinpoint, we check for an annotation pattern. If there is one we know it will be matched // against the 'primary' joinpoint (the one in the type) - 'super'joinpoints can't match it. If this situation occurs // we can re-use the HasMemberTypePattern to guard on whether the perthis/target should match. pr354470 if (!m_isTarget && node.getKind().equals(Shadow.MethodExecution)) { if (!isStarAnnotation) { return new HasMemberTypePatternForPerThisMatching(signaturePattern); } } return signaturePattern.getDeclaringType(); } else if (node.getKind().equals(Shadow.ConstructorCall) || node.getKind().equals(Shadow.FieldGet) || node.getKind().equals(Shadow.FieldSet) || node.getKind().equals(Shadow.MethodCall)) { if (m_isTarget) { return node.getSignature().getDeclaringType(); } else { return MAYBE; } } else if (node.getKind().equals(Shadow.ExceptionHandler)) { return MAYBE; } else { throw new ParserException("Undetermined - should not happen: " + node.getKind().getSimpleName(), null); } } public Object visit(AndPointcut node, Object data) { return new AndTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right)); } public Object visit(OrPointcut node, Object data) { return new OrTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right)); } public Object visit(NotPointcut node, Object data) { // TypePattern negated = getPerTypePointcut(node.getNegatedPointcut()); // if (MAYBE.equals(negated)) { // return MAYBE; // } // return new NotTypePattern(negated); // AMC - the only safe thing to return here is maybe... // see for example pr114054 return MAYBE; } public Object visit(ThisOrTargetAnnotationPointcut node, Object data) { if (m_isTarget && !node.isThis()) { return new AnyWithAnnotationTypePattern(node.getAnnotationTypePattern()); } else if (!m_isTarget && node.isThis()) { return new AnyWithAnnotationTypePattern(node.getAnnotationTypePattern()); } else { // perthis(@target(Foo)) return MAYBE; } } public Object visit(ThisOrTargetPointcut node, Object data) { if ((m_isTarget && !node.isThis()) || (!m_isTarget && node.isThis())) { String pointcutString = node.getType().toString(); // see pr115788 "<nothing>" means there was a problem resolving types - that will be reported so dont blow up // the parser here.. if (pointcutString.equals("<nothing>")) { return new NoTypePattern(); } // pertarget(target(Foo)) => Foo+ for type pattern matching // perthis(this(Foo)) => Foo+ for type pattern matching // TODO AV - we do like a deep copy by parsing it again.. quite dirty, would need a clean deep copy TypePattern copy = new PatternParser(pointcutString.replace('$', '.')).parseTypePattern(); // TODO AV - see dirty replace from $ to . here as inner classes are with $ instead (#108488) copy.includeSubtypes = true; return copy; } else { // perthis(target(Foo)) => maybe return MAYBE; } } public Object visit(ReferencePointcut node, Object data) { // && pc_ref() // we know there is no support for binding in perClause: perthis(pc_ref(java.lang.String)) // TODO AV - may need some work for generics.. ResolvedPointcutDefinition pointcutDec; ResolvedType searchStart = m_fromAspectType; if (node.onType != null) { searchStart = node.onType.resolve(m_fromAspectType.getWorld()); if (searchStart.isMissing()) { return MAYBE;// this should not happen since concretize will fails but just in case.. } } pointcutDec = searchStart.findPointcut(node.name); return getPerTypePointcut(pointcutDec.getPointcut()); } public Object visit(IfPointcut node, Object data) { return TypePattern.ANY; } public Object visit(HandlerPointcut node, Object data) { // quiet unexpected since a KindedPointcut but do as if... return MAYBE; } public Object visit(CflowPointcut node, Object data) { return MAYBE; } public Object visit(ConcreteCflowPointcut node, Object data) { return MAYBE; } public Object visit(ArgsPointcut node, Object data) { return MAYBE; } public Object visit(ArgsAnnotationPointcut node, Object data) { return MAYBE; } public Object visit(AnnotationPointcut node, Object data) { return MAYBE; } public Object visit(Pointcut.MatchesNothingPointcut node, Object data) { // a small hack since the usual MatchNothing has its toString = "<nothing>" which is not parseable back // while I use back parsing for check purpose. return new NoTypePattern() { public String toString() { return "false"; } }; } /** * A MayBe type pattern that acts as ANY except that !MAYBE = MAYBE * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class TypePatternMayBe extends AnyTypePattern { } }
35.833333
130
0.699583
009487924df6bb69f7fc348241b7874dc38f1599
824
/******************************************************************************* * Copyright (c) 2015 Pawel Zalejko([email protected]). * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/ *******************************************************************************/ package mobile.client.iot.pzalejko.iothome; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
39.238095
93
0.60801
5ad3a60502b6ea20fb0326be0a70845dada4b2f8
8,127
/******************************************************************************* * Copyright 2013 Thomas Letsch ([email protected]) * * 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.vaadin.addons.javaee.table; import java.util.Collection; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.vaadin.addons.javaee.container.EntityContainer; import org.vaadin.addons.javaee.container.EntityItem; import org.vaadin.addons.javaee.fields.factory.GlobalFieldFactory; import org.vaadin.addons.javaee.i18n.TranslationKeys; import org.vaadin.addons.javaee.i18n.TranslationService; import org.vaadin.dialogs.ConfirmDialog; import com.googlecode.javaeeutils.jpa.PersistentEntity; import com.vaadin.data.Container; import com.vaadin.data.util.converter.Converter; import com.vaadin.data.util.filter.UnsupportedFilterException; import com.vaadin.server.ThemeResource; import com.vaadin.shared.ui.MultiSelectMode; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Table; import com.vaadin.ui.UI; import com.vaadin.ui.themes.Reindeer; /** * Base entity table to be subclassed for concrete implementations. * * @author [email protected] * * @param <ENTITY> * The persistent entity */ public abstract class BasicEntityTable<ENTITY extends PersistentEntity> extends Table implements Container.Filterable { private static final long serialVersionUID = 1L; private static final int DEFAULT_PAGE_SIZE = 5; @Inject protected TranslationService translationService; @Inject private GlobalFieldFactory tableFieldFactory; /** * Only query container if a filter is set */ protected boolean needsFilter = true; public BasicEntityTable() { } public BasicEntityTable(Class<ENTITY> entityClass) { setId(entityClass.getSimpleName() + "Table"); } protected abstract EntityContainer<ENTITY> getContainer(); /** * Can be overwritten */ protected void initColumns() { List<String> columnNames = getContainer().getPropertyNames(); initColumns(columnNames); } /** * Can be overwritten */ protected void initColumns(List<String> columnNames) { for (String columnName : columnNames) { addColumn(columnName); } } @PostConstruct protected void init() { if (needsFilter) { getContainer().needsFiltering(); } setEditable(false); setMultiSelect(false); setMultiSelectMode(MultiSelectMode.DEFAULT); setSelectable(true); setBuffered(true); setPageLength(DEFAULT_PAGE_SIZE); setCaption(translationService.getText(getContainer().getEntityClass().getSimpleName() + "s")); setTableFieldFactory(tableFieldFactory); setContainerDataSource(getContainer()); setVisibleColumns(new Object[] {}); initColumns(); } public void clear() { getContainer().clear(); } /** * Adds a generated column with a delete button for each row. Clicking on this button will cause a remove item on the underlying * container, thus deleting the entity behind the current row. */ public void addDeleteColumn() { addColumn(TranslationKeys.TITLE_DELETE, new DeleteColumnGenerator()); } public void addColumn(String name) { Class<?> type = getContainer().getType(name); addColumn(name, type); } public void addColumn(String name, Class<?> type) { addContainerProperty(name, type, null, translationService.getText(name), null, null); } public void addColumn(String name, Converter<String, ?> converter) { addColumn(name); setConverter(name, converter); } public void addColumn(String name, ColumnGenerator columnGenerator) { addGeneratedColumn(name, columnGenerator); setColumnHeader(name, translationService.getText(name)); } @Override public Long getValue() { return (Long) super.getValue(); } @Override public Collection<Filter> getContainerFilters() { return getContainer().getContainerFilters(); } @Override public void addContainerFilter(Filter filter) throws UnsupportedFilterException { getContainer().addContainerFilter(filter); } @Override public void removeContainerFilter(Filter filter) { getContainer().removeContainerFilter(filter); } @Override public void removeAllContainerFilters() { getContainer().removeAllContainerFilters(); } public boolean isAnySelected() { return getValue() != null; } public ENTITY getSelectedEntity() { EntityItem<ENTITY> item = getSelectedEntityItem(); if (item == null) { return null; } ENTITY entity = item.getEntity(); return entity; } @SuppressWarnings("unchecked") public EntityItem<ENTITY> getSelectedEntityItem() { if (getValue() == null || getValue().equals(getNullSelectionItemId())) { return null; } Long id = getValue(); EntityItem<ENTITY> item = (EntityItem<ENTITY>) getItem(id); return item; } public void removeSelectedItem() { Long id = getValue(); getContainer().removeItem(id); } public void selectFirst() { select(firstItemId()); } public void clearSelection() { select(getNullSelectionItemId()); } public void refreshCache() { getContainer().refreshCache(); } public final class DeleteColumnGenerator implements Table.ColumnGenerator { private static final long serialVersionUID = 1L; @Override public Object generateCell(Table source, final Object itemId, Object columnId) { HorizontalLayout layout = new HorizontalLayout(); layout.setMargin(false); Button deleteButton = new Button("", new DeleteButtonListener(itemId)); deleteButton.setIcon(new ThemeResource("icons/silk/delete.png")); deleteButton.setStyleName(Reindeer.BUTTON_SMALL); layout.addComponent(deleteButton); return layout; } } public final class DeleteButtonListener implements Button.ClickListener { private final Object itemId; private static final long serialVersionUID = 1L; private DeleteButtonListener(Object itemId) { this.itemId = itemId; } @Override public void buttonClick(ClickEvent event) { ConfirmDialog.show(UI.getCurrent(), translationService.getText(TranslationKeys.TITLE_DELETE), translationService.getText(TranslationKeys.MESSAGE_REALLY_DELETE), translationService.getText(TranslationKeys.YES), translationService.getText(TranslationKeys.NO), new RowDeletionConfirmListener(itemId)); } } public final class RowDeletionConfirmListener implements ConfirmDialog.Listener { private static final long serialVersionUID = 1L; private Object itemId; public RowDeletionConfirmListener(Object itemId) { this.itemId = itemId; } @Override public void onClose(ConfirmDialog dialog) { if (dialog.isConfirmed()) { getContainer().removeItem(itemId); } } } }
30.667925
135
0.663591
976c1d83ddb5b421c2d5c7aca1e6be89a9a779de
2,368
package com.spark.platform.wx.shop.biz.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.spark.platform.common.base.enums.DelFlagEnum; import com.spark.platform.wx.shop.api.entity.user.ShopUserCollect; import com.spark.platform.wx.shop.api.entity.user.ShopUserFootprint; import com.spark.platform.wx.shop.biz.user.dao.ShopUserFootprintDao; import com.spark.platform.wx.shop.biz.user.service.ShopUserFootprintService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.commons.lang3.StringUtils; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * <p> * 用户浏览足迹 服务实现类 * </p> * * @author wangdingfeng * @since 2020-12-10 */ @Service public class ShopUserFootprintServiceImpl extends ServiceImpl<ShopUserFootprintDao, ShopUserFootprint> implements ShopUserFootprintService { @Override public IPage listPage(Page page, ShopUserFootprint shopUserFootprint) { QueryWrapper queryWrapper = new QueryWrapper<ShopUserCollect>();; queryWrapper.like(StringUtils.isNotBlank(shopUserFootprint.getGoodsTitle()),"g.title",shopUserFootprint.getGoodsTitle()) .eq(true,"f.del_flag", DelFlagEnum.NORMAL.getValue()) .eq(null != shopUserFootprint.getGoodsId(),"f.goods_id",shopUserFootprint.getGoodsId()) .eq(null != shopUserFootprint.getUserId(),"f.user_id",shopUserFootprint.getUserId()) .orderByDesc("f.create_date"); return super.baseMapper.listPage(page, queryWrapper); } @Override public int count(Integer userId) { return super.count(Wrappers.<ShopUserFootprint>lambdaQuery().eq(ShopUserFootprint::getUserId,userId)); } @Override @Async public void saveFootprint(Integer userId, Integer goodsId) { int count = super.baseMapper.findToday(userId,goodsId); if(count > 0){ return; } ShopUserFootprint shopUserFootprint = new ShopUserFootprint(); shopUserFootprint.setUserId(userId); shopUserFootprint.setGoodsId(goodsId); super.save(shopUserFootprint); } }
41.54386
140
0.745777
b66b80e6694c5ce8bcefaeec40e380acb27eefad
1,941
package oop.variables; public class Variables { /* * instance variables * - class level * - belong to the class * - belong to the objects of the class * - initialised whenever we create an object * - different copies are created every time we create objects * * local variables * - method level * - belong to the method * - initialised whenever we call a method * * static variables * - class level * - belong to the class * - DON'T belong to the objects of the class * - initialised only once at the start of execution * before instance variables * - only one copy of the static variable is created * and shared for every object instanciated * - if any object operate on the static variable * the changes will affect the other objects aswell * */ public static void main(String[] args) { Fan fanOne = new Fan(false); Fan fanTwo = new Fan(false); // instance variable: isOn Boolean localVaribaleIsOn = fanOne.isOn; // local variable: localVariable Integer localVariable = 0; // static varible: staticVariable Integer staticVariableFan = Fan.staticVariable; // only one static variable exists no matter how many objects you have fanOne.printStaticVariable(); fanTwo.printStaticVariable(); } } class Fan { public Boolean isOn; public static Integer staticVariable = 0; public Fan(Boolean isOn) { this.isOn = isOn; } public void checkFanStatus() { if (isOn) System.out.println("Fan is On"); else System.out.println("Fan is Off"); } public void turnOn() { isOn = !isOn; } public void turnOff() { isOn = !isOn; } public void printStaticVariable() { staticVariable++; System.out.println(staticVariable); } }
24.56962
78
0.615662
3256e6b0d6f5090ec9cfa8b38dc1b8db83fb5fb1
7,620
/* Copyright (c) 2017 Lancaster Software & Service * * 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 lss.bef.core; import java.util.Iterator; import java.util.Random; import java.util.Hashtable; //import corej.context.Log; //import corej.context.internal.ClassFactoryUtil; //import com.sun.jmx.remote.opt.util.Service; import java.lang.InheritableThreadLocal; // INTERNAL CLASSES //import corej.object.Handler; //import corej.object.HandlerImp; // WELL KNOWN CLASSES //import corej.network.ServerRequestHandler; //import corej.network.ServerRequestHandlerImp; //import corej.network.ServerRequestProcessor; //import corej.network.ServerRequestProcessorBase; //import corej.network.file.FileClient; //import corej.network.file.FileClientImp; //import corej.network.file.FileServer; //import corej.network.file.FileServerImp; //import corej.network.socket.SocketClient; //import corej.network.socket.SocketClientImp; //import corej.network.socket.SocketServer; //import corej.network.socket.SocketServerImp; //import corej.util.StreamUtil; //import corej.util.StreamUtilImp; //import corej.util.StringTokenizerEx; //import corej.util.StringTokenizerExImp; import lss.bef.core.internal.ClassFactoryUtil; import lss.bef.core.internal.HandlerImp; // INTERNALY KNOWN CLASSES import lss.bef.entity.Tuple; import lss.bef.entity.TupleBase; import lss.bef.core.Factory; import lss.bef.entity.EntityDefines; public class FactoryImp implements Factory { // FACTORY SUPPORT private static Random discriminator = new Random(); // private static InheritableThreadLocal<SessionContainer> tLocalSessionContainer = new InheritableThreadLocal(); private Hashtable<Class,Class> internalClasses = null; private Hashtable<String,Class> internalClassesByName = null; private Hashtable<Class,Class> wellKnownClasses = null; // private LoggerImp logController = null; // LOGGERS public FactoryImp() { this.internalClasses = new Hashtable<Class,Class>(); this.internalClassesByName = new Hashtable<String,Class>(); this.wellKnownClasses = new Hashtable<Class,Class>(); initializeInternalObjectDictionary(); } // PUBLIC METHODS /* public Class classObj( String componentName ) { Class objRet = ClassFactoryUtil.getClassForName( componentName ); return objRet; } */ /* public SessionContainer getSessionContainer() { SessionContainer objRet = tLocalSessionContainer.get(); if( objRet == null ) { String strRet = this.getUniqueId( "Session#" ); objRet = new SessionContainerImp( strRet ); tLocalSessionContainer.set( objRet ); } return objRet; } */ public Object instance( String componentName ) { Object objRet = null; Class cls = this.internalClassesByName.get( componentName ); if( cls == null ) cls = ClassFactoryUtil.getClassForName( componentName ); System.out.println( "Found class for [" + componentName + "] Class=" + cls.getName() ); if( cls != null ) { objRet = getInstance( cls ); } return objRet; } /* public Object instance( Class cls, Object ... objects ) { return getInstance( cls, objects ); } public Object instance( String componentName, Object ... objects ) { Object objRet = null; Class cls = ClassFactoryUtil.getClassForName( componentName ); // System.out.println( "Found class for [" + componentName + "] Class=" + cls.getName() ); if( cls != null ) { objRet = getInstance( cls, objects ); } return objRet; } */ // PRIVATE METHODS private void initializeInternalObjectDictionary() { // this.internalClasses.put( Handler.class, HandlerImp.class ); // this.wellKnownClasses.put( ServerRequestHandler.class, ServerRequestHandlerImp.class ); // this.wellKnownClasses.put( ServerRequestProcessor.class, ServerRequestProcessorBase.class ); // this.wellKnownClasses.put( FileClient.class, FileClientImp.class ); // this.wellKnownClasses.put( FileServer.class, FileServerImp.class ); // this.wellKnownClasses.put( SocketClient.class, SocketClientImp.class ); // this.wellKnownClasses.put( SocketServer.class, SocketServerImp.class ); // this.wellKnownClasses.put( StreamUtil.class, StreamUtilImp.class ); // this.wellKnownClasses.put( StringTokenizerEx.class, StringTokenizerExImp.class ); this.wellKnownClasses.put( Tuple.class, TupleBase.class ); this.internalClassesByName.put( EntityDefines.TupleBase, Tuple.class ); } private Object getInstance( Class cls, Object ... objects ) { Object objRet = null; // FIRST - we look if this class is one of the internal very well know entities that we don't want // delegate to any other factory if( this.internalClasses.containsKey( cls ) ) { if( objects != null && objects.length > 0 ) { objRet = ClassFactoryUtil.createObject( internalClasses.get( cls ), cls, objects ); } else { objRet = ClassFactoryUtil.createObject( internalClasses.get( cls ), cls ); } if( objRet instanceof HandlerImp) { HandlerImp obj = (HandlerImp)objRet; } } else if( this.wellKnownClasses.containsKey( cls ) ) { if( objects != null && objects.length > 0 ) { objRet = ClassFactoryUtil.createObject( wellKnownClasses.get( cls ), cls, objects ); } else { objRet = ClassFactoryUtil.createObject( wellKnownClasses.get( cls ), cls ); } } // now we will try to use resolve method if( objRet == null ) { objRet = resolve( cls ); if( objRet == null ) { // LAST - this is the last resource - in this case we will simple create the object using the // default class loader if( objects != null && objects.length > 0 ) { objRet = ClassFactoryUtil.createObject( cls, objects ); } else { objRet = ClassFactoryUtil.createObject( cls ); } } if( objRet == null ) { System.out.println( "On FactoryCore.instance(" + cls.getName() + ") - Cannot find suitable factory" ); } } return objRet; } private Object resolve( Class cls ) { Object objRet = null; /* Iterator it = Service.providers( cls, cls.getClassLoader() ); // This loop means that if there is more than one implementation the resolve will stick with // the last one - there is no guarantee of any order of the JARS will influence the sequence // of providers - better to make sure you have only one implementation while( it.hasNext() ) { objRet = it.next(); } */ return objRet; } }
29.083969
116
0.707218
6c367b99b34644a6fb287208efbda4344d82568f
1,991
package lylace.lab; public class Lab02 { public static void main(String[] arg) { // #3 ~ #15 // #3 // int x, y, z; // 3 * x // 3 * x + y // (x + y) / 7 // (3 * x + y) / (z + 2) // #4 // double number = (1 / 3) * 3; // 숫자 default값이 int이므로 1/3 은 0으로 되므로 // 0*3 = 0 인데 변수타입이 double로 되어있으므로 0.0 // System.out.printf("(1/3) * 3 = %1.0f%n", (1d / 3) * 3);//가까운 값을 구하는 식 // #5 // int quotient, remainder; // quotient = 7 / 3; // remainder = 7 % 3; // System.out.println(quotient); // int 타입이라 정수부분인 2만 남음 // System.out.println(remainder); // // #6 // int result = 11; // result /= 2; // /= 대입연산자 11/2 이고, int 타입이라 정수부분인 5만 남음 // System.out.println(result); // #7 // double x = 2.5, y = -1.5; // int m = 18, n = 4; // System.out.println(x + n * y - (x + n) * y); // System.out.println(m / n + m % n); // System.out.println(5 * x - n / 5); // System.out.println(1 - (1 - (1 - (1 - (1 - n))))); // #8 논리 연산자의 단축평가 // System.out.println(true||); // #9 - 문자열로 처리 // System.out.print("May 13, 1988 fell on day number\n"); // System.out.println( // ((13 + (13 * 3 - 1) / 5 + 1988 % 100 + 1988 % 100 / 4 + 1988 / 400 - 2 * // (1988 / 100)) % 7 + 7) % 7); // // 특정일의 요일을 알아내는 수식 // int year = 1988, month = 5, day = 13; // System.out.println((year + (year / 4) - (year / 100) + (year / 400) + (13 * // month + 8) / 5 + day) % 7); // System.out.println("//hello there" + '9' + 7); // 문자열 + 문자 = 문자열, 문자 + 문자 = // 코드 숫자계산 // System.out.println("Not x is" + true);// 문자열 + boolean타입 키워드 = 문자열 // // // #12 형변환 : 축소 // int n = (int) 3.9; // System.out.println("n ==" + n); // // #13 증가 감소 연산자 // int p = 3; // p++; // System.out.println("p ==" + p); // p--; // System.out.println("p ==" + p); // #15 char a, b; a = 'b'; System.out.println(a); System.out.println((int) 'a'); System.out.println((int) a); } }
26.546667
81
0.466097
89b9d567e13d06e74dfc05fc4c13b858e717046b
243
package com.hubspot.httpql.error; public class UnknownFieldException extends RuntimeException { private static final long serialVersionUID = -5969282691775554298L; public UnknownFieldException(String message) { super(message); } }
24.3
69
0.794239
b1c9ffb62b2d8f6d443509dcb886e76dba88bea8
1,340
package com.bumptech.glide.f.a; import android.graphics.drawable.Drawable; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; // compiled from: DrawableCrossFadeFactory.java public final class a<T extends Drawable> implements d<T> { private final g<T> a; private final int b; private b<T> c; private b<T> d; // compiled from: DrawableCrossFadeFactory.java private static class a implements a { private final int a; a() { this.a = 300; } public final Animation a() { Animation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); alphaAnimation.setDuration((long) this.a); return alphaAnimation; } } public a() { this((byte) 0); } private a(byte b) { this(new g(new a())); } private a(g<T> gVar) { this.a = gVar; this.b = 300; } public final c<T> a(boolean z, boolean z2) { if (z) { return e.b(); } if (z2) { if (this.c == null) { this.c = new b(this.a.a(false, true), this.b); } return this.c; } if (this.d == null) { this.d = new b(this.a.a(false, false), this.b); } return this.d; } }
23.103448
70
0.529851
fcfbdde8a635aeb7e2401ba9637d428bec5e6929
48,003
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.apimgt.migration.client; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.internal.APIManagerComponent; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.migration.APIMigrationException; import org.wso2.carbon.apimgt.migration.client.internal.ServiceHolder; import org.wso2.carbon.apimgt.migration.util.Constants; import org.wso2.carbon.apimgt.migration.util.RegistryService; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.governance.api.exception.GovernanceException; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.FileUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.TreeMap; import java.util.Optional; import java.util.Set; import java.util.StringTokenizer; import static org.wso2.carbon.apimgt.impl.utils.APIUtil.getTenantDomainFromTenantId; import static org.wso2.carbon.apimgt.migration.util.Constants.*; public class MigrationClientBase { private static final Log log = LogFactory.getLog(MigrationClientBase.class); private List<Tenant> tenantsArray; private static final String IS_MYSQL_SESION_MODE_EXISTS = "SELECT COUNT(@@SESSION.sql_mode)"; private static final String GET_MYSQL_SESSION_MODE = "SELECT @@SESSION.sql_mode AS MODE"; private static final String NO_ZERO_DATE_MODE = "NO_ZERO_DATE"; private static final String MIGRATION = "Migration"; private static final String VERSION_3 = "3.0.0"; private static final String META = "Meta"; private final String V400 = "4.0.0"; private String tenantArguments; private String blackListTenantArguments; private final String tenantRange; private final TenantManager tenantManager; public MigrationClientBase(String tenantArguments, String blackListTenantArguments, String tenantRange, TenantManager tenantManager) throws UserStoreException { this.tenantManager = tenantManager; this.tenantRange = tenantRange; if (tenantArguments != null) { // Tenant arguments have been provided so need to load specific ones tenantArguments = tenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs tenantsArray = new ArrayList<>(); buildTenantList(tenantManager, tenantsArray, tenantArguments); this.tenantArguments = tenantArguments; } else if (blackListTenantArguments != null) { blackListTenantArguments = blackListTenantArguments.replaceAll("\\s", ""); // Remove spaces and tabs List<Tenant> blackListTenants = new ArrayList<>(); buildTenantList(tenantManager, blackListTenants, blackListTenantArguments); this.blackListTenantArguments = blackListTenantArguments; List<Tenant> allTenants = new ArrayList<>(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); allTenants.add(superTenant); tenantsArray = new ArrayList<>(); for (Tenant tenant : allTenants) { boolean isBlackListed = false; for (Tenant blackListTenant : blackListTenants) { if (blackListTenant.getId() == tenant.getId()) { isBlackListed = true; break; } } if (!isBlackListed) { tenantsArray.add(tenant); } } } else if (tenantRange != null) { tenantsArray = new ArrayList<Tenant>(); int l, u; try { l = Integer.parseInt(tenantRange.split("-")[0].trim()); u = Integer.parseInt(tenantRange.split("-")[1].trim()); } catch (Exception e) { throw new UserStoreException("TenantRange argument is not properly set. use format 1-12", e); } log.debug("no of Tenants " + tenantManager.getAllTenants().length); int lastIndex = tenantManager.getAllTenants().length - 1; log.debug("last Tenant id " + tenantManager.getAllTenants()[lastIndex].getId()); for (Tenant t : tenantManager.getAllTenants()) { if (t.getId() > l && t.getId() < u) { log.debug("using tenants " + t.getDomain() + "(" + t.getId() + ")"); tenantsArray.add(t); } } } else { // Load all tenants tenantsArray = new ArrayList<>(Arrays.asList(tenantManager.getAllTenants())); Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantsArray.add(superTenant); } setAdminUserName(tenantManager); } /** * * @param registryService registryService * @param migrateFromVersion migrateFromVersion * @return */ public TreeMap<String, MigrationClient> getMigrationServiceList(RegistryService registryService, String migrateFromVersion) { HashMap<String, MigrationClient> serviceList = new HashMap<>(); if (V400.equals(migrateFromVersion)) { MigrateFrom400 migrateFrom400 = null; try { migrateFrom400 = new MigrateFrom400(tenantArguments, blackListTenantArguments, tenantRange, registryService, tenantManager); } catch (UserStoreException e) { log.error("User store exception occurred while creating 400 migration client", e); } serviceList.put(V400, migrateFrom400); } return new TreeMap<>(serviceList); } /** * * @param migrationServiceList * @param continueFromStep * @throws APIMigrationException * @throws SQLException */ public void doMigration(TreeMap<String, MigrationClient> migrationServiceList, String continueFromStep) throws APIMigrationException, SQLException { if (continueFromStep == null) { continueFromStep = All_STEPS; } for (Map.Entry<String, MigrationClient> service : migrationServiceList.entrySet()) { MigrationClient serviceClient = service.getValue(); switch (continueFromStep) { case REGISTRY_RESOURCE_MIGRATION: registryResourceMigration(serviceClient); updateScopeRoleMappings(serviceClient); migrateTenantConfToDB(serviceClient); registryDataPopulation(serviceClient); break; case SCOPE_ROLE_MAPPING_MIGRATION: updateScopeRoleMappings(serviceClient); migrateTenantConfToDB(serviceClient); registryDataPopulation(serviceClient); break; case TENANT_CONF_MIGRATION: migrateTenantConfToDB(serviceClient); registryDataPopulation(serviceClient); break; case REGISTRY_DATA_POPULATION: registryDataPopulation(serviceClient); break; case All_STEPS: databaseMigration(serviceClient); registryResourceMigration(serviceClient); updateScopeRoleMappings(serviceClient); migrateTenantConfToDB(serviceClient); registryDataPopulation(serviceClient); default: log.info("The step: " + continueFromStep + " is not defined"); } } } public void doValidation(TreeMap<String, MigrationClient> migrationServiceList, String runPreMigrationStep) throws APIMigrationException { log.info("Executing pre migration step .........."); for (Map.Entry<String, MigrationClient> service : migrationServiceList.entrySet()) { MigrationClient serviceClient = service.getValue(); serviceClient.preMigrationValidation(runPreMigrationStep); } log.info("Successfully executed the pre validation step."); } private void databaseMigration(MigrationClient serviceClient) throws APIMigrationException, SQLException { log.info("Start migrating databases .........."); serviceClient.databaseMigration(); log.info("Successfully migrated databases."); } private void registryResourceMigration(MigrationClient serviceClient) throws APIMigrationException { log.info("Start migrating api rxt .........."); serviceClient.registryResourceMigration(); log.info("Successfully migrated api rxt."); } private void updateScopeRoleMappings(MigrationClient serviceClient) throws APIMigrationException { log.info("Start migrating Role Scope Tenant Conf Mappings .........."); serviceClient.updateScopeRoleMappings(); log.info("Successfully migrated Role Scope Tenant Conf Mappings."); } private void migrateTenantConfToDB(MigrationClient serviceClient) throws APIMigrationException { log.info("Start migrating Tenant Conf .........."); serviceClient.migrateTenantConfToDB(); log.info("Successfully migrated Tenant Conf to Database."); } private void registryDataPopulation(MigrationClient serviceClient) throws APIMigrationException { log.info("Start populating data for new properties in api artifacts .........."); serviceClient.registryDataPopulation(); log.info("Successfully migrated data for api artifacts.........."); } private void buildTenantList(TenantManager tenantManager, List<Tenant> tenantList, String tenantArguments) throws UserStoreException { if (tenantArguments.contains(",")) { // Multiple arguments specified String[] parts = tenantArguments.split(","); for (String part : parts) { if (part.length() > 0) { populateTenants(tenantManager, tenantList, part); } } } else { // Only single argument provided populateTenants(tenantManager, tenantList, tenantArguments); } } private void populateTenants(TenantManager tenantManager, List<Tenant> tenantList, String argument) throws UserStoreException { if (log.isDebugEnabled()) { log.debug("Argument provided : " + argument); } if (argument.contains("@")) { // Username provided as argument int tenantID = tenantManager.getTenantId(argument); if (tenantID != -1) { tenantList.add(tenantManager.getTenant(tenantID)); } else { log.error("Tenant does not exist for username " + argument); } } else { // Domain name provided as argument if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(argument)) { Tenant superTenant = new Tenant(); superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); superTenant.setId(MultitenantConstants.SUPER_TENANT_ID); tenantList.add(superTenant); } else { Tenant[] tenants = tenantManager.getAllTenantsForTenantDomainStr(argument); if (tenants.length > 0) { tenantList.addAll(Arrays.asList(tenants)); } else { log.error("Tenant does not exist for domain " + argument); } } } } private void setAdminUserName(TenantManager tenantManager) throws UserStoreException { log.debug("Setting tenant admin names"); for (int i = 0; i < tenantsArray.size(); ++i) { Tenant tenant = tenantsArray.get(i); if (tenant.getId() == MultitenantConstants.SUPER_TENANT_ID) { tenant.setAdminName("admin"); } else { tenantsArray.set(i, tenantManager.getTenant(tenant.getId())); } } } protected List<Tenant> getTenantsArray() { return tenantsArray; } protected void updateAPIManagerDatabase(String sqlScriptPath) throws SQLException { log.info("Database migration for API Manager started"); Connection connection = null; PreparedStatement preparedStatement = null; Statement statement = null; ResultSet resultSet = null; try { connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); String dbType = MigrationDBCreator.getDatabaseType(connection); if (Constants.DB_TYPE_MYSQL.equals(dbType)) { statement = connection.createStatement(); resultSet = statement.executeQuery(GET_MYSQL_SESSION_MODE); if (resultSet.next()) { String mode = resultSet.getString("MODE"); log.info("MySQL Server SQL Mode is : " + mode); if (mode.contains(NO_ZERO_DATE_MODE)) { File timeStampFixScript = new File(sqlScriptPath + dbType + "-timestamp_fix.sql"); if (timeStampFixScript.exists()) { log.info(NO_ZERO_DATE_MODE + " mode detected, run schema compatibility script"); InputStream is = new FileInputStream(timeStampFixScript); List<String> sqlStatements = readSQLStatements(is, dbType); for (String sqlStatement : sqlStatements) { preparedStatement = connection.prepareStatement(sqlStatement); preparedStatement.execute(); connection.commit(); } } } } } InputStream is = new FileInputStream(sqlScriptPath + dbType + ".sql"); List<String> sqlStatements = readSQLStatements(is, dbType); for (String sqlStatement : sqlStatements) { log.debug("SQL to be executed : " + sqlStatement); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { statement = connection.createStatement(); statement.executeUpdate(sqlStatement); } else { preparedStatement = connection.prepareStatement(sqlStatement); preparedStatement.execute(); } } connection.commit(); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while migrating databases", e); connection.rollback(); } finally { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } log.info("DB resource migration done for all the tenants"); } /** * This method is used to remove the FK constraint which is unnamed * This finds the name of the constraint and build the query to delete the constraint and execute it * * @param sqlScriptPath path of sql script * @throws SQLException */ protected void dropFKConstraint(String sqlScriptPath) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Statement statement = null; try { connection = APIMgtDBUtil.getConnection(); String dbType = MigrationDBCreator.getDatabaseType(connection); String queryToExecute = IOUtils.toString( new FileInputStream(new File(sqlScriptPath + "constraint" + File.separator + dbType + ".sql")), "UTF-8"); String queryArray[] = queryToExecute.split(Constants.LINE_BREAK); connection.setAutoCommit(false); statement = connection.createStatement(); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryArray[0] = queryArray[0].replace(Constants.DELIMITER, ""); queryArray[0] = queryArray[0].replace("<AM_DB_NAME>", connection.getMetaData().getUserName()); } resultSet = statement.executeQuery(queryArray[0]); String constraintName = null; while (resultSet.next()) { constraintName = resultSet.getString("constraint_name"); } if (constraintName != null) { queryToExecute = queryArray[1].replace("<temp_key_name>", constraintName); if (Constants.DB_TYPE_ORACLE.equals(dbType)) { queryToExecute = queryToExecute.replace(Constants.DELIMITER, ""); } if (queryToExecute.contains("\\n")) { queryToExecute = queryToExecute.replace("\\n", ""); } preparedStatement = connection.prepareStatement(queryToExecute); preparedStatement.execute(); connection.commit(); } } catch (APIMigrationException e) { //Foreign key might be already deleted, log the error and let it continue log.error("Error occurred while deleting foreign key", e); } catch (IOException e) { //If user does not add the file migration will continue and migrate the db without deleting // the foreign key reference log.error("Error occurred while finding the foreign key deletion query for execution", e); } catch (Exception e) { /* MigrationDBCreator extends from org.wso2.carbon.utils.dbcreator.DatabaseCreator and in the super class method getDatabaseType throws generic Exception */ log.error("Error occurred while deleting foreign key", e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { log.error("Unable to close the statement", e); } } APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet); } } private List<String> readSQLStatements(InputStream is, String dbType) { List<String> sqlStatements = new ArrayList<>(); try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF8")); String sqlQuery = ""; boolean isFoundQueryEnd = false; String line; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); if (line.startsWith("//") || line.startsWith("--")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(line); if (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } if (line.contains("\\n")) { line = line.replace("\\n", ""); } sqlQuery += ' ' + line; if (line.contains(";")) { isFoundQueryEnd = true; } if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_ORACLE.equals(dbType)) { if ("/".equals(line.trim())) { isFoundQueryEnd = true; } else { isFoundQueryEnd = false; } sqlQuery = sqlQuery.replaceAll("/", ""); } if (org.wso2.carbon.apimgt.migration.util.Constants.DB_TYPE_DB2.equals(dbType)) { sqlQuery = sqlQuery.replace(";", ""); } if (isFoundQueryEnd) { if (sqlQuery.length() > 0) { if (log.isDebugEnabled()) { log.debug("SQL to be executed : " + sqlQuery); } sqlStatements.add(sqlQuery.trim()); } // Reset variables to read next SQL sqlQuery = ""; isFoundQueryEnd = false; } } bufferedReader.close(); } catch (IOException e) { log.error("Error while reading SQL statements from stream", e); } return sqlStatements; } /** * This method is used to update the API artifacts in the registry * - to migrate Publisher Access Control feature related data. * - to add overview_type property to API artifacts * - to add 'enableStore' rxt field * * @throws APIMigrationException */ public void updateGenericAPIArtifacts(RegistryService registryService) throws APIMigrationException { for (Tenant tenant : getTenantsArray()) { try { registryService.startTenantFlow(tenant); log.debug("Updating APIs for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')'); GenericArtifact[] artifacts = registryService.getGenericAPIArtifacts(); for (GenericArtifact artifact : artifacts) { String path = artifact.getPath(); if (registryService.isGovernanceRegistryResourceExists(path)) { Object apiResource = registryService.getGovernanceRegistryResource(path); if (apiResource == null) { continue; } registryService.updateGenericAPIArtifactsForAccessControl(path, artifact); registryService.updateGenericAPIArtifact(path, artifact); registryService.updateEnableStoreInRxt(path,artifact); } } log.info("Completed Updating API artifacts tenant ---- " + tenant.getId() + '(' + tenant.getDomain() + ')'); } catch (GovernanceException e) { log.error("Error while accessing API artifact in registry for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')', e); } catch (RegistryException | UserStoreException e) { log.error("Error while updating API artifact in the registry for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')', e); } finally { registryService.endTenantFlow(); } } } public void migrateFaultSequencesInRegistry(RegistryService registryService) { /* change the APIMgtFaultHandler class name in debug_json_fault.xml and json_fault.xml this method will read the new *json_fault.xml sequences from <APIM_2.1.0_HOME>/repository/resources/customsequences/fault and overwrite what is there in registry for all the tenants*/ log.info("Fault sequence migration from APIM 2.0.0 to 2.1.0 has started"); String apim210FaultSequencesLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File .separator + "resources" + File.separator + "customsequences" + File.separator + "fault"; String apim210FaultSequenceFile = apim210FaultSequencesLocation + File.separator + "json_fault.xml"; String api210DebugFaultSequenceFile = apim210FaultSequencesLocation + File.separator + "debug_json_fault.xml"; // read new files String apim210FaultSequenceContent = null; try { apim210FaultSequenceContent = FileUtil.readFileToString(apim210FaultSequenceFile); } catch (IOException e) { log.error("Error in reading file: " + apim210FaultSequenceFile, e); } String apim210DebugFaultSequenceContent = null; try { apim210DebugFaultSequenceContent = FileUtil.readFileToString(api210DebugFaultSequenceFile); } catch (IOException e) { log.error("Error in reading file: " + api210DebugFaultSequenceFile, e); } if (StringUtils.isEmpty(apim210FaultSequenceContent) && StringUtils.isEmpty(apim210DebugFaultSequenceContent)) { // nothing has been read from <APIM_NEW_HOME>/repository/resources/customsequences/fault log.error("No content read from <APIM_NEW_HOME>/repository/resources/customsequences/fault location, " + "aborting migration"); return; } for (Tenant tenant : getTenantsArray()) { try { registryService.startTenantFlow(tenant); // update json_fault.xml and debug_json_fault.xml in registry if (StringUtils.isNotEmpty(apim210FaultSequenceContent)) { try { final String jsonFaultResourceRegistryLocation = "/apimgt/customsequences/fault/json_fault.xml"; if (registryService.isGovernanceRegistryResourceExists(jsonFaultResourceRegistryLocation)) { // update registryService.updateGovernanceRegistryResource(jsonFaultResourceRegistryLocation, apim210FaultSequenceContent); } else { // add registryService.addGovernanceRegistryResource(jsonFaultResourceRegistryLocation, apim210FaultSequenceContent, "application/xml"); } log.info("Successfully migrated json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId()); } catch (UserStoreException e) { log.error("Error in updating json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId(), e); } catch (RegistryException e) { log.error("Error in updating json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId(), e); } } if (StringUtils.isNotEmpty(apim210DebugFaultSequenceContent)) { try { final String debugJsonFaultResourceRegistryLocation = "/apimgt/customsequences/fault/debug_json_fault.xml"; if (registryService.isGovernanceRegistryResourceExists(debugJsonFaultResourceRegistryLocation)) { // update registryService.updateGovernanceRegistryResource(debugJsonFaultResourceRegistryLocation, apim210DebugFaultSequenceContent); } else { // add registryService.addGovernanceRegistryResource(debugJsonFaultResourceRegistryLocation, apim210DebugFaultSequenceContent, "application/xml"); } log.info("Successfully migrated debug_json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId()); } catch (UserStoreException e) { log.error("Error in updating debug_json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId(), e); } catch (RegistryException e) { log.error("Error in updating debug_json_fault.xml in registry for tenant: " + tenant.getDomain() + ", tenant id: " + tenant.getId(), e); } } } finally { registryService.endTenantFlow(); } } } /** * This method is used to migrate rxt * * @throws APIMigrationException */ public void rxtMigration(RegistryService registryService) throws APIMigrationException { log.info("Rxt migration for API Manager started."); String rxtName = "api.rxt"; String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "migration-resources" + File.separator + "rxts" + File.separator + rxtName; for (Tenant tenant : getTenantsArray()) { try { registryService.startTenantFlow(tenant); log.info("Updating api.rxt for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')'); //Update api.rxt file String rxt = FileUtil.readFileToString(rxtDir); registryService.updateRXTResource(rxtName, rxt); log.info("End Updating api.rxt for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')'); } catch (IOException e) { log.error("Error when reading api.rxt from " + rxtDir + " for tenant " + tenant.getId() + '(' + tenant .getDomain() + ')', e); } catch (RegistryException e) { log.error("Error while updating api.rxt in the registry for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')', e); } catch (UserStoreException e) { log.error("Error while updating api.rxt in the registry for tenant " + tenant.getId() + '(' + tenant.getDomain() + ')', e); } finally { registryService.endTenantFlow(); } } log.info("Rxt resource migration done for all the tenants"); } /** * Gets the content of the local tenant-conf.json as a JSON Object * * @return JSON content of the local tenant-conf.json * @throws IOException error while reading local tenant-conf.json */ protected static JSONObject getTenantConfJSONFromFile() throws IOException, APIMigrationException { JSONObject tenantConfJson = null; try { String tenantConfDataStr = new String(getTenantConfFromFile(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); tenantConfJson = (JSONObject) parser.parse(tenantConfDataStr); if (tenantConfJson == null) { throw new APIMigrationException("tenant-conf.json (in file system) content cannot be null"); } } catch (ParseException e) { log.error("Error while parsing tenant-conf.json from file system."); } return tenantConfJson; } /** * Gets the content of the local tenant-conf.json as a JSON Object * * @return JSON content of the local tenant-conf.json * @throws IOException error while reading local tenant-conf.json */ protected static byte[] getTenantConfFromFile() throws IOException { JSONObject tenantConfJson = null; String tenantConfLocation = CarbonUtils.getCarbonHome() + File.separator + APIConstants.RESOURCE_FOLDER_LOCATION + File.separator + APIConstants.API_TENANT_CONF; File tenantConfFile = new File(tenantConfLocation); byte[] data; if (tenantConfFile.exists()) { // Load conf from resources directory in pack if it exists try (FileInputStream fileInputStream = new FileInputStream(tenantConfFile)) { data = IOUtils.toByteArray(fileInputStream); } } else { // Fallback to loading the conf that is stored at jar level if file does not exist in pack try (InputStream inputStream = APIManagerComponent.class .getResourceAsStream("/tenant/" + APIConstants.API_TENANT_CONF)) { data = IOUtils.toByteArray(inputStream); } } return data; } public static JSONObject getTenantConfigFromRegistry(int tenantId) throws APIMigrationException { try { if (tenantId != org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID) { APIUtil.loadTenantRegistry(tenantId); } org.wso2.carbon.registry.core.service.RegistryService registryService = ServiceHolder.getRegistryService(); UserRegistry registry = registryService.getConfigSystemRegistry(tenantId); Resource resource; if (registry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) { resource = registry.get(APIConstants.API_TENANT_CONF_LOCATION); String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); return (JSONObject) parser.parse(content); } else { return null; } } catch (RegistryException | ParseException e) { throw new APIMigrationException("Error while getting tenant config from registry for tenant: " + tenantId, e); } } public static void updateTenantConf(String tenantConfString, int tenantId) throws APIMigrationException { org.wso2.carbon.registry.core.service.RegistryService registryService = ServiceHolder.getRegistryService(); try { UserRegistry registry = registryService.getConfigSystemRegistry(tenantId); updateTenantConf(registry, tenantConfString.getBytes()); } catch (RegistryException e) { throw new APIMigrationException("Error while saving tenant conf to the registry of tenant " + tenantId, e); } } private static void updateTenantConf(UserRegistry registry, byte[] data) throws RegistryException { Resource resource = registry.newResource(); resource.setMediaType(APIConstants.API_TENANT_CONF_MEDIA_TYPE); resource.setContent(data); registry.put(APIConstants.API_TENANT_CONF_LOCATION, resource); } /** * Loads tenant-conf.json (tenant config) to registry from the tenant-conf.json available in the file system. * If any REST API scopes are added to the local tenant-conf.json, they will be updated in the registry. * * @param tenantID tenant Id * @throws APIManagementException when error occurred while loading the tenant-conf to registry */ public static void loadAndSyncTenantConf(int tenantID) throws APIMigrationException { org.wso2.carbon.registry.core.service.RegistryService registryService = ServiceHolder.getRegistryService(); try { UserRegistry registry = registryService.getConfigSystemRegistry(tenantID); byte[] data = getTenantConfFromFile(); if (registry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) { log.debug("tenant-conf of tenant " + tenantID + " is already uploaded to the registry"); Optional<Byte[]> migratedTenantConf = migrateTenantConfScopes(tenantID); if (migratedTenantConf.isPresent()) { log.debug("Detected new additions to tenant-conf of tenant " + tenantID); data = ArrayUtils.toPrimitive(migratedTenantConf.get()); } else { log.debug("No changes required in tenant-conf.json of tenant " + tenantID); return; } } log.debug("Adding/updating tenant-conf.json to the registry of tenant " + tenantID); updateTenantConf(registry, data); log.debug("Successfully added/updated tenant-conf.json of tenant " + tenantID); } catch (RegistryException e) { throw new APIMigrationException("Error while saving tenant conf to the registry of tenant " + tenantID, e); } catch (IOException e) { throw new APIMigrationException("Error while reading tenant conf file content of tenant " + tenantID, e); } catch (APIMigrationException e) { e.printStackTrace(); } } /** * Migrate the newly added scopes to the tenant-conf which is already in the registry identified with tenantId and * its byte content is returned. If there were no changes done, an empty Optional will be returned. * * @param tenantId Tenant Id * @return Optional byte content * @throws APIManagementException when error occurred while updating the updating the tenant-conf with scopes. */ private static Optional<Byte[]> migrateTenantConfScopes(int tenantId) throws APIMigrationException { JSONObject tenantConf = getTenantConfigFromRegistry(tenantId); JSONObject scopesConfigTenant = getRESTAPIScopesFromTenantConfig(tenantConf); JSONObject scopeConfigLocal = getRESTAPIScopesConfigFromFileSystem(); JSONObject roleMappingConfigTenant = getRESTAPIScopeRoleMappingsFromTenantConfig(tenantConf); JSONObject roleMappingConfigLocal = getRESTAPIRoleMappingsConfigFromFileSystem(); Map<String, String> scopesTenant = APIUtil.getRESTAPIScopesFromConfig(scopesConfigTenant, roleMappingConfigTenant); Map<String, String> scopesLocal = APIUtil.getRESTAPIScopesFromConfig(scopeConfigLocal, roleMappingConfigLocal); JSONArray tenantScopesArray = (JSONArray) scopesConfigTenant.get(APIConstants.REST_API_SCOPE); boolean isRoleUpdated = false; boolean isMigrated = false; JSONObject metaJson = (JSONObject) tenantConf.get(MIGRATION); if (metaJson != null && metaJson.get(VERSION_3) != null) { isMigrated = Boolean.parseBoolean(metaJson.get(VERSION_3).toString()); } if (!isMigrated) { try { //Get admin role name of the current domain String adminRoleName = CarbonContext.getThreadLocalCarbonContext().getUserRealm() .getRealmConfiguration().getAdminRoleName(); for (int i = 0; i < tenantScopesArray.size(); i++) { JSONObject scope = (JSONObject) tenantScopesArray.get(i); String roles = scope.get(APIConstants.REST_API_SCOPE_ROLE).toString(); if (APIConstants.APIM_SUBSCRIBE_SCOPE.equals(scope.get(APIConstants.REST_API_SCOPE_NAME)) && !roles.contains(adminRoleName)) { tenantScopesArray.remove(i); JSONObject scopeJson = new JSONObject(); scopeJson.put(APIConstants.REST_API_SCOPE_NAME, APIConstants.APIM_SUBSCRIBE_SCOPE); scopeJson.put(APIConstants.REST_API_SCOPE_ROLE, roles + APIConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT + adminRoleName); tenantScopesArray.add(scopeJson); isRoleUpdated = true; break; } } if (isRoleUpdated) { JSONObject metaInfo = new JSONObject(); JSONObject migrationInfo = new JSONObject(); migrationInfo.put(VERSION_3, true); metaInfo.put(MIGRATION, migrationInfo); tenantConf.put(META, metaInfo); } } catch (UserStoreException e) { String tenantDomain = getTenantDomainFromTenantId(tenantId); String errorMessage = "Error while retrieving admin role name of " + tenantDomain; log.error(errorMessage, e); throw new APIMigrationException(errorMessage, e); } Set<String> scopes = scopesLocal.keySet(); //Find any scopes that are not added to tenant conf which is available in local tenant-conf scopes.removeAll(scopesTenant.keySet()); if (!scopes.isEmpty() || isRoleUpdated) { for (String scope : scopes) { JSONObject scopeJson = new JSONObject(); scopeJson.put(APIConstants.REST_API_SCOPE_NAME, scope); scopeJson.put(APIConstants.REST_API_SCOPE_ROLE, scopesLocal.get(scope)); if (log.isDebugEnabled()) { log.debug("Found scope that is not added to tenant-conf.json in tenant " + tenantId + ": " + scopeJson); } tenantScopesArray.add(scopeJson); } try { ObjectMapper mapper = new ObjectMapper(); String formattedTenantConf = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tenantConf); if (log.isDebugEnabled()) { log.debug("Finalized tenant-conf.json: " + formattedTenantConf); } return Optional.of(ArrayUtils.toObject(formattedTenantConf.getBytes())); } catch (JsonProcessingException e) { throw new APIMigrationException("Error while formatting tenant-conf.json of tenant " + tenantId); } } else { log.debug("Scopes in tenant-conf.json in tenant " + tenantId + " are already migrated."); return Optional.empty(); } } else { log.debug("Scopes in tenant-conf.json in tenant " + tenantId + " are already migrated."); return Optional.empty(); } } private static JSONObject getRESTAPIScopesFromTenantConfig(JSONObject tenantConf) { return (JSONObject) tenantConf.get(APIConstants.REST_API_SCOPES_CONFIG); } private static JSONObject getRESTAPIScopeRoleMappingsFromTenantConfig(JSONObject tenantConf) { return (JSONObject) tenantConf.get(APIConstants.REST_API_ROLE_MAPPINGS_CONFIG); } /** * Returns the REST API scopes JSONObject from the tenant-conf.json in the file system * * @return REST API scopes JSONObject from the tenant-conf.json in the file system * @throws APIManagementException when error occurred while retrieving local REST API scopes. */ private static JSONObject getRESTAPIScopesConfigFromFileSystem() throws APIMigrationException { try { byte[] tenantConfData = getTenantConfFromFile(); String tenantConfDataStr = new String(tenantConfData, Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject tenantConfJson = (JSONObject) parser.parse(tenantConfDataStr); if (tenantConfJson == null) { throw new APIMigrationException("tenant-conf.json (in file system) content cannot be null"); } JSONObject restAPIScopes = getRESTAPIScopesFromTenantConfig(tenantConfJson); if (restAPIScopes == null) { throw new APIMigrationException("tenant-conf.json (in file system) should have RESTAPIScopes config"); } return restAPIScopes; } catch (IOException e) { throw new APIMigrationException("Error while reading tenant conf file content from file system", e); } catch (ParseException e) { throw new APIMigrationException("ParseException thrown when parsing tenant config json from string " + "content", e); } } /** * Returns the REST API role mappings JSONObject from the tenant-conf.json in the file system * * @return REST API role mappings JSONObject from the tenant-conf.json in the file system * @throws APIManagementException when error occurred while retrieving local REST API role mappings. */ private static JSONObject getRESTAPIRoleMappingsConfigFromFileSystem() throws APIMigrationException { try { byte[] tenantConfData = getTenantConfFromFile(); String tenantConfDataStr = new String(tenantConfData, Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject tenantConfJson = (JSONObject) parser.parse(tenantConfDataStr); if (tenantConfJson == null) { throw new APIMigrationException("tenant-conf.json (in file system) content cannot be null"); } JSONObject roleMappings = getRESTAPIScopeRoleMappingsFromTenantConfig(tenantConfJson); if (roleMappings == null) { if (log.isDebugEnabled()) { log.debug("Scope role mappings are not defined in the tenant-conf.json in file system"); } } return roleMappings; } catch (IOException e) { throw new APIMigrationException("Error while reading tenant conf file content from file system", e); } catch (ParseException e) { throw new APIMigrationException("ParseException thrown when parsing tenant config json from string " + "content", e); } } }
48.003
131
0.610587
2fae3506ead15d94a2b26a8728e5f8b91599631f
747
package net.byteflux.libby; /** * Class containing URLs of public repositories. */ public class Repositories { /** * Maven Central repository URL. */ public static final String MAVEN_CENTRAL = "https://repo1.maven.org/maven2/"; /** * Sonatype OSS repository URL. */ public static final String SONATYPE = "https://oss.sonatype.org/content/groups/public/"; /** * Bintray JCenter repository URL. */ public static final String JCENTER = "https://jcenter.bintray.com/"; /** * JitPack repository URL. */ public static final String JITPACK = "https://jitpack.io/"; private Repositories() { throw new UnsupportedOperationException("Private constructor"); } }
23.34375
92
0.64257
3331dc754f2b4dcfd7aa427c67a7e5dcd6db7ed1
2,488
package com.rags.tools.mbq.queue.store; import com.rags.tools.mbq.QueueStatus; import com.rags.tools.mbq.connection.rest.messagecodec.SearchRequest; import com.rags.tools.mbq.message.MBQMessage; import com.rags.tools.mbq.message.QMessage; import com.rags.tools.mbq.queue.IdSeqKey; import java.util.List; import java.util.Map; /** * @author ragha * @since 29-12-2019 */ public interface MBQDataStore { /** * Retrieves items from the queue based on the item id * * @param queueName Queue Name * @param id q item id * @return MBQ Message */ MBQMessage get(String queueName, String id); /** * Retrieves items from the queue based on the item ids * * @param queueName Queue Name * @param ids q item ids * @return MBQ Messages */ List<MBQMessage> get(String queueName, List<String> ids); /** * Retrieves all Pending Item IDS on Startup * * @return MBQ pending messages ID and QueueName */ Map<String, List<IdSeqKey>> getAllPendingItems(); /** * Pushes messages to the queue * * @param queueName queue name * @param messages messages to be pushed * @return list of messages that has been pushed */ List<MBQMessage> push(String queueName, List<QMessage> messages); /** * Updates status of queue messages * * @param queueName Queue Name * @param ids queue item ids * @param status status to be updated * @return true if update is success */ boolean updateStatus(String queueName, List<String> ids, QueueStatus status); /** * Updates status of queue messages * * @param queueName Queue Name * @param ids queue item ids * @return true if update is success */ boolean updateStatus(String queueName, Map<QueueStatus, List<String>> ids); /** * Marks all prev statuc to new Status in the queue * * @param prevStatus prev status in the queue * @param newStatus new status in the queue */ void updateStatus(QueueStatus prevStatus, QueueStatus newStatus); /** * Searches Items from the queue data store. * * @param searchRequest request object */ List<MBQMessage> search(SearchRequest searchRequest); /** * Fetches all the Messages based on Ids * * @param ids Item Ids * @return List of MBQMessages */ List<MBQMessage> get(List<String> ids); }
26.468085
81
0.641479
ea1975f6972df15fd9f2abc8206eb3ce880dccac
146
package com.quanlt.vietcomicclean.domain.exception; public interface ErrorBundle { Exception getException(); String getErrorMessage(); }
20.857143
51
0.773973
5335696b27e558663a529940704000a62d81aae8
1,718
package edu.stts.fatburner.ui.register; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import edu.stts.fatburner.R; import edu.stts.fatburner.data.model.User; public class CalorieActivity extends AppCompatActivity { private ImageButton btnNextCalorie; private EditText et; private User userBaru; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_calorie); btnNextCalorie = findViewById(R.id.btnNextCalorie); et = findViewById(R.id.editText); userBaru = (User) getIntent().getSerializableExtra("userBaru"); } public void nextCalorie(View v) { Intent intent = null; if(!et.getText().toString().equals("")){ switch(v.getId()){ case R.id.btnNextCalorie: double calorie = Double.parseDouble(et.getText().toString()); userBaru.setCalorie(calorie); intent = new Intent(this,EndRegisterActivity.class); intent.putExtra("userBaru",userBaru); break; } if (intent != null && !et.getText().equals("")) startActivity(intent); } else Toast.makeText(this, "Field cannot be empty", Toast.LENGTH_SHORT).show(); } }
36.553191
122
0.668219
b9d9ab11edb91a542cd7fd415ed47d5a6c1bd392
1,066
package exceptionhandling; public class MultipleExceptionBlock{ public static void main(String[] args) { try { int marks=109; if (marks>100) throw new MarksException();//Thrpwing out own exception //throw new NullPointerException("Some Data");//Throwing an Exception int [] a=new int[20]; System.out.println(a[12]); int n=12/10; System.out.println("Program Done"); } catch(MarksException ex)//Catching our own exception { System.out.println("Marks Problem " + ex); } catch(ArithmeticException ex)//Only for arithmetic exception { System.out.println("Arithmetic Problem " + ex); } catch(ArrayIndexOutOfBoundsException ex)//Only for ArrayIndex problems { System.out.println("Array Problem " + ex); } finally { System.out.println("Finally. Will run always Exception or no exception"); } //Multiple Exception Block } }
28.052632
85
0.578799
85b8848a39a386292ebf10bec2c11307ec104873
119
package repository.uma; import models.uma.Email; public interface EmailRepository { Email save(Email email); }
11.9
34
0.747899
4b8d7768a87cc4d69a426b41d6cf4ff230df62ac
536
package ota.client12 ; import com4j.*; /** * <p> * Parameter type. * </p> */ public enum TDAPI_BP_STEP_PARAM_TYPE { /** * <p> * Input Parameter. * </p> * <p> * The value of this constant is 0 * </p> */ BP_STEP_PARAM_IN, // 0 /** * <p> * Output Parameter. * </p> * <p> * The value of this constant is 1 * </p> */ BP_STEP_PARAM_OUT, // 1 /** * <p> * Runtime Parameter. * </p> * <p> * The value of this constant is 2 * </p> */ BP_STEP_PARAM_RUNTIME, // 2 }
13.74359
38
0.498134
56dd88da1776db4338762bc5dfb5d946b69d56a3
337
package www.bwsensing.com.system.dto.command.query; import com.alibaba.cola.dto.PageQuery; import java.util.List; import lombok.Data; /** * @author macos-zyj */ @Data public class StructureTemplateSortPageQuery extends PageQuery { /**模板名称*/ private String templateName; /**所属行业*/ private List<Integer> belowFields; }
19.823529
63
0.72997
d161b08c5661dd1e2fe0fa9ced8621b924fc6ffb
1,254
package com.ii.app.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.math.BigDecimal; import java.time.Instant; @Entity @Table (name = "transactions") @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Transaction { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Long id; @Column (name = "date") private Instant date; @Column (name = "balance") private BigDecimal balance; @Column (name = "balance_with_commission") private BigDecimal balanceWithCommission; @ManyToOne @JoinColumn (name = "source_bank_account_id", nullable = false) private BankAccount sourceBankAccount; @Column (name = "title") private String title; @ManyToOne @JoinColumn (name = "destined_bank_account_id") private BankAccount destinedBankAccount; @ManyToOne @JoinColumn(name="source_currency_type_id") private CurrencyType sourceCurrencyType; @ManyToOne @JoinColumn(name="destined_currency_type_id") private CurrencyType destinedCurrencyType; }
24.115385
71
0.685805
3756638a83d2bc31aaf89ed0af0976f9523d4ecb
1,748
// Copyright (c) 2018 The Midi2Drum developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package midi2drum; //ITR XML <NormalNote ch="7" Measure="0" Position="10" TyoeIndex="0" Volume="1"/> public class MyNote { int measure; int tickWithinMeasure; long midiTimeAbsolute; int midiChannel; int pitch; //midiNote int velocity; public int getMeasure() { return measure; } public void setMeasure(int measure) { this.measure = measure; } public int getTickWithinMeasure() { return tickWithinMeasure; } public void setTickWithinMeasure(int tickWithinMeasure) { this.tickWithinMeasure = tickWithinMeasure; } public long getMidiTimeAbsolute() { return midiTimeAbsolute; } public void setMidiTimeAbsolute(int midiTimeAbsolute) { this.midiTimeAbsolute = midiTimeAbsolute; } public int getMidiChannel() { return midiChannel; } public void setMidiChannel(int midiChannel) { this.midiChannel = midiChannel; } public int getPitch() { return pitch; } public void setPitch(int pitch) { this.pitch = pitch; } public int getVelocity() { return velocity; } public void setVelocity(int velocity) { this.velocity = velocity; } /** * @param measure * @param tickWithinMeasure * @param midiTimeAbsolute * @param midiChannel * @param pitch * @param velocity */ public MyNote(int measure, int tickWithinMeasure, long midiTimeAbsolute, int midiChannel, int pitch, int velocity) { this.measure = measure; this.tickWithinMeasure = tickWithinMeasure; this.midiTimeAbsolute = midiTimeAbsolute; this.midiChannel = midiChannel; this.pitch = pitch; this.velocity = velocity; } }
21.060241
101
0.730549
bf0b5b34ff829d1ab170103e6cba63a32798824f
1,770
package com.appsomniac.movie.tv.showcube.adapter.theatre; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.appsomniac.movie.tv.showcube.R; import com.appsomniac.movie.tv.showcube.model.nearby.PlaceApi; import com.appsomniac.movie.tv.showcube.model.nearby.Theatre; import java.util.ArrayList; public class TheatreViewHolder extends RecyclerView.ViewHolder { public ImageView theatre_image; public TextView theatre_name; public TextView theatre_address; public ImageButton theatre_website; public ImageButton theatre_phone_number; public ImageButton theatre_map_url; public TextView theatre_rating; private int theatre_position; public ArrayList<PlaceApi> al_theatres; public ArrayList<Theatre> al_single_theatre_data; private Theatre single_theatre; private Context mContext; public TheatreViewHolder(LayoutInflater inflater, ViewGroup parent, ArrayList<PlaceApi> al_theatres, Context context, final int position) { super(inflater.inflate(R.layout.item_theatre, parent, false)); this.al_theatres = al_theatres; this.mContext = context; this.theatre_position = position; al_single_theatre_data = new ArrayList<>(); single_theatre = new Theatre(); initialize(); } public void initialize(){ theatre_image = (ImageView) itemView.findViewById(R.id.theatre_image); theatre_name = (TextView) itemView.findViewById(R.id.theatre_name); theatre_address = (TextView) itemView.findViewById(R.id.theatre_address); } }
32.181818
143
0.761017