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
91aede57883e3241ecd65e42a07b02a554538947
555
package dderrien.common.model; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Index; @Entity @Cache @Index public class User extends AbstractBase<User> { String name; String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
19.137931
50
0.672072
f43ea63cd8092b9ea9b9996a61cc3af041449970
759
package com.github.supermanhub.spring_boot_quick_start.integration.base; import org.junit.Ignore; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; /** * <b>Integration Test Base</b><br> * You can create more than one Integration Test Base class for different * purpose * * @author Wenbo Wang ([email protected]) */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) // @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = // TestScopeWebSecurityConfigurer.class) @Ignore public class IntegrationTestBase { }
31.625
75
0.807642
1d20a90a5809710d8270a8dc88b0c40eef9e5c5f
973
package fr.trxyy.alternative.alternative_api.assets; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * @author Trxyy */ public class AssetIndex { /** * The default asset name */ public static final String DEFAULT_ASSET_NAME = "legacy"; /** * The objects stocked inside a Map<String, AssetObject> */ private final Map<String, AssetObject> objects; /** * Is Virtual ? */ private boolean virtual; /** * The Constructor */ public AssetIndex() { this.objects = new LinkedHashMap<String, AssetObject>(); } /** * @return The objects list as a Map */ public Map<String, AssetObject> getObjects() { return this.objects; } /** * @return Get the unique Objects as a Set */ public Set<AssetObject> getUniqueObjects() { return new HashSet<AssetObject>(this.objects.values()); } /** * @return If it's virtual */ public boolean isVirtual() { return this.virtual; } }
18.018519
58
0.678314
40788fecd5183763b1bfab085475b5432daede8c
674
package frc.robot.auto; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.intake.IntakeSubsystem; public class ExtakeBall extends SequentialCommandGroup { private final double EXTAKE_SPEED = -1; public ExtakeBall(IntakeSubsystem intakeSubsystem) { addRequirements(intakeSubsystem); addCommands( new InstantCommand(() -> intakeSubsystem.setInnerIntakeMotor(this.EXTAKE_SPEED)), new WaitCommand(2), new InstantCommand(intakeSubsystem::disableInnerIntakeMotor) ); } }
33.7
93
0.744807
513c1673fdce7ce1810172ebd70456b153fccabb
3,780
package com.acgist.snail.context; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.acgist.snail.IContext; import com.acgist.snail.net.IChannelHandler; import com.acgist.snail.net.UdpMessageHandler; import com.acgist.snail.net.torrent.utp.UtpMessageHandler; /** * <p>UTP上下文</p> * <p>管理UTP消息代理</p> * * @author acgist */ public final class UtpContext implements IContext, IChannelHandler<DatagramChannel> { private static final Logger LOGGER = LoggerFactory.getLogger(UtpContext.class); private static final UtpContext INSTANCE = new UtpContext(); public static final UtpContext getInstance() { return INSTANCE; } /** * <p>UTP超时执行周期(秒):{@value}</p> */ private static final int UTP_TIMEOUT_INTERVAL = 10; /** * <p>连接ID</p> */ private short connectionId = (short) System.currentTimeMillis(); /** * <p>UDP通道</p> */ private DatagramChannel channel; /** * <p>消息代理上下文</p> */ private final MessageHandlerContext context; /** * <p>UTP消息代理列表</p> * <p>连接Key=消息代理</p> * * @see #buildKey(short, InetSocketAddress) */ private final Map<String, UtpMessageHandler> utpMessageHandlers; private UtpContext() { this.context = MessageHandlerContext.getInstance(); this.utpMessageHandlers = new ConcurrentHashMap<>(); SystemThreadContext.timerAtFixedDelay( UTP_TIMEOUT_INTERVAL, UTP_TIMEOUT_INTERVAL, TimeUnit.SECONDS, this::timeout ); } @Override public void handle(DatagramChannel channel) { this.channel = channel; } /** * <p>获取连接ID</p> * * @return 连接ID */ public short connectionId() { synchronized (this) { return this.connectionId++; } } /** * <p>获取UTP消息代理</p> * * @param connectionId 连接ID * @param socketAddress 连接地址 * * @return UTP消息代理 */ public UdpMessageHandler get(short connectionId, InetSocketAddress socketAddress) { final String key = this.buildKey(connectionId, socketAddress); UtpMessageHandler utpMessageHandler = this.utpMessageHandlers.get(key); if(utpMessageHandler != null) { return utpMessageHandler; } utpMessageHandler = new UtpMessageHandler(connectionId, socketAddress); utpMessageHandler.handle(this.channel); // 只需要管理服务端连接 this.context.newInstance(utpMessageHandler); return utpMessageHandler; } /** * <p>添加UTP消息代理</p> * * @param utpMessageHandler UTP消息代理 */ public void put(UtpMessageHandler utpMessageHandler) { synchronized (this.utpMessageHandlers) { this.utpMessageHandlers.put(utpMessageHandler.key(), utpMessageHandler); } } /** * <p>删除UTP消息代理</p> * * @param utpMessageHandler UTP消息代理 */ public void remove(UtpMessageHandler utpMessageHandler) { synchronized (this.utpMessageHandlers) { this.utpMessageHandlers.remove(utpMessageHandler.key()); } } /** * <p>生成UTP消息代理连接Key</p> * * @param connectionId 连接ID * @param socketAddress 请求地址 * * @return 连接Key */ public String buildKey(short connectionId, InetSocketAddress socketAddress) { return socketAddress.getHostString() + socketAddress.getPort() + connectionId; } /** * <p>处理超时UTP消息</p> * <p>如果消息代理可用:重新发送超时消息</p> * <p>如果消息代理关闭:移除消息代理</p> */ private void timeout() { LOGGER.debug("处理超时UTP消息"); synchronized (this.utpMessageHandlers) { try { this.utpMessageHandlers.values().stream() // 超时重试 .filter(UtpMessageHandler::timeoutRetry) // 转换List关闭:防止关闭删除消息代理产生异常 .collect(Collectors.toList()) // 已经关闭:直接移除 .forEach(this::remove); } catch (Exception e) { LOGGER.error("处理超时UTP消息异常", e); } } } }
23.04878
85
0.707672
2e716c304abe091fb73d84b2885878845eb74fd3
815
package com.oven.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "myFilter", urlPatterns = "/test/*") public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) { System.out.println("初始化过滤器。。。"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("进入到过滤器。。。"); String name = servletRequest.getParameter("name"); if ("Oven".equals(name)) { filterChain.doFilter(servletRequest, servletResponse); } } @Override public void destroy() { System.out.println("过滤器销毁。。。"); } }
27.166667
152
0.679755
ebfd86366b4c56dfdb5f7a90c5bc633ce549a8d3
1,656
package com.dianping.zebra.shard.api; import java.util.HashMap; import java.util.List; import java.util.Map; public class ShardDataSourceHelper { private static final ThreadLocal<ShardParamsHolder> SHARD_PARAMS = new ThreadLocal<ShardParamsHolder>(){ protected ShardParamsHolder initialValue() { return new ShardParamsHolder(); } }; private static final ThreadLocal<Boolean> EXTRACT_PARAMS_ONLY_FROM_THREAD_LOCAL = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static List<Object> getShardParams(String shardColumn) { ShardParamsHolder holder = SHARD_PARAMS.get(); return holder.getShardParams(shardColumn); } public static void setShardParams(String shardColumn, List<Object> params) { ShardParamsHolder holder = SHARD_PARAMS.get(); holder.setShardParams(shardColumn, params); } public static void clearAllThreadLocal() { SHARD_PARAMS.remove(); EXTRACT_PARAMS_ONLY_FROM_THREAD_LOCAL.remove(); } public static void setExtractParamsOnlyFromThreadLocal(boolean extractParamsOnlyFromThreadLocal) { EXTRACT_PARAMS_ONLY_FROM_THREAD_LOCAL.set(extractParamsOnlyFromThreadLocal); } public static boolean extractParamsOnlyFromThreadLocal() { return EXTRACT_PARAMS_ONLY_FROM_THREAD_LOCAL.get(); } public static class ShardParamsHolder { private Map<String, List<Object>> shardParams = new HashMap<String, List<Object>>(); public void setShardParams(String shardColumn, List<Object> params) { this.shardParams.put(shardColumn, params); } public List<Object> getShardParams(String shardColumn) { return this.shardParams.get(shardColumn); } } }
28.067797
111
0.783213
8cdcd0b6152ec10f98e71c544ccf88c39a1200d2
1,855
package com.qlm.similitude.lsh.measure; import java.io.*; import java.util.*; import java.util.stream.Collectors; public class GenerateTruth { @SuppressWarnings("ResultOfMethodCallIgnored") public static void main(String[] args) { String sentencesFile = args[0]; String outFile = args[1]; Double minJaccardScore = Double.parseDouble(args[2]); try (BufferedReader br = new BufferedReader(new FileReader(sentencesFile))) { System.out.println("Reading sentences into cache"); List<Set<String>> sentences = loadSentences(br); System.out.println("DONE: Reading sentences into cache"); File outF = new File(outFile); outF.delete(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(outF))) { System.out.println("Scoring"); for (int i = 0; i < sentences.size(); i++) { compareSentences(sentences.get(i), sentences, i+1, bw, minJaccardScore); } } } catch (IOException ioe) { ioe.printStackTrace(); } } public static void compareSentences(Set<String> xSet, List<Set<String>> sentences, int start, Writer bw, double minJaccardScore) throws IOException { int xStart = start - 1; JaccardSimilarity score; for (int i = start; i < sentences.size(); i++) { score = new JaccardSimilarity(xSet, xStart, sentences.get(i), i); if (score.getScore() >= minJaccardScore) { bw.append(score.toString()).append("\n"); } } } public static List<Set<String>> loadSentences(BufferedReader reader) throws FileNotFoundException { List<Set<String>> sentences; if (reader != null) { sentences = reader.lines().map(line -> new HashSet<>(Arrays.asList(line.split(",")[1].split(" ")))).collect(Collectors.toList()); } else { sentences = new ArrayList<>(0); } return sentences; } }
34.351852
151
0.656604
48d6fa2e9c7b723c8e51b189669db60f6853a312
22,039
package computing.corona.mobile.cov_erage; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.icu.text.SimpleDateFormat; import android.net.ParseException; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.time.Instant; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.HttpsURLConnection; public class MainActivity extends AppCompatActivity { int submissionCounter; String userId; String postalCode; int gender; int yearOfBirth; int generalHealth; int coronaVirus; int numberOfContacts; int coughing; int temperature; int headache; int soreThroat; int runnyNose; int limbPain; int diarrhea; int loneliness; int insomnia; EditText postLeitZahlEditText; Spinner genderSpinner; Spinner yearOfBirthSpinner; SeekBar generalHealthSeekbar; Spinner coronaVirusSpinner; EditText numberOfContactsEditText; Spinner coughingSpinner; Spinner temperatureSpinner; Spinner headacheSpinner; Spinner soreThroatSpinner; Spinner runnyNoseSpinner; Spinner limbPainSpinner; Spinner diarrheaSpinner; Spinner lonelinessSpinner; Spinner insomniaSpinner; Button sendButton; SharedPreferences sharedPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPrefs = getApplicationContext() .getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE); submissionCounter = sharedPrefs.getInt("submissionCounter", 0); userId = sharedPrefs.getString("userId","-1"); if (userId.equals("-1")) { userId = UUID.randomUUID().toString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("userId", userId); editor.apply(); } postalCode = sharedPrefs.getString("postalCode",""); gender = sharedPrefs.getInt("gender", -1); yearOfBirth = sharedPrefs.getInt("yearOfBirth",0); generalHealth = sharedPrefs.getInt("generalHealth",5); coronaVirus = sharedPrefs.getInt("coronaVirus",-1); numberOfContacts = sharedPrefs.getInt("numberOfContacts",-1); coughing = sharedPrefs.getInt("coughing",-1); temperature = sharedPrefs.getInt("temperature",-1); headache = sharedPrefs.getInt("headache",-1); soreThroat = sharedPrefs.getInt("soreThroat",-1); runnyNose = sharedPrefs.getInt("runnyNose",-1); limbPain = sharedPrefs.getInt("limbPain",-1); diarrhea = sharedPrefs.getInt("diarrhea",-1); loneliness = sharedPrefs.getInt("loneliness",-1); insomnia = sharedPrefs.getInt("insomnia",-1); postLeitZahlEditText = findViewById(R.id.postleitzahlEditText); postLeitZahlEditText.setText(postalCode); genderSpinner = (Spinner) findViewById(R.id.geschlechtSpinner); String[] values = getResources().getStringArray(R.array.gender); // changing an ArrayAdapter ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item); genderSpinner.setAdapter(spinnerArrayAdapter); if (gender > 0) { genderSpinner.setSelection(gender); } else { genderSpinner.setSelection(0); } ArrayList<String> years = new ArrayList<String>(); years.add("keine Angabe"); int thisYear = Calendar.getInstance().get(Calendar.YEAR); for (int i = 1900; i <= thisYear; i++) { years.add(Integer.toString(i)); } final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, years); yearOfBirthSpinner = (Spinner)findViewById(R.id.yearOfBirthSpinner); yearOfBirthSpinner.setAdapter(adapter); if (yearOfBirth > 0) { int spinnerPosition = adapter.getPosition(String.valueOf(yearOfBirth)); yearOfBirthSpinner.setSelection(spinnerPosition); } else { yearOfBirthSpinner.setSelection(0); } generalHealthSeekbar = findViewById(R.id.generalHealthSeekbar); generalHealthSeekbar.setProgress(generalHealth); coronaVirusSpinner = (Spinner) findViewById(R.id.coronaVirusSpinner); values = getResources().getStringArray(R.array.coronaVirus); ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter2.setDropDownViewResource(R.layout.spinner_item); coronaVirusSpinner.setAdapter(spinnerArrayAdapter2); if (coronaVirus > 0) { coronaVirusSpinner.setSelection(coronaVirus); } else { coronaVirusSpinner.setSelection(0); } numberOfContactsEditText = findViewById(R.id.numberOfContactsEditText); if (numberOfContacts > 0) { numberOfContactsEditText.setText(numberOfContacts + ""); } coughingSpinner = (Spinner) findViewById(R.id.coughingSpinner); values = getResources().getStringArray(R.array.coughing); ArrayAdapter<String> spinnerArrayAdapter3 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter3.setDropDownViewResource(R.layout.spinner_item); coughingSpinner.setAdapter(spinnerArrayAdapter3); if (coughing > 0) { coughingSpinner.setSelection(coughing); } else { coughingSpinner.setSelection(0); } temperatureSpinner = (Spinner) findViewById(R.id.temperatureSpinner); values = getResources().getStringArray(R.array.temperature); ArrayAdapter<String> spinnerArrayAdapter4 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter4.setDropDownViewResource(R.layout.spinner_item); temperatureSpinner.setAdapter(spinnerArrayAdapter4); if (temperature > 0) { temperatureSpinner.setSelection(temperature); } else { temperatureSpinner.setSelection(0); } headacheSpinner = (Spinner) findViewById(R.id.headacheSpinner); values = getResources().getStringArray(R.array.headache); ArrayAdapter<String> spinnerArrayAdapter5 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter5.setDropDownViewResource(R.layout.spinner_item); headacheSpinner.setAdapter(spinnerArrayAdapter5); if (headache > 0) { headacheSpinner.setSelection(headache); } else { headacheSpinner.setSelection(0); } soreThroatSpinner = (Spinner) findViewById(R.id.soreThroatSpinner); values = getResources().getStringArray(R.array.headache); ArrayAdapter<String> spinnerArrayAdapter6 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter6.setDropDownViewResource(R.layout.spinner_item); soreThroatSpinner.setAdapter(spinnerArrayAdapter6); if (soreThroat > 0) { soreThroatSpinner.setSelection(soreThroat); } else { soreThroatSpinner.setSelection(0); } runnyNoseSpinner = (Spinner) findViewById(R.id.runnyNoseSpinner); values = getResources().getStringArray(R.array.headache); ArrayAdapter<String> spinnerArrayAdapter7 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter7.setDropDownViewResource(R.layout.spinner_item); runnyNoseSpinner.setAdapter(spinnerArrayAdapter7); if (runnyNose > 0) { runnyNoseSpinner.setSelection(runnyNose); } else { runnyNoseSpinner.setSelection(0); } limbPainSpinner = (Spinner) findViewById(R.id.limbPainSpinner); values = getResources().getStringArray(R.array.headache); ArrayAdapter<String> spinnerArrayAdapter8 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter8.setDropDownViewResource(R.layout.spinner_item); limbPainSpinner.setAdapter(spinnerArrayAdapter8); if (limbPain > 0) { limbPainSpinner.setSelection(limbPain); } else { limbPainSpinner.setSelection(0); } diarrheaSpinner = (Spinner) findViewById(R.id.diarrheaSpinner); values = getResources().getStringArray(R.array.diarrhea); ArrayAdapter<String> spinnerArrayAdapter9 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter9.setDropDownViewResource(R.layout.spinner_item); diarrheaSpinner.setAdapter(spinnerArrayAdapter9); if (diarrhea > 0) { diarrheaSpinner.setSelection(diarrhea); } else { diarrheaSpinner.setSelection(0); } lonelinessSpinner = (Spinner) findViewById(R.id.lonelinessSpinner); values = getResources().getStringArray(R.array.loneliness); ArrayAdapter<String> spinnerArrayAdapter10 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter10.setDropDownViewResource(R.layout.spinner_item); lonelinessSpinner.setAdapter(spinnerArrayAdapter10); if (loneliness > 0) { lonelinessSpinner.setSelection(loneliness); } else { lonelinessSpinner.setSelection(0); } insomniaSpinner = (Spinner) findViewById(R.id.insomniaSpinner); values = getResources().getStringArray(R.array.insomnia); ArrayAdapter<String> spinnerArrayAdapter11 = new ArrayAdapter<String>( this,R.layout.spinner_item, values ); spinnerArrayAdapter11.setDropDownViewResource(R.layout.spinner_item); insomniaSpinner.setAdapter(spinnerArrayAdapter11); if (insomnia > 0) { insomniaSpinner.setSelection(insomnia); } else { insomniaSpinner.setSelection(0); } sendButton = findViewById(R.id.sendButton); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor editor = sharedPrefs.edit(); postalCode = postLeitZahlEditText.getText().toString(); editor.putString("postalCode",postalCode); if (genderSpinner.getSelectedItemPosition() > 0) { gender = genderSpinner.getSelectedItemPosition(); } else { gender = -1; } editor.putInt("gender",gender); if (yearOfBirthSpinner.getSelectedItemPosition() > 0) { yearOfBirth = Integer.parseInt((String)yearOfBirthSpinner.getSelectedItem()); } else { yearOfBirth = -1; } editor.putInt("yearOfBirth",yearOfBirth); generalHealth = generalHealthSeekbar.getProgress(); editor.putInt("generalHealth",generalHealth); if (coronaVirusSpinner.getSelectedItemPosition() > 0) { coronaVirus = coronaVirusSpinner.getSelectedItemPosition(); } else { coronaVirus = -1; } editor.putInt("coronaVirus",coronaVirus); if (numberOfContactsEditText.getText().toString().length()>0) { numberOfContacts = Integer.valueOf(numberOfContactsEditText.getText().toString()); } else { numberOfContacts = -1; } editor.putInt("numberOfContacts",numberOfContacts); if (coughingSpinner.getSelectedItemPosition() > 0) { coughing = coughingSpinner.getSelectedItemPosition(); } else { coughing = -1; } editor.putInt("coughing",coughing); if (temperatureSpinner.getSelectedItemPosition() > 0) { temperature = temperatureSpinner.getSelectedItemPosition(); } else { temperature = -1; } editor.putInt("temperature",temperature); if (headacheSpinner.getSelectedItemPosition() > 0) { headache = headacheSpinner.getSelectedItemPosition(); } else { headache = -1; } editor.putInt("headache",headache); if (soreThroatSpinner.getSelectedItemPosition() > 0) { soreThroat = soreThroatSpinner.getSelectedItemPosition(); } else { soreThroat = -1; } editor.putInt("soreThroat",soreThroat); if (runnyNoseSpinner.getSelectedItemPosition() > 0) { runnyNose = runnyNoseSpinner.getSelectedItemPosition(); } else { runnyNose = -1; } editor.putInt("runnyNose",runnyNose); if (limbPainSpinner.getSelectedItemPosition() > 0) { limbPain = limbPainSpinner.getSelectedItemPosition(); } else { limbPain = -1; } editor.putInt("limbPain",limbPain); if (diarrheaSpinner.getSelectedItemPosition() > 0) { diarrhea = diarrheaSpinner.getSelectedItemPosition(); } else { diarrhea = -1; } editor.putInt("diarrhea",diarrhea); if (lonelinessSpinner.getSelectedItemPosition() > 0) { loneliness = lonelinessSpinner.getSelectedItemPosition(); } else { loneliness = -1; } editor.putInt("loneliness",loneliness); if (insomniaSpinner.getSelectedItemPosition() > 0) { insomnia = insomniaSpinner.getSelectedItemPosition(); } else { insomnia = -1; } editor.putInt("insomnia",insomnia); /* postalCode = sharedPrefs.getString("postalCode",""); gender = sharedPrefs.getInt("gender", -1); yearOfBirth = sharedPrefs.getInt("yearOfBirth",0); generalHealth = sharedPrefs.getInt("generalHealth",5); coronaVirus = sharedPrefs.getInt("coronaVirus",-1); numberOfContacts = sharedPrefs.getInt("numberOfContacts",-1); coughing = sharedPrefs.getInt("coughing",-1); temperature = sharedPrefs.getInt("temperature",-1); headache = sharedPrefs.getInt("headache",-1); soreThroat = sharedPrefs.getInt("soreThroat",-1); runnyNose = sharedPrefs.getInt("runnyNose",-1); limbPain = sharedPrefs.getInt("limbPain",-1); diarrhea = sharedPrefs.getInt("diarrhea",-1); loneliness = sharedPrefs.getInt("loneliness",-1); insomnia = sharedPrefs.getInt("insomnia",-1); */ JSONObject postRequest = new JSONObject(); try { postRequest.put("userId", userId); postRequest.put("postalCode", postalCode); postRequest.put("gender", gender); postRequest.put("yearOfBirth", yearOfBirth); postRequest.put("generalHealth", generalHealth); postRequest.put("coronaVirus", coronaVirus); postRequest.put("numberOfContacts", numberOfContacts); postRequest.put("coughing", coughing); postRequest.put("temperature", temperature); postRequest.put("headache", headache); postRequest.put("soreThroat", soreThroat); postRequest.put("runnyNose", runnyNose); postRequest.put("limbPain", limbPain); postRequest.put("diarrhea", diarrhea); postRequest.put("loneliness", loneliness); postRequest.put("insomnia", insomnia); } catch (JSONException e) { e.printStackTrace(); } long thisTS = Calendar.getInstance().getTime().getTime(); long lastTS = sharedPrefs.getLong("lastSent",-1); if (getCountOfDays(thisTS,lastTS) < 0) { new sendDataTask(postRequest).execute(); Toast.makeText(MainActivity.this,"Danke!",Toast.LENGTH_LONG).show(); editor.putInt("submissionCounter", ++submissionCounter); } else { new sendDataTask(postRequest).execute(); Toast.makeText(MainActivity.this,"Danke!",Toast.LENGTH_LONG).show(); // Toast.makeText(MainActivity.this,"Jeden Tag nur ein Senden erlaubt",Toast.LENGTH_LONG).show(); editor.putInt("submissionCounter", ++submissionCounter); } editor.putLong("lastSent",thisTS); editor.apply(); finish(); } }); } public int getCountOfDays(long startTS, long endTS) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); Date createdConvertedDate = new Date(), expireConvertedDate = new Date(), todayWithZeroTime = null; try { createdConvertedDate.setTime(startTS); expireConvertedDate.setTime(endTS); Date today = new Date(); todayWithZeroTime = dateFormat.parse(dateFormat.format(today)); } catch (ParseException | java.text.ParseException e) { e.printStackTrace(); } int cYear = 0, cMonth = 0, cDay = 0; if (createdConvertedDate.after(todayWithZeroTime)) { Calendar cCal = Calendar.getInstance(); cCal.setTime(createdConvertedDate); cYear = cCal.get(Calendar.YEAR); cMonth = cCal.get(Calendar.MONTH); cDay = cCal.get(Calendar.DAY_OF_MONTH); } else { Calendar cCal = Calendar.getInstance(); cCal.setTime(todayWithZeroTime); cYear = cCal.get(Calendar.YEAR); cMonth = cCal.get(Calendar.MONTH); cDay = cCal.get(Calendar.DAY_OF_MONTH); } Calendar eCal = Calendar.getInstance(); eCal.setTime(expireConvertedDate); int eYear = eCal.get(Calendar.YEAR); int eMonth = eCal.get(Calendar.MONTH); int eDay = eCal.get(Calendar.DAY_OF_MONTH); Calendar date1 = Calendar.getInstance(); Calendar date2 = Calendar.getInstance(); date1.clear(); date1.set(cYear, cMonth, cDay); date2.clear(); date2.set(eYear, eMonth, eDay); long diff = date2.getTimeInMillis() - date1.getTimeInMillis(); float dayCount = (float) diff / (24 * 60 * 60 * 1000); return (int) dayCount; } private class sendDataTask extends AsyncTask<String, String, String> { JSONObject postBody; private sendDataTask(JSONObject postBody) { this.postBody = postBody; } @Override protected String doInBackground(String... strings) { try { URL url = new URL("https://aiulvempz3.execute-api.eu-central-1.amazonaws.com/production/droplet"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(10000); urlConnection.setConnectTimeout(15000); urlConnection.setRequestProperty("Content-Type", "application/json"); byte[] outputInBytes = postBody.toString().getBytes("UTF-8"); OutputStream os = urlConnection.getOutputStream(); os.write(outputInBytes); os.close(); /* BufferedReader in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String inputLine; String response = ""; while ((inputLine = in.readLine()) != null) { response += inputLine; } in.close(); */ int status = urlConnection.getResponseCode(); Log.d("COVID", "status: " + status); } catch (IOException e) { e.printStackTrace(); } return null; } } }
39.853526
117
0.60334
0297d711f55cccb5e2076afbc41cd6f5e69c7fcd
1,378
package com.vo; import java.io.Serializable; import java.util.List; /** * @Description: 部门管理 * @Date: 2018.1.30 * @author lv * @version 1.0 */ public class Department implements Serializable { private int department_id; // 部门ID private int area_id; // 区域id private String department_name; // 部门名称 private String department_description; // 部门描述 private String area_name; // 区域名称 private List<Position> position; // 职称集合 public int getDepartment_id() { return department_id; } public void setDepartment_id(int department_id) { this.department_id = department_id; } public int getArea_id() { return area_id; } public void setArea_id(int area_id) { this.area_id = area_id; } public String getDepartment_name() { return department_name; } public void setDepartment_name(String department_name) { this.department_name = department_name; } public String getDepartment_description() { return department_description; } public void setDepartment_description(String department_description) { this.department_description = department_description; } public String getArea_name() { return area_name; } public void setArea_name(String area_name) { this.area_name = area_name; } public List<Position> getPosition() { return position; } public void setPosition(List<Position> position) { this.position = position; } }
19.138889
71
0.743106
36982c85fab53cbf3e928b568838e1cc7fe9f359
5,584
package org.folio.circulation.infrastructure.storage; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.folio.circulation.support.Result.failed; import static org.folio.circulation.support.Result.succeeded; import static org.folio.circulation.support.results.CommonFailures.failedDueToServerError; import java.lang.invoke.MethodHandles; import java.util.concurrent.CompletableFuture; import org.folio.circulation.domain.Item; import org.folio.circulation.domain.Loan; import org.folio.circulation.domain.Request; import org.folio.circulation.domain.User; import org.folio.circulation.rules.AppliedRuleConditions; import org.folio.circulation.rules.CirculationRuleMatch; import org.folio.circulation.support.CirculationRulesClient; import org.folio.circulation.support.CollectionResourceClient; import org.folio.circulation.support.ForwardOnFailure; import org.folio.circulation.support.Result; import org.folio.circulation.support.SingleRecordFetcher; import org.folio.circulation.support.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.json.JsonObject; public abstract class CirculationPolicyRepository<T> { private static final String APPLIED_RULE_CONDITIONS = "appliedRuleConditions"; private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final CirculationRulesClient circulationRulesClient; protected final CollectionResourceClient policyStorageClient; protected CirculationPolicyRepository( CirculationRulesClient circulationRulesClient, CollectionResourceClient policyStorageClient) { this.circulationRulesClient = circulationRulesClient; this.policyStorageClient = policyStorageClient; } public CompletableFuture<Result<T>> lookupPolicy(Loan loan) { return lookupPolicy(loan.getItem(), loan.getUser()); } public CompletableFuture<Result<T>> lookupPolicy(Request request) { return lookupPolicy(request.getItem(), request.getRequester()); } public CompletableFuture<Result<T>> lookupPolicy( Item item, User user) { return lookupPolicyId(item, user) .thenComposeAsync(r -> r.after(ruleMatchEntity -> lookupPolicy( ruleMatchEntity.getPolicyId(), ruleMatchEntity.getAppliedRuleConditions()))); } private Result<T> mapToPolicy(JsonObject json, AppliedRuleConditions ruleConditionsEntity) { if (log.isInfoEnabled()) { log.info("Mapping json to policy {}", json.encodePrettily()); } return toPolicy(json, ruleConditionsEntity); } public CompletableFuture<Result<T>> lookupPolicy(String policyId, AppliedRuleConditions conditionsEntity) { log.info("Looking up policy with id {}", policyId); return SingleRecordFetcher.json(policyStorageClient, "circulation policy", response -> failedDueToServerError(getPolicyNotFoundErrorMessage(policyId))) .fetch(policyId) .thenApply(result -> result.next(json -> mapToPolicy(json, conditionsEntity))); } public CompletableFuture<Result<CirculationRuleMatch>> lookupPolicyId(Item item, User user) { if (item.isNotFound()) { return completedFuture(failedDueToServerError( "Unable to apply circulation rules for unknown item")); } if (item.doesNotHaveHolding()) { return completedFuture(failedDueToServerError( "Unable to apply circulation rules for unknown holding")); } String loanTypeId = item.determineLoanTypeForItem(); String locationId = item.getLocationId(); String materialTypeId = item.getMaterialTypeId(); String patronGroupId = user.getPatronGroupId(); log.info( "Applying circulation rules for material type: {}, patron group: {}, loan type: {}, location: {}", materialTypeId, patronGroupId, loanTypeId, locationId); final CompletableFuture<Result<Response>> circulationRulesResponse = circulationRulesClient.applyRules(loanTypeId, locationId, materialTypeId, patronGroupId); return circulationRulesResponse .thenCompose(r -> r.after(this::processRulesResponse)); } private CompletableFuture<Result<CirculationRuleMatch>> processRulesResponse(Response response) { final CompletableFuture<Result<CirculationRuleMatch>> future = new CompletableFuture<>(); if (response.getStatusCode() == 404) { future.complete(failedDueToServerError("Unable to apply circulation rules")); } else if (response.getStatusCode() != 200) { future.complete(failed(new ForwardOnFailure(response))); } else { log.info("Rules response {}", response.getBody()); String policyId = fetchPolicyId(response.getJson()); boolean isItemTypePresent = response.getJson().getJsonObject(APPLIED_RULE_CONDITIONS) .getBoolean("materialTypeMatch"); boolean isLoanTypePresent = response.getJson().getJsonObject(APPLIED_RULE_CONDITIONS) .getBoolean("loanTypeMatch"); boolean isPatronGroupPresent = response.getJson().getJsonObject(APPLIED_RULE_CONDITIONS) .getBoolean("patronGroupMatch"); log.info("Policy to fetch based upon rules {}", policyId); future.complete(succeeded(new CirculationRuleMatch( policyId, new AppliedRuleConditions(isItemTypePresent, isLoanTypePresent, isPatronGroupPresent)))); } return future; } protected abstract String getPolicyNotFoundErrorMessage(String policyId); protected abstract Result<T> toPolicy(JsonObject representation, AppliedRuleConditions ruleConditionsEntity); protected abstract String fetchPolicyId(JsonObject jsonObject); }
41.362963
111
0.773281
261f49139286dd8cf5959976f5222032bfe54e7c
2,701
/* * Copyright (C) 2017 The LineageOS Project * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lineage.jelly.utils; import android.util.Patterns; import android.webkit.URLUtil; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class UrlUtils { public static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( "(?i)" + // switch on case insensitive matching "(" + // begin group for schema "(?:http|https|file|chrome|content)://" + "|(?:inline|data|about|javascript):" + ")" + "(.*)" ); private UrlUtils() { } /** * Attempts to determine whether user input is a URL or search * terms. Anything with a space is passed to search if canBeSearch is true. * <p> * Converts to lowercase any mistakenly uppercased schema (i.e., * "Http://" converts to "http://" * * @return Original or modified URL */ public static String smartUrlFilter(String url) { String inUrl = url.trim(); boolean hasSpace = inUrl.indexOf(' ') != -1; Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); if (matcher.matches()) { // force scheme to lowercase String scheme = matcher.group(1); String lcScheme = scheme.toLowerCase(); if (!lcScheme.equals(scheme)) { inUrl = lcScheme + matcher.group(2); } if (hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) { inUrl = inUrl.replace(" ", "%20"); } return inUrl; } if (!hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) { return URLUtil.guessUrl(inUrl); } return null; } /** * Formats a launch-able uri out of the template uri by replacing the template parameters with * actual values. */ public static String getFormattedUri(String templateUri, String query) { return URLUtil.composeSearchUrl(query, templateUri, "{searchTerms}"); } }
33.7625
98
0.612366
8a32b78daa79d3c3b67ebc7308a000b7c8177097
5,108
/* Reads lines from a tree of nested include (text) files @(#) $Id: NestedLineReader.java 9 2008-09-05 05:21:15Z gfis $ 2007-12-04: copied from program/ProgramTransformer -> generalized scanner 2007-10-29, Georg Fischer: extracted from JavaTransformer */ /* * Copyright 2006 Dr. Georg Fischer <punctum at punctum dot kom> * * 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.teherba.xtrans; import java.io.BufferedReader; import java.io.FileInputStream; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Stack; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** Reads lines from a tree of nested include (text) files. * @author Dr. Georg Fischer */ public class NestedLineReader { public final static String CVSID = "@(#) $Id: NestedLineReader.java 9 2008-09-05 05:21:15Z gfis $"; /** log4j logger (category) */ private static Logger log = LogManager.getLogger(NestedLineReader.class.getName());; /** maximum nesting level */ private static final int MAX_NEST = 16; /** stack of readersfor the currently open files */ protected Stack/*<1.5*/<BufferedReader>/*1.5>*/ readerStack; /** current (top-most) reader in the stack */ protected BufferedReader reader; /** No-args Constructor. */ public NestedLineReader() { readerStack = new Stack/*<1.5*/<BufferedReader>/*1.5>*/(); reader = null; } // Constructor /** Constructor which opens an initial source file. * @param fileName file to be opened initially. * @param sourceEncoding encoding of the include file to be opened */ public NestedLineReader(String fileName, String sourceEncoding) { this(); open(fileName, sourceEncoding); } // Constructor /** Opens a nested include file. * @param fileName file to be opened. * @param sourceEncoding encoding of the include file to be opened * @return whether the file could be opened. */ public boolean open(String fileName, String sourceEncoding) { boolean result = true; // assume success try { ReadableByteChannel channel = (new FileInputStream (fileName)).getChannel(); reader = new BufferedReader(Channels.newReader(channel, sourceEncoding)); result = open(reader); } catch (Exception exc) { log.error(exc.getMessage(), exc); result = false; } return result; } // open /** Opens a nested include file. * @param charReader a BufferedReader for a character file, already open * @return whether the file could be opened. */ public boolean open(BufferedReader charReader) { boolean result = true; // assume success try { if (readerStack.size() < MAX_NEST) { reader = charReader; readerStack.push(reader); } else { result = false; log.error("more than " + MAX_NEST + " nested include files"); } } catch (Exception exc) { log.error(exc.getMessage(), exc); result = false; } return result; } // open /** Reads the next line. * @return line read from one of the nested source files, * or <em>null</em> at then end of the outermost file. */ public String readLine() { String result = null; try { result = reader.readLine(); boolean busy = true; while (busy && result == null) { reader.close(); if (readerStack.size() > 1) { reader = readerStack.pop(); result = reader.readLine(); } else { // outermost file is also at EOF busy = false; } } // while popping } catch (Exception exc) { log.error(exc.getMessage(), exc); result = null; } return result; } // readLine /** Closes all open files. */ public void close() { try { while (! readerStack.empty()) { reader = readerStack.pop(); reader.close(); } // not yet empty } catch (Exception exc) { log.error(exc.getMessage(), exc); } } // close } // class NestedLineReader
35.72028
104
0.587314
d012a25b4187b7e2b87a6184330da00f6ab744e7
1,429
package com.coroptis.jblinktree.store; /* * #%L * jblinktree * %% * Copyright (C) 2015 coroptis * %% * 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. * #L% */ import com.coroptis.jblinktree.Node; /** * Allows to convert Node&lt;K,V&gt; to Node&lt;K,Interer&gt; and convert it * back. * * @author jajir * * @param <K> * key type * @param <V> * value type */ public interface NodeConverter<K, V> { /** * Convert Node&lt;K,V&gt; to Node&lt;K,Integer&gt;. Integers will be empty. * * @param node * required node * @return converted node */ Node<K, Integer> convertToKeyInt(Node<K, V> node); /** * Convert Node&lt;K,Integer&gt; to Node&lt;K,V&gt;. Values will be empty. * * @param node * required node * @return converted node */ Node<K, V> convertToKeyValue(Node<K, Integer> node); }
25.517857
80
0.63261
943fc820c7ef15bbf0ad18fb584e464aa80cb179
1,327
package io.fairspace.saturn.services.metadata.validation; import io.fairspace.saturn.vocabulary.FS; import org.apache.jena.rdf.model.Model; import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDFS; public class UniqueLabelValidator implements MetadataRequestValidator { @Override public void validate(Model before, Model after, Model removed, Model added, ViolationHandler violationHandler) { added.listSubjectsWithProperty(RDFS.label) .forEachRemaining(subject -> { var resource = subject.inModel(after); var type = resource.getPropertyResourceValue(RDF.type); var label = resource.getProperty(RDFS.label).getString(); var conflictingResourceExists = after .listSubjectsWithProperty(RDFS.label, label) .filterDrop(subject::equals) .filterKeep(res -> res.hasProperty(RDF.type, type)) .filterDrop(res -> res.hasProperty(FS.dateDeleted)) .hasNext(); if (conflictingResourceExists) { violationHandler.onViolation("Duplicate label", resource, RDFS.label, null); } }); } }
47.392857
116
0.601356
db8337090e006da5aa0128357969c22b4523b9a8
1,869
package com.migibert.kheo.core.plugin.os; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.migibert.kheo.core.ServerEvent; import com.migibert.kheo.core.plugin.AbstractEventGenerator; public class OsEventGenerator extends AbstractEventGenerator<OsServerProperty> { private Logger logger = LoggerFactory.getLogger(OsEventGenerator.class); @Override public List<ServerEvent> generateSpecificEvents(List<OsServerProperty> original, List<OsServerProperty> discovered) { List<ServerEvent> generatedEvents = new ArrayList<>(); // // if (!original.equals(discovered)) { // if (!original.hardwarePlatform.equals(discovered.hardwarePlatform)) { // logger.info("OS Hardware platform changed! Generating event..."); // generatedEvents.add(new ServerEvent(EventType.OS_HARDWARE_PLATFORM_CHANGED.name(), original.hardwarePlatform, discovered.hardwarePlatform)); // } // if (!original.kernelName.equals(discovered.kernelName)) { // logger.info("OS Kernel name changed! Generating event..."); // generatedEvents.add(new ServerEvent(EventType.OS_KERNEL_NAME_CHANGED.name(), original.kernelName, discovered.kernelName)); // } // if (!original.kernelRelease.equals(discovered.kernelRelease)) { // logger.info("OS Kernel release changed! Generating event..."); // generatedEvents.add(new ServerEvent(EventType.OS_KERNEL_RELEASE_CHANGED.name(), original.kernelRelease, discovered.kernelRelease)); // } // if (!original.name.equals(discovered.name)) { // logger.info("OS name platform changed! Generating event..."); // generatedEvents.add(new ServerEvent(EventType.OS_NAME_CHANGED.name(), original.name, discovered.name)); // } // } return generatedEvents; } @Override public Class<OsServerProperty> getPropertyClass() { return OsServerProperty.class; } }
39.765957
146
0.762975
72117bca11491b01246595f1b27ecb17f37051fc
5,514
package subway.domain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; import static subway.message.ErrorMessage.LINE_INVALID_NAME_LENGTH; import static subway.message.ErrorMessage.LINE_STATIONS_ITEM_DUPLICATED; import static subway.message.ErrorMessage.LINE_STATIONS_TOO_SMALL; import static subway.message.ErrorMessage.LINE_STATION_ALREADY_EXIST; import static subway.message.ErrorMessage.LINE_STATION_DOES_NOT_EXIST; import static subway.message.ErrorMessage.LINE_STATION_INDEX_OUT_OF_RANGE; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class LineTest { private static final String stationName1 = "강남역"; private static final String stationName2 = "역삼역"; private static final String validLineName = "2호선"; private static final Station station1 = new Station(stationName1); private static final Station station2 = new Station(stationName2); private static List<Station> initialStations; private static Line line; private final String stationName3 = "매봉역"; private final String invalidLineName = "a"; private final Station station3 = new Station(stationName3); @BeforeAll static void init() { initialStations = new ArrayList<>(); initialStations.add(station1); initialStations.add(station2); line = new Line(validLineName, initialStations); } @Test void line_InvalidNameLength_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> { final Line line = new Line(invalidLineName, initialStations); }).withMessage(LINE_INVALID_NAME_LENGTH.toString()); } @Test void line_InitialStationsDuplicate_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> { final List<Station> invalidStations = new ArrayList<>(); invalidStations.add(station1); invalidStations.add(station1); final Line line = new Line(validLineName, invalidStations); }).withMessage(LINE_STATIONS_ITEM_DUPLICATED.toString()); } @Test void line_SmallInitialStationsSize_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> { final List<Station> invalidStations = new ArrayList<>(); invalidStations.add(new Station(stationName1)); final Line line = new Line(validLineName, invalidStations); }).withMessage(LINE_STATIONS_TOO_SMALL.toString()); } @Test void getName_SameName_Equal() { assertThat(line.getName()).isEqualTo(validLineName); } @Test void getName_DifferentName_NotEqual() { assertThat(line.getName()).isNotEqualTo(invalidLineName); } @Test void getStations_SameStation_Equal() { final List<Station> stationList = line.getStations(); assertThat(stationList.get(0)).isEqualTo(station1); assertThat(stationList.get(1)).isEqualTo(station2); } @Test void getStations_DifferentStation_NotEqual() { final List<Station> stationList = line.getStations(); assertThat(stationList.get(0)).isNotEqualTo(station2); assertThat(stationList.get(1)).isNotEqualTo(station3); } @Test void addStation_StationAlreadyExist_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> line.addStation(0, station1) ).withMessage(LINE_STATION_ALREADY_EXIST.toString()); } @Test void addStation_IndexOutOfRange_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> line.addStation(-1, station3) ).withMessage(LINE_STATION_INDEX_OUT_OF_RANGE.toString()); assertThatIllegalArgumentException().isThrownBy(() -> line.addStation(line.getStations().size() + 1, station3) ).withMessage(LINE_STATION_INDEX_OUT_OF_RANGE.toString()); } @Test void addStation_ValidFormat_NoExceptionThrown() { assertThatNoException().isThrownBy(() -> { final Line tempLine = new Line(validLineName, initialStations); tempLine.addStation(0, station3); }); assertThatNoException().isThrownBy(() -> { final Line tempLine = new Line(validLineName, initialStations); tempLine.addStation(tempLine.getStations().size(), station3); }); } @Test void removeStation_StationNotExist_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> line.removeStation(station3) ).withMessage(LINE_STATION_DOES_NOT_EXIST.toString()); } @Test void removeStation_TooSmallStationListSize_ExceptionThrown() { assertThatIllegalArgumentException().isThrownBy(() -> line.removeStation(station1) ).withMessage(LINE_STATIONS_TOO_SMALL.toString()); } @Test void removeStation_ValidFormat_NoExceptionThrown() { assertThatNoException().isThrownBy(() -> { final List<Station> stations = new ArrayList<>(); stations.add(new Station(stationName1)); stations.add(new Station(stationName2)); stations.add(station3); final Line tempLine = new Line(validLineName, stations); tempLine.removeStation(station3); }); } }
38.291667
81
0.699855
cce1146701769dac0b9837d333e14b0c89dc5c2e
1,209
package seedu.address.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_REPEATED_PREFIX_COMMAND = "Repeated prefixes are not allowed!"; public static final String MESSAGE_INVALID_EXPENSE_DISPLAYED_INDEX = "The expense index provided is invalid"; public static final String MESSAGE_BUDGET_DOES_NOT_EXIST_FOR_CATEGORY = "There is no budget for that category"; public static final String MESSAGE_INVALID_DEBT_DISPLAYED_INDEX = "The debt index provided is invalid"; public static final String MESSAGE_INVALID_RECURRING_DISPLAYED_INDEX = "The recurring index provided is invalid"; public static final String MESSAGE_EXPENSES_FOUND_OVERVIEW = "%1$d expenses found!"; public static final String MESSAGE_DEBTS_FOUND_OVERVIEW = "%1$d debts found!"; public static final String MESSAGE_RECURRINGS_FOUND_OVERVIEW = "%1$d recurrings found!"; public static final String MESSAGE_BUDGET_EXISTS = "Budget already exists for that category."; }
60.45
117
0.791563
5ad8bdf1dd605e1e9d7f7d7ae0760dd7aecd08bd
3,684
package cellsociety_team17; import java.util.List; import javafx.scene.shape.Shape; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public abstract class Cell { protected static final Color[] STATE_COLORS = { Color.WHITE, Color.BLUE, Color.RED }; private int myState; private int myRow; private int myColumn; private Shape myShape; private List<Cell> myNeighbors; public static final int CELLSIZE = 40; public Cell(int row, int column, int state) { myState = state; myRow = row; myColumn = column; myShape = new Rectangle(CELLSIZE, CELLSIZE); myShape.setTranslateX(myColumn * CELLSIZE); myShape.setTranslateY(myRow * CELLSIZE); //this.getMyShape().addEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler); } /*EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { int randomState = (int) Math.random() * 2; setMyState(randomState) ; myShape.setFill(STATE_COLORS[randomState]); } }; */ public Cell(int row, int column, int state, Shape shape) { this(row, column, state); myShape = shape; } /** * Returns the int value of current state * * @return int the current state of the cell */ public int getMyState() { return myState; } /** * Sets the int value state of the cell * * @param state * int value of current state */ public void setMyState(int state) { myState = state; } /** * Returns the int value of the cell's row * * @return int row containing the cell */ public int getMyRow() { return myRow; } /** * Sets the int value of the row in the grid representing this cell * * @param r * int value of the row in the grid */ public void setMyRow(int r) { myRow = r; } /** * Returns the int value of the cell's column * * @return int column containing the cell */ public int getMyColumn() { return myColumn; } /** * Sets the int value of the column in the grid representing this cell * * @param c * int value of the column in the grid */ public void setMyColumn(int c) { myColumn = c; } /** * returns the Shape instance of this cell * * @return Shape of the cell */ public Shape getMyShape() { return myShape; } /** * Sets the shape value of a cell * * @param s * Shape of the cell */ public void setMyShape(Shape s) { myShape = s; this.updateColor(); if(myShape.getClass().getSimpleName().equals("Triangle")) { myShape.setTranslateY(myRow * myShape.getBoundsInLocal().getHeight()); if(myColumn % 2 == 0) { myShape.setRotate(180); myShape.setTranslateX(((myColumn) * myShape.getBoundsInLocal().getWidth())-((myColumn/2)* myShape.getBoundsInLocal().getWidth())); } else { myShape.setTranslateX(((myColumn-1) * myShape.getBoundsInLocal().getWidth())-((myColumn/2)* myShape.getBoundsInLocal().getWidth())); } } } /** * Gets an ArrayList<Cell> of cells containing all the neighboring cells * * @return ArrayList<Cell><CEll> */ public List<Cell> getNeighbors() { return getMyNeighbors(); } /** * Sets an ArrayList<Cell> of cells containing all the neighboring cells * * @param neighbors */ public void setNeighbors(List<Cell> neighbors) { setMyNeighbors(neighbors); } abstract List<Cell> update(); abstract void updateColor(); public List<Cell> getMyNeighbors() { return myNeighbors; } public void setMyNeighbors(List<Cell> neighbors) { this.myNeighbors = neighbors; } }
22.463415
136
0.663409
641fee83e494ecf8481f216c38ee906bfed9c181
3,550
/* * Copyright (c) 2014, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package jakarta.tutorial.synchconsumer; import jakarta.annotation.Resource; import jakarta.jms.ConnectionFactory; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.JMSRuntimeException; import jakarta.jms.Message; import jakarta.jms.Queue; import jakarta.jms.TextMessage; import jakarta.jms.Topic; /** * The SynchConsumer class consists only of a main method, which fetches one or * more messages from a queue or topic using synchronous message delivery. Run * this program in conjunction with Producer. Specify "queue" or "topic" on the * command line when you run the program. */ public class SynchConsumer { @Resource(lookup = "java:comp/DefaultJMSConnectionFactory") private static ConnectionFactory connectionFactory; @Resource(lookup = "jms/MyQueue") private static Queue queue; @Resource(lookup = "jms/MyTopic") private static Topic topic; /** * Main method. * * @param args the destination name and type used by the example */ public static void main(String[] args) { String destType; Destination dest = null; JMSConsumer consumer; if (args.length != 1) { System.err.println("Program takes one argument: <dest_type>"); System.exit(1); } destType = args[0]; System.out.println("Destination type is " + destType); if (!(destType.equals("queue") || destType.equals("topic"))) { System.err.println("Argument must be \"queue\" or \"topic\""); System.exit(1); } try { if (destType.equals("queue")) { dest = (Destination) queue; } else { dest = (Destination) topic; } } catch (JMSRuntimeException e) { System.err.println("Error setting destination: " + e.toString()); System.exit(1); } /* * In a try-with-resources block, create context. * Create consumer. * Receive all text messages from destination until * a non-text message is received indicating end of * message stream. */ try (JMSContext context = connectionFactory.createContext();) { consumer = context.createConsumer(dest); int count = 0; while (true) { Message m = consumer.receive(1000); if (m != null) { if (m instanceof TextMessage) { // Comment out the following two lines to receive // a large volume of messages System.out.println( "Reading message: " + m.getBody(String.class)); count += 1; } else { break; } } } System.out.println("Messages received: " + count); } catch (JMSException e) { System.err.println("Exception occurred: " + e.toString()); System.exit(1); } System.exit(0); } }
32.87037
79
0.584225
10764b87cea5b59164efeab05565e735acd0f39e
2,289
package com.test; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import java.util.concurrent.TimeUnit; /** * @author ZhangShaowei on 2020/4/8 14:17 */ @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Thread) @Fork(2) @Warmup(iterations = 2, time = 5) @Measurement(iterations = 10, time = 5) public class BenchmarkTests { // ConfigurableApplicationContext context; // @Setup(Level.Trial) // public void init() { // context = SpringApplication.run(TestApplication.class); // } public void shutdown() { } @Benchmark public void test1() { } // public static void main(String[] args) throws RunnerException { // Options options = new OptionsBuilder() // .include(BenchmarkTests.class.getSimpleName()) //// .warmupIterations(2) //// .measurementIterations(10) // .threads(1) // .measurementTime(TimeValue.seconds(1)) // .build(); // new Runner(options).run(); // } // // ConfigurableApplicationContext context; // // AuthenticationService authenticationService; // // // @Setup(Level.Trial) // public void init() { // context = SpringApplication.run(GatewayApplication.class); // authenticationService = context.getBean(AuthenticationService.class); // } // // // @Param({"ROLE_SUPER_ADMIN", // "ROLE_ADMIN", // "ROLE_PC_ADMIN", // "ROLE_PC_OPER", // "ROLE_TC_ADMIN", // "ROLE_TC_OPER", // "ROLE_SC_ADMIN", // "ROLE_RC_ADMIN", // "ROLE_EPC_USER", // "ROLE_EPC_ADMIN", // "ROLE_SUB_ADMIN"}) // private String mark; // // @Benchmark // public void test1() { // this.authenticationService.authenticate("/smc/actuator/info", "POST", Collections.singletonList(this.mark)); // } }
27.25
118
0.633901
b7a79fac524e1f54f4abfcd1b2cc1c00b1c87bdf
1,533
package lark.core.lang; import lark.core.enums.BaseEnum; /** * @author cuigh */ public class BusinessException extends RuntimeException implements Error { protected int code; protected String detail; public BusinessException() { super(); } public BusinessException(int code) { super(); this.code = code; } public BusinessException(Error error) { this(error.getCode(), error.getMessage()); } public BusinessException(int code, String msg) { super(msg); this.code = code; } public BusinessException(BaseEnum baseEnum) { this(baseEnum.getCode(), baseEnum.getMsg()); } public BusinessException(int code, Throwable inner) { super(inner); this.code = code; } public BusinessException(int code, String msg, Throwable inner) { super(msg, inner); this.code = code; } public BusinessException(int code, String msg, String detail) { super(msg); this.code = code; this.detail = detail; } public BusinessException(int code, String msg, String detail, Throwable inner) { super(msg, inner); this.code = code; this.detail = detail; } @Override public int getCode() { return code; } public String getDetail() { return detail; } public void setCode(int code) { this.code = code; } public void setDetail(String detail) { this.detail = detail; } }
19.909091
84
0.598174
7fd201be93f6adbdd57d6ba9269599f4e3b9ec27
1,216
/* Copyright (C) 2004 Versant Inc. http://www.db4o.com */ package com.db4o.cs.internal; import com.db4o.cs.internal.messages.*; import com.db4o.foundation.*; class BlobProcessor implements Runnable { private ClientObjectContainer stream; private Queue4 queue = new NonblockingQueue(); private boolean terminated = false; BlobProcessor(ClientObjectContainer aStream){ stream = aStream; } void add(MsgBlob msg){ synchronized(queue){ queue.add(msg); } } synchronized boolean isTerminated(){ return terminated; } public void run(){ try{ Socket4Adapter socket = stream.createParallelSocket(); MsgBlob msg = null; // no blobLock synchronisation here, since our first msg is valid synchronized(queue){ msg = (MsgBlob)queue.next(); } while(msg != null){ msg.write(socket); msg.processClient(socket); synchronized(stream._blobLock){ synchronized(queue){ msg = (MsgBlob)queue.next(); } if(msg == null){ terminated = true; Msg.CLOSE_SOCKET.write(socket); try{ socket.close(); }catch(Exception e){ } } } } }catch(Exception e){ e.printStackTrace(); } } }
19.612903
68
0.643092
3e8f9e16931ec3c10b71b46a90b46ddf496030ed
4,930
/* * This file is generated by jOOQ. */ package com.sourceclear.agile.piplanning.service.jooq.tables; import com.sourceclear.agile.piplanning.service.jooq.Agile; import com.sourceclear.agile.piplanning.service.jooq.Indexes; import com.sourceclear.agile.piplanning.service.jooq.Keys; import com.sourceclear.agile.piplanning.service.jooq.tables.records.TicketPinsRecord; import java.util.Arrays; import java.util.List; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Row3; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.TableOptions; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class TicketPins extends TableImpl<TicketPinsRecord> { private static final long serialVersionUID = -548516997; /** * The reference instance of <code>agile.ticket_pins</code> */ public static final TicketPins TICKET_PINS = new TicketPins(); /** * The class holding records for this type */ @Override public Class<TicketPinsRecord> getRecordType() { return TicketPinsRecord.class; } /** * The column <code>agile.ticket_pins.ticket_id</code>. */ public final TableField<TicketPinsRecord, Long> TICKET_ID = createField(DSL.name("ticket_id"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>agile.ticket_pins.sprint_id</code>. */ public final TableField<TicketPinsRecord, Long> SPRINT_ID = createField(DSL.name("sprint_id"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>agile.ticket_pins.board_id</code>. */ public final TableField<TicketPinsRecord, Long> BOARD_ID = createField(DSL.name("board_id"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * Create a <code>agile.ticket_pins</code> table reference */ public TicketPins() { this(DSL.name("ticket_pins"), null); } /** * Create an aliased <code>agile.ticket_pins</code> table reference */ public TicketPins(String alias) { this(DSL.name(alias), TICKET_PINS); } /** * Create an aliased <code>agile.ticket_pins</code> table reference */ public TicketPins(Name alias) { this(alias, TICKET_PINS); } private TicketPins(Name alias, Table<TicketPinsRecord> aliased) { this(alias, aliased, null); } private TicketPins(Name alias, Table<TicketPinsRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); } public <O extends Record> TicketPins(Table<O> child, ForeignKey<O, TicketPinsRecord> key) { super(child, key, TICKET_PINS); } @Override public Schema getSchema() { return Agile.AGILE; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.TICKET_PINS_BOARD_ID_IDX); } @Override public UniqueKey<TicketPinsRecord> getPrimaryKey() { return Keys.TICKET_PINS_PKEY; } @Override public List<UniqueKey<TicketPinsRecord>> getKeys() { return Arrays.<UniqueKey<TicketPinsRecord>>asList(Keys.TICKET_PINS_PKEY, Keys.TICKET_PINS_UNIQUE); } @Override public List<ForeignKey<TicketPinsRecord, ?>> getReferences() { return Arrays.<ForeignKey<TicketPinsRecord, ?>>asList(Keys.TICKET_PINS__TICKET_PINS_TICKET_ID_FKEY, Keys.TICKET_PINS__TICKET_PINS_SPRINT_ID_FKEY, Keys.TICKET_PINS__TICKET_PINS_BOARD_ID_FKEY); } public Tickets tickets() { return new Tickets(this, Keys.TICKET_PINS__TICKET_PINS_TICKET_ID_FKEY); } public Sprints sprints() { return new Sprints(this, Keys.TICKET_PINS__TICKET_PINS_SPRINT_ID_FKEY); } public Boards boards() { return new Boards(this, Keys.TICKET_PINS__TICKET_PINS_BOARD_ID_FKEY); } @Override public TicketPins as(String alias) { return new TicketPins(DSL.name(alias), this); } @Override public TicketPins as(Name alias) { return new TicketPins(alias, this); } /** * Rename this table */ @Override public TicketPins rename(String name) { return new TicketPins(DSL.name(name), null); } /** * Rename this table */ @Override public TicketPins rename(Name name) { return new TicketPins(name, null); } // ------------------------------------------------------------------------- // Row3 type methods // ------------------------------------------------------------------------- @Override public Row3<Long, Long, Long> fieldsRow() { return (Row3) super.fieldsRow(); } }
28.830409
199
0.660243
f83078a6912980099a3115726da1b7c7bd73a7ed
1,392
package seedu.address.model.timetable; import java.util.HashMap; import java.util.Map; public class LessonTypeMapping { private static LessonTypeMapping mapping = null; private Map<String, String> lessonTypeMap; // Obtained data from "https://github.com/nusmodifications/nusmods/blob/8e76af2e407f602dcecab538804009b6de280196/website/src/utils/timetables.ts" private LessonTypeMapping() { lessonTypeMap = new HashMap<>(); lessonTypeMap.put("LEC", "Lecture"); lessonTypeMap.put("TUT", "Tutorial"); lessonTypeMap.put("LAB", "Laboratory"); lessonTypeMap.put("REC", "Recitation"); lessonTypeMap.put("SEC", "Sectional Teaching"); lessonTypeMap.put("DLEC", "Design Lecture"); lessonTypeMap.put("PLEC", "Packaged Lecture"); lessonTypeMap.put("PTUT", "Packaged Tutorial"); lessonTypeMap.put("SEM", "Seminar-Style Module Class"); lessonTypeMap.put("TUT2", "Tutorial Type 2"); lessonTypeMap.put("TUT3", "Tutorial Type 3"); lessonTypeMap.put("WS", "Workshop"); } public String get(String key) { return lessonTypeMap.get(key); } // static method to create instance of Singleton class public static LessonTypeMapping getInstance() { if (mapping == null) { mapping = new LessonTypeMapping(); } return mapping; } }
35.692308
149
0.658764
7fc04355171328591eeba3510438a232b855c0c1
1,249
package com.buraktuysuz.secondhomework.entityService; import com.buraktuysuz.secondhomework.dao.UserDao; import com.buraktuysuz.secondhomework.entity.User; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserEntityService { private UserDao userDao; public UserEntityService(UserDao userDao) { this.userDao=userDao; } public List<User> findAll() { return (List<User>) userDao.findAll(); } public User findByUsername(String username) { return userDao.findByUsername(username); } public User findByPhone(String phone) { return userDao.findByPhone(phone); } public User findById(Long id){ Optional<User> optionalProduct = userDao.findById(id); User user = null; if (optionalProduct.isPresent()){ user = optionalProduct.get(); } return user; } public void delete(User user) { userDao.delete(user); } public User save(User user) { user =userDao.save(user);; return user; } public void deleteById(Long id) { userDao.deleteById(id); } public long count() { return userDao.count(); } }
22.709091
71
0.655725
06406667256f25598552c4561efa3cd1f4cfa0cf
3,434
package com.someoneice.partyrecipes.Block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nullable; public class dgjar extends Block { public static final IntegerProperty AMOUNT = IntegerProperty.create("amount", 1, 3); public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; public dgjar() { super(Properties.of(Material.GLASS).strength(2.0f).noOcclusion()); } protected static final VoxelShape[] SHAPE = new VoxelShape[]{ Block.box(6, 0, 6, 18, 18, 18), Block.box(6, 0, 6, 10, 10, 10), Block.box(6, 0, 6, 10, 10, 7), Block.box(6, 0, 6, 15, 10, 6) }; @Override public VoxelShape getShape(BlockState p_220053_1_, BlockGetter p_220053_2_, BlockPos p_220053_3_, CollisionContext p_220053_4_) { return SHAPE[p_220053_1_.getValue(AMOUNT)]; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(AMOUNT, FACING); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState().setValue(FACING, context.getHorizontalDirection()); } @Override public BlockState updateShape(BlockState p_196271_1_, Direction p_196271_2_, BlockState p_196271_3_, LevelAccessor p_196271_4_, BlockPos p_196271_5_, BlockPos p_196271_6_) { return p_196271_2_ == Direction.DOWN && !p_196271_1_.canSurvive(p_196271_4_, p_196271_5_) ? Blocks.AIR.defaultBlockState() : super.updateShape(p_196271_1_, p_196271_2_, p_196271_3_, p_196271_4_, p_196271_5_, p_196271_6_); } @Override public InteractionResult use(BlockState block, Level world, BlockPos pos, Player player, InteractionHand data, BlockHitResult hitfx) { player.getFoodData().eat(1, 0.1F); world.playSound((Player) null, pos, SoundEvents.GENERIC_EAT, SoundSource.BLOCKS, 1.0F, 1.0F + world.random.nextFloat()*0.3F); if (!world.isClientSide()) { if (world.random.nextInt(16) == 0) { world.removeBlock(pos, false); world.gameEvent(player, GameEvent.BLOCK_DESTROY, pos); } } return InteractionResult.SUCCESS; } }
44.025641
229
0.746069
39bde49a9af1461e3b16533415a59f6c4d0fb9c9
15,609
/* * Copyright (C) 2018 Seoul National University * * 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 edu.snu.mist.common.operators; import edu.snu.mist.common.MistDataEvent; import edu.snu.mist.common.MistWatermarkEvent; import edu.snu.mist.common.SerializeUtils; import edu.snu.mist.common.parameters.CepEventPatterns; import edu.snu.mist.common.parameters.WindowTime; import edu.snu.mist.common.types.Tuple2; import org.apache.reef.tang.annotations.Parameter; import javax.inject.Inject; import java.io.IOException; import java.util.*; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * This operator applies complex event pattern to the the data received and emit the matched patterns. * @param <T> the type of user-defined event */ public final class CepOperator<T> extends OneStreamOperator { private static final Logger LOG = Logger.getLogger(CepOperator.class.getName()); /** * Input event pattern sequence. */ private final List<CepEventPattern<T>> eventPatternList; /** * The minimum index of final state. * All the states are final state after this index. * The minimum final state index of following example is 2 * 1(loop)---2---3(optional)---4(optional) */ private final int minFinalStateIndex; /** * For each state, calculate min state's index and max state's index to proceed. * The proceed index of state 1 in following example is (1, 4). * 1(loop)---2(optional)---3(optional)---4 */ private final List<Tuple2<Integer, Integer>> proceedIndexList; /** * List of event stacks which are the candidates of matched pattern until current input. */ private final List<EventStack<T>> matchedEventStackList; /** * Window time of cep query. */ private final long windowTime; @Inject private CepOperator( @Parameter(CepEventPatterns.class) final String serializedEvents, @Parameter(WindowTime.class) final long windowTime, final ClassLoader classLoader) throws IOException, ClassNotFoundException { this(SerializeUtils.deserializeFromString(serializedEvents, classLoader), windowTime); } /** * Constructor of cep operator. * @param cepEventPatterns cep event list * @param windowTime window time */ public CepOperator( final List<CepEventPattern<T>> cepEventPatterns, final long windowTime) { // Add all the event sequence. this.eventPatternList = new ArrayList<>(); this.eventPatternList.addAll(cepEventPatterns); // Add first initial state as null cep event. this.eventPatternList.add(0, null); // Set window time. this.windowTime = windowTime; this.matchedEventStackList = new ArrayList<>(); // Find minimum index of final state. for (int eventIndex = eventPatternList.size() - 1; true; eventIndex--) { if (!eventPatternList.get(eventIndex).isOptional()) { this.minFinalStateIndex = eventIndex; break; } else if (eventIndex == 1) { this.minFinalStateIndex = 1; break; } } // Initialize proceed index list. this.proceedIndexList = new ArrayList<>(); for (int eventIndex = 0; eventIndex < eventPatternList.size(); eventIndex++) { int minIndex; int maxIndex; // If loop state, set it to minimum index. if (eventIndex != 0 && eventPatternList.get(eventIndex).isRepeated()) { minIndex = eventIndex; maxIndex = eventIndex + 1; // else normal state, (current index + 1) to minimum index. } else { minIndex = eventIndex + 1; maxIndex = minIndex; } // calculate the maximum index. for (int i = eventIndex + 1; i < eventPatternList.size() - 1; i++) { // If next state is optional, increase max index. if (eventPatternList.get(i).isOptional()) { maxIndex++; } else { break; } } // No proceed state for current state, set min and max index to (-1). if (minIndex >= eventPatternList.size()) { minIndex = -1; maxIndex = -1; } else if (maxIndex >= eventPatternList.size()) { maxIndex = minIndex; } final Tuple2<Integer, Integer> proceedIndexTup = new Tuple2<>(minIndex, maxIndex); this.proceedIndexList.add(proceedIndexTup); } } @Override public void processLeftData(final MistDataEvent data) { final T input = (T) data.getValue(); final long timeStamp = data.getTimestamp(); // Save the index of delete stack. final List<EventStack<T>> newMatchedEventStackList = new ArrayList<>(); for (int iterStackIndex = 0; iterStackIndex < matchedEventStackList.size(); iterStackIndex++) { final EventStack<T> stack = matchedEventStackList.get(iterStackIndex); // Flag whether discard original event stack or not. boolean isDiscard = true; if (stack.getFirstEventTime() + windowTime >= timeStamp) { final int stateIndex = stack.getStack().peek().getIndex(); final int minProceedIndex = (int) proceedIndexList.get(stateIndex).get(0); final int maxProceedIndex = (int) proceedIndexList.get(stateIndex).get(1); // Current state is final state and has no transition condition. if (minProceedIndex == -1 && maxProceedIndex == -1) { continue; } // Current state. final CepEventPattern<T> currEventPattern = eventPatternList.get(stateIndex); for (int proceedIndex = minProceedIndex; proceedIndex <= maxProceedIndex; proceedIndex++) { // If the current state is loop state. if (proceedIndex == stateIndex && proceedIndex != 0) { if (currEventPattern.isRepeated() && !stack.getStack().peek().isStopped()) { // Current looping state's iteration times. final int times = stack.getStack().peek().getlist().size(); // Stop condition is triggered. if (currEventPattern.getStopCondition().test(input)) { stack.getStack().peek().setStopped(); // If the current event does not satisfy the min times, continue the iteration. if (times < currEventPattern.getMinRepetition()) { continue; } } else if (currEventPattern.getCondition().test(input)) { // If the current continguity is strict, but the stack does not include the last event, // then it would be eliminated. if (currEventPattern.getInnerContiguity() == CepEventContiguity.STRICT && !stack.isIncludingLast()) { continue; } // If current entry satisfies times condition. if (currEventPattern.getMaxRepetition() == -1 || times < currEventPattern.getMaxRepetition()) { final EventStack<T> newStack = new EventStack<>(stack.getFirstEventTime()); newStack.setStack(stack.deepCopy().getStack()); newStack.getStack().peek().addEvent(input); newMatchedEventStackList.add(newStack); // Emit the final state's stack. if (proceedIndex >= minFinalStateIndex && newStack.isEmitted()) { emit(data, newStack); } // If the current contiguity is NDR, then the stack should not be discarded. if (currEventPattern.getInnerContiguity() == CepEventContiguity.NON_DETERMINISTIC_RELAXED) { isDiscard = false; } } // If the current input does not satisfy the transition condition. } else { if (currEventPattern.getInnerContiguity() == CepEventContiguity.STRICT) { stack.getStack().peek().setStopped(); } // If transition condition of relaxed contiguity is not satisfied, // the current original stack should not be discarded. if (currEventPattern.getInnerContiguity() == CepEventContiguity.RELAXED || currEventPattern.getInnerContiguity() == CepEventContiguity.NON_DETERMINISTIC_RELAXED) { isDiscard = false; } } } } else { final CepEventPattern<T> cepEventPattern = eventPatternList.get(proceedIndex); final int times = stack.getStack().peek().getlist().size(); if (cepEventPattern.getCondition().test(input)) { // If the current continguity is strict, but the stack does not include the last event, // then it would be eliminated. if (cepEventPattern.getContiguity() == CepEventContiguity.STRICT && !stack.isIncludingLast()) { continue; } final EventStack<T> newStack = new EventStack<>(stack.getFirstEventTime()); newStack.setStack(stack.deepCopy().getStack()); final EventStackEntry<T> newEntry = new EventStackEntry<>(proceedIndex); newEntry.addEvent(input); newStack.getStack().push(newEntry); newMatchedEventStackList.add(newStack); // Emit the stack at the final state. if (proceedIndex >= minFinalStateIndex) { emit(data, newStack); } // Do not discard the stack of ndr contiguity. if (cepEventPattern.getContiguity() == CepEventContiguity.NON_DETERMINISTIC_RELAXED) { isDiscard = false; } } else { // If transition condition of ndr contiguity is not satisfied, // the current original stack should not be discarded. if (cepEventPattern.getContiguity() == CepEventContiguity.NON_DETERMINISTIC_RELAXED) { isDiscard = false; } } } } } // Check whether current stack should be discard or not. if (!isDiscard) { final EventStack<T> newStack = stack.deepCopy(); newStack.setIncludeLast(false); if (!stack.isEmitted()) { newStack.setAlreadyEmitted(); } newMatchedEventStackList.add(newStack); } } // The condition for initial state to first state. final int minProceedIndex = (int) proceedIndexList.get(0).get(0); final int maxProceedIndex = (int) proceedIndexList.get(0).get(1); for (int proceedIndex = minProceedIndex; proceedIndex <= maxProceedIndex; proceedIndex++) { final CepEventPattern<T> cepEventPattern = eventPatternList.get(proceedIndex); if (cepEventPattern.getCondition().test(input)) { final EventStack<T> newStack = new EventStack<>(timeStamp); final EventStackEntry<T> newEntry = new EventStackEntry<>(proceedIndex); newEntry.addEvent(input); newStack.getStack().push(newEntry); newMatchedEventStackList.add(newStack); // If final state, emit the stack. if (proceedIndex >= minFinalStateIndex) { emit(data, newStack); } } } // Update matched event stack list. matchedEventStackList.clear(); matchedEventStackList.addAll(newMatchedEventStackList); } @Override public void processLeftWatermark(final MistWatermarkEvent input) { outputEmitter.emitWatermark(input); } /** * Emit the event stack which is in final state. * @param input current mist data event * @param eventStack event stack */ private void emit(final MistDataEvent input, final EventStack<T> eventStack) { final Map<String, List<T>> output = new HashMap<>(); final long timeStamp = input.getTimestamp(); // Check whether current event stack satisfies the loop condition. final int finalStateIndex = eventStack.getStack().peek().getIndex(); final EventStackEntry<T> finalEntry = eventStack.getStack().peek(); final int times = finalEntry.getlist().size(); final CepEventPattern<T> finalState = eventPatternList.get(finalStateIndex); if (!finalState.isRepeated() || (times >= finalState.getMinRepetition() && (finalState.getMaxRepetition() == -1 || times <= finalState.getMaxRepetition()))) { // Make an output data. for (final EventStackEntry<T> iterEntry : eventStack.getStack()) { output.put(eventPatternList.get(iterEntry.getIndex()).getEventPatternName(), iterEntry.getlist()); } if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} processes {1} to {2}", new Object[]{this.getClass().getName(), input, output}); } outputEmitter.emitData(new MistDataEvent(output, timeStamp)); eventStack.setAlreadyEmitted(); } } }
44.853448
119
0.544494
5176ca826af62d0dc44b6235fed4f685bbbbc49e
1,320
package gui; import javax.swing.*; import java.awt.*; public class FriendListPanel extends JPanel { private final JPanel friendsPanel; private final JButton btRefresh; public FriendListPanel() { setLayout(new BorderLayout()); var btContainer = new JPanel(); btRefresh = new JButton("Refresh"); btContainer.add(btRefresh); add(btContainer, BorderLayout.PAGE_START); // Button is in container and not directly in the panel // because with the BorderLayout.PAGE_START it'd fill that // whole segment of the layout. friendsPanel = new JPanel(); friendsPanel.setLayout(new BoxLayout(friendsPanel, BoxLayout.PAGE_AXIS)); var scrollPane = new JScrollPane(); scrollPane.setViewportView(friendsPanel); scrollPane.getVerticalScrollBar().setUnitIncrement(20); add(scrollPane, BorderLayout.CENTER); } public void addFriendBar(FriendBar bar) { friendsPanel.add(bar); } public void removeFriendBar(FriendBar bar) { friendsPanel.remove(bar); repaint(); revalidate(); } public void clear() { friendsPanel.removeAll(); } public void onClickRefresh(Runnable action) { btRefresh.addActionListener(e -> action.run()); } }
26.938776
81
0.656061
0718ca62125197457ac511d6261f3b41b1cb13b4
1,319
<#include "/macro.include"/> <#include "/java_copyright.include"> <#assign className = table.className> <#assign classNameLower = className?uncap_first> <#list table.pkColumns as column> <#assign pkJavaType = column.javaType> </#list> package ${basepackage}.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "${table.sqlName}") public class ${className} implements java.io.Serializable{ private static final long serialVersionUID = 1L; <@generateFields/> <@generateGetAndSet/> } <#macro generateFields> <#list table.columns as column> /** * ${column.columnAlias!} */ <#if column.pk> @Id <#else> <#if column.sqlName==column.columnNameLower> @Column <#else> @Column(name="${column.sqlName}") </#if> </#if> private ${column.simpleJavaType} ${column.columnNameLower}; </#list> </#macro> <#macro generateGetAndSet> <#list table.columns as column> public void set${column.columnName}(${column.simpleJavaType} ${column.columnNameLower}) { this.${column.columnNameLower} = ${column.columnNameLower}; } public ${column.simpleJavaType} get${column.columnName}() { return this.${column.columnNameLower}; } </#list> </#macro>
24.425926
93
0.686884
516b09fd1c001a7e9866a399f59b52a8778078b3
1,236
/* * Copyright (c) 2020 L3Harris Technologies */ package com.l3harris.swim.outputs.database; import com.l3harris.swim.outputs.Output; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.typesafe.config.Config; import org.bson.Document; import org.json.JSONObject; import org.json.XML; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MongoOutput extends Output { private static Logger logger = LoggerFactory.getLogger(MongoOutput.class); private MongoClient client; private MongoDatabase database; private MongoCollection collection; public MongoOutput(Config config) { super(config); // TODO pass in mongo connection from config client = new MongoClient(); database = client.getDatabase("test"); collection = database.getCollection("messages"); logger.info("Connection to mongo successful"); } @Override public void output(String message) { JSONObject xmlJSONObj = XML.toJSONObject(message); xmlJSONObj.toString(); // TODO only add fields required collection.insertOne(Document.parse(xmlJSONObj.toString())); } }
28.090909
78
0.723301
67ceade7de0b8d6d989ccfb46946205bc5a0faa3
2,952
package com.pg85.otg.util.gen; import com.pg85.otg.constants.Constants; import com.pg85.otg.util.ChunkCoordinate; public class DecorationArea { // Anything that uses decoration bounds should be using the methods in this class. // TODO: Refactor this, change the decorated area from 2x2 to 3x3 chunks and // remove the +8 decoration offset used for resources. BO/Carver offsets are also // in here for clarity for the moment, should clean that up when resources are // properly re-aligned. public static final int DECORATION_OFFSET = 8; public static final int CARVER_OFFSET = 8; public static final int BO_CHUNK_CENTER_X = 8; public static final int BO_CHUNK_CENTER_Z = 7; private static final int WIDTH_IN_CHUNKS = 2; private static final int HEIGHT_IN_CHUNKS = 2; public static final int WIDTH = WIDTH_IN_CHUNKS * Constants.CHUNK_SIZE; public static final int HEIGHT = HEIGHT_IN_CHUNKS * Constants.CHUNK_SIZE; private final int minX; private final int maxX; private final int minZ; private final int maxZ; private final int width; private final int height; private final ChunkCoordinate chunkBeingDecorated; public DecorationArea(ChunkCoordinate chunkBeingDecorated) { int top = 0; int right = Constants.CHUNK_SIZE; int bottom = Constants.CHUNK_SIZE; int left = 0; this.width = left + right + Constants.CHUNK_SIZE; this.height = top + bottom + Constants.CHUNK_SIZE; this.minX = chunkBeingDecorated.getBlockX() - left; this.maxX = chunkBeingDecorated.getBlockX() + Constants.CHUNK_SIZE + right; this.minZ = chunkBeingDecorated.getBlockZ() - top; this.maxZ = chunkBeingDecorated.getBlockZ() + Constants.CHUNK_SIZE + bottom; this.chunkBeingDecorated = chunkBeingDecorated; } // TODO: Some resources don't check decoration bounds before calling getMaterial/setBlock, // which does the check and returns null/ignores the call. Making resources check preemptively // may be more efficient and would allow us to remove isInAreaBeingDecorated checks in // getMaterial/setBlock (except for debugging purposes). public boolean isInAreaBeingDecorated(int blockX, int blockZ) { return blockX >= this.minX && blockX < this.maxX && blockZ >= this.minZ && blockZ < this.maxZ ; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public int getTop() { return this.minZ; } public int getBottom() { return this.minZ + this.height; } public int getLeft() { return this.minX; } public int getRight() { return this.minX + this.width; } public ChunkCoordinate getChunkBeingDecorated() { return this.chunkBeingDecorated; } public int getChunkBeingDecoratedCenterX() { return this.chunkBeingDecorated.getChunkX() * Constants.CHUNK_SIZE + DECORATION_OFFSET; } public int getChunkBeingDecoratedCenterZ() { return this.chunkBeingDecorated.getChunkZ() * Constants.CHUNK_SIZE + DECORATION_OFFSET; } }
27.849057
95
0.751016
7aec8b45a0eaf63f29d813b51346e4d0434e68f7
34,693
/** * 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.cxf.tools.corba.processors; import java.io.File; import java.net.URI; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.wsdl.Definition; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.xml.WSDLWriter; import javax.xml.namespace.QName; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.apache.cxf.binding.corba.wsdl.AddressType; import org.apache.cxf.binding.corba.wsdl.Anonarray; import org.apache.cxf.binding.corba.wsdl.Anonfixed; import org.apache.cxf.binding.corba.wsdl.Anonsequence; import org.apache.cxf.binding.corba.wsdl.Anonstring; import org.apache.cxf.binding.corba.wsdl.Array; import org.apache.cxf.binding.corba.wsdl.CorbaType; import org.apache.cxf.binding.corba.wsdl.Struct; import org.apache.cxf.binding.corba.wsdl.TypeMappingType; import org.apache.cxf.binding.corba.wsdl.Union; import org.apache.cxf.binding.corba.wsdl.Unionbranch; import org.apache.cxf.helpers.DOMUtils; import org.apache.cxf.tools.corba.common.WSDLCorbaFactory; import org.apache.cxf.tools.corba.processors.wsdl.WSDLToCorbaBinding; import org.apache.cxf.tools.corba.processors.wsdl.WSDLToIDLAction; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class WSDLToCorbaBindingTypeTest { WSDLToCorbaBinding generator; WSDLWriter writer; @Before public void setUp() { generator = new WSDLToCorbaBinding(); try { WSDLCorbaFactory wsdlfactory = WSDLCorbaFactory .newInstance("org.apache.cxf.tools.corba.common.WSDLCorbaFactoryImpl"); writer = wsdlfactory.newWSDLWriter(); } catch (Exception ex) { ex.printStackTrace(); } } private Element getElementNode(Document document, String elName) { Element root = document.getDocumentElement(); for (Node nd = root.getFirstChild(); nd != null; nd = nd.getNextSibling()) { if (Node.ELEMENT_NODE == nd.getNodeType() && (elName.equals(nd.getNodeName()))) { return (Element)nd; } } return null; } @Test public void testWsAddressingAccountType() throws Exception { try { String fileName = getClass().getResource("/wsdl/wsaddressing_bank.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("Bank"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, DOMUtils.findAllElementsByTagNameNS(typemap, "http://cxf.apache.org/bindings/corba", "sequence").size()); assertEquals(2, DOMUtils.findAllElementsByTagNameNS(typemap, "http://cxf.apache.org/bindings/corba", "object").size()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("BankCORBABinding"); idlgen.setOutputFile("wsaddressing_bank.idl"); idlgen.generateIDL(model); File f = new File("wsaddressing_bank.idl"); assertTrue("wsaddressing_bank.idl should be generated", f.exists()); } finally { new File("wsaddressing_bank.idl").deleteOnExit(); } } @Test public void testWsAddressingBankType() throws Exception { try { String fileName = getClass().getResource("/wsdl/wsaddressing_account.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("Account"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:object").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("AccountCORBABinding"); idlgen.setOutputFile("wsaddressing_account.idl"); idlgen.generateIDL(model); File f = new File("wsaddressing_account.idl"); assertTrue("wsaddressing_account.idl should be generated", f.exists()); } finally { new File("wsaddressing_account.idl").deleteOnExit(); } } @Test public void testWsAddressingTypes() throws Exception { try { String fileName = getClass().getResource("/wsdl/wsaddressing_server.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("TestServer"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:object").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("TestServerCORBABinding"); idlgen.setOutputFile("wsaddressing_server.idl"); idlgen.generateIDL(model); File f = new File("wsaddressing_server.idl"); assertTrue("wsaddressing_server.idl should be generated", f.exists()); } finally { new File("wsaddressing_server.idl").deleteOnExit(); } } @Test public void testDateTimeTypes() throws Exception { try { String fileName = getClass().getResource("/wsdl/datetime.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("BasePortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(2, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(2, typemap.getElementsByTagName("corba:struct").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("BaseCORBABinding"); idlgen.setOutputFile("datetime.idl"); idlgen.generateIDL(model); File f = new File("datetime.idl"); assertTrue("datetime.idl should be generated", f.exists()); } finally { new File("datetime.idl").deleteOnExit(); } } @Test public void testNestedInterfaceTypes() throws Exception { try { String fileName = getClass().getResource("/wsdl/nested_interfaces.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("C.C1"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:anonstring").getLength()); assertEquals(9, typemap.getElementsByTagName("corba:struct").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("C.C1CORBABinding"); idlgen.setOutputFile("nested_interfaces.idl"); idlgen.generateIDL(model); File f = new File("nested_interfaces.idl"); assertTrue("nested_interfaces.idl should be generated", f.exists()); } finally { new File("nested_interfaces.idl").deleteOnExit(); } } @Test public void testNestedComplexTypes() throws Exception { try { String fileName = getClass().getResource("/wsdl/nested_complex.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("X"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(6, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(14, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:enum").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:array").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("XCORBABinding"); idlgen.setOutputFile("nested_complex.idl"); idlgen.generateIDL(model); File f = new File("nested_complex.idl"); assertTrue("nested_complex.idl should be generated", f.exists()); } finally { new File("nested_complex.idl").deleteOnExit(); } } @Test public void testNestedDerivedTypes() throws Exception { try { String fileName = getClass().getResource("/wsdl/nested-derivedtypes.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("DerivedTypesPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(6, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(58, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(3, typemap.getElementsByTagName("corba:sequence").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("DerivedTypesCORBABinding"); idlgen.setOutputFile("nested-derivedtypes.idl"); idlgen.generateIDL(model); File f = new File("nested-derivedtypes.idl"); assertTrue("nested-derivedtypes.idl should be generated", f.exists()); } finally { new File("nested-derivedtypes.idl").deleteOnExit(); } } @Test public void testNestedType() throws Exception { try { String fileName = getClass().getResource("/wsdl/nested.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("TypeInheritancePortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(4, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(23, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:anonstring").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("TypeInheritanceCORBABinding"); idlgen.setOutputFile("nested.idl"); idlgen.generateIDL(model); File f = new File("nested.idl"); assertTrue("nested.idl should be generated", f.exists()); } finally { new File("nested.idl").deleteOnExit(); } } @Test public void testNillableType() throws Exception { try { String fileName = getClass().getResource("/wsdl/nillable.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("NillablePortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(2, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:struct").getLength()); TypeMappingType mapType = (TypeMappingType)model.getExtensibilityElements().get(0); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("NillableCORBABinding"); idlgen.setOutputFile("nillable.idl"); idlgen.generateIDL(model); Union un = (Union)mapType.getStructOrExceptionOrUnion().get(2); assertEquals("Name is incorrect for Union Type", "long_nil", un.getName()); assertEquals("Type is incorrect for Union Type", "PEl", un.getType().getLocalPart()); Unionbranch unbranch = un.getUnionbranch().get(0); assertEquals("Name is incorrect for UnionBranch Type", "value", unbranch.getName()); assertEquals("Type is incorrect for UnionBranch Type", "long", unbranch.getIdltype().getLocalPart()); File f = new File("nillable.idl"); assertTrue("nillable.idl should be generated", f.exists()); } finally { new File("nillable.idl").deleteOnExit(); } } // tests Type Inheritance and attributes. @Test public void testTypeInheritance() throws Exception { try { String fileName = getClass().getResource("/wsdl/TypeInheritance.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("TypeInheritancePortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(3, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:anonstring").getLength()); assertEquals(17, typemap.getElementsByTagName("corba:struct").getLength()); TypeMappingType mapType = (TypeMappingType)model.getExtensibilityElements().get(0); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("TypeInheritanceCORBABinding"); idlgen.setOutputFile("typeInherit.idl"); idlgen.generateIDL(model); List<CorbaType> types = mapType.getStructOrExceptionOrUnion(); for (int i = 0; i < types.size(); i++) { CorbaType type = types.get(i); if ("Type5SequenceStruct".equals(type.getName())) { assertTrue("Name is incorrect for Type5SequenceStruct Type", type instanceof Struct); assertEquals("Type is incorrect for AnonSequence Type", "Type5", type.getType().getLocalPart()); } else if ("attrib2Type".equals(type.getName())) { assertTrue("Name is incorrect for attrib2Type Type", type instanceof Anonstring); assertEquals("Type is incorrect for AnonString Type", "string", type.getType().getLocalPart()); } else if ("attrib2Type_nil".equals(type.getName())) { assertTrue("Name is incorrect for Struct Type", type instanceof Union); assertEquals("Type is incorrect for AnonSequence Type", "attrib2", type.getType().getLocalPart()); } } File f = new File("typeInherit.idl"); assertTrue("typeInherit.idl should be generated", f.exists()); } finally { new File("typeInherit.idl").deleteOnExit(); } } // tests anonymous strings and fixed types. @Test public void testAnonFixedType() throws Exception { try { String fileName = getClass().getResource("/wsdl/anonfixed.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("X"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:anonfixed").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:anonstring").getLength()); assertEquals(3, typemap.getElementsByTagName("corba:struct").getLength()); TypeMappingType mapType = (TypeMappingType)model.getExtensibilityElements().get(0); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("XCORBABinding"); idlgen.setOutputFile("atype.idl"); idlgen.generateIDL(model); List<CorbaType> types = mapType.getStructOrExceptionOrUnion(); for (int i = 0; i < types.size(); i++) { CorbaType type = types.get(i); if (type instanceof Anonstring) { Anonstring str = (Anonstring)type; assertEquals("Name is incorrect for Array Type", "X._1_S", str.getName()); assertEquals("Type is incorrect for AnonString Type", "string", str.getType().getLocalPart()); } else if (type instanceof Anonfixed) { Anonfixed fx = (Anonfixed)type; assertEquals("Name is incorrect for Anon Array Type", "X._2_S", fx.getName()); assertEquals("Type is incorrect for AnonFixed Type", "decimal", fx.getType().getLocalPart()); } else if (type instanceof Struct) { Struct struct = (Struct)type; String[] testResult; if ("X.op_a".equals(struct.getName())) { testResult = new String[]{"X.op_a", "X.op_a", "p1", "X.S", "p2", "X.S"}; } else if ("X.op_aResult".equals(struct.getName())) { testResult = new String[]{"X.op_aResult", "X.op_aResult", "return", "X.S", "p2", "X.S"}; } else { testResult = new String[]{"X.S", "X.S", "str", "X._1_S", "fx", "X._2_S"}; } assertEquals("Name is incorrect for Anon Array Type", testResult[0], struct.getName()); assertEquals("Type is incorrect for Struct Type", testResult[1], struct.getType().getLocalPart()); assertEquals("Name for first Struct Member Type is incorrect", testResult[2], struct.getMember().get(0).getName()); assertEquals("Idltype for first Struct Member Type is incorrect", testResult[3], struct.getMember().get(0).getIdltype().getLocalPart()); assertEquals("Name for second Struct Member Type is incorrect", testResult[4], struct.getMember().get(1).getName()); assertEquals("Idltype for second Struct Member Type is incorrect", testResult[5], struct.getMember().get(1).getIdltype().getLocalPart()); } else { //System.err.println("Type: " + i + " " + type.getClass().getName()); } } File f = new File("atype.idl"); assertTrue("atype.idl should be generated", f.exists()); } finally { new File("atype.idl").deleteOnExit(); } } // tests anonymous arrays and sequences @Test public void testAnonType() throws Exception { try { String fileName = getClass().getResource("/wsdl/atype.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("X"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(3, typemap.getElementsByTagName("corba:anonsequence").getLength()); assertEquals(2, typemap.getElementsByTagName("corba:anonarray").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:array").getLength()); assertEquals(2, typemap.getElementsByTagName("corba:struct").getLength()); TypeMappingType mapType = (TypeMappingType)model.getExtensibilityElements().get(0); Map<String, CorbaType> tmap = new HashMap<>(); for (CorbaType type : mapType.getStructOrExceptionOrUnion()) { tmap.put(type.getName(), type); } WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("XCORBABinding"); idlgen.setOutputFile("atype.idl"); idlgen.generateIDL(model); Array arr = (Array)tmap.get("X.A"); assertNotNull(arr); assertEquals("ElementType is incorrect for Array Type", "X._5_A", arr.getElemtype().getLocalPart()); Anonarray arr2 = (Anonarray)tmap.get("X._5_A"); assertNotNull(arr2); assertEquals("ElementType is incorrect for Anon Array Type", "X._4_A", arr2.getElemtype().getLocalPart()); Anonarray arr3 = (Anonarray)tmap.get("X._4_A"); assertNotNull(arr3); assertEquals("ElementType is incorrect for Anon Array Type", "X._1_A", arr3.getElemtype().getLocalPart()); Anonsequence seq = (Anonsequence)tmap.get("X._1_A"); assertNotNull(seq); assertEquals("ElementType is incorrect for Anon Sequence Type", "X._2_A", seq.getElemtype().getLocalPart()); Anonsequence seq2 = (Anonsequence)tmap.get("X._2_A"); assertNotNull(seq2); assertEquals("ElementType is incorrect for Anon Sequence Type", "X._3_A", seq2.getElemtype().getLocalPart()); Anonsequence seq3 = (Anonsequence)tmap.get("X._3_A"); assertNotNull(seq3); assertEquals("ElementType is incorrect for Anon Sequence Type", "long", seq3.getElemtype().getLocalPart()); File f = new File("atype.idl"); assertTrue("atype.idl should be generated", f.exists()); } finally { new File("atype.idl").deleteOnExit(); } } @Test public void testAnyType() throws Exception { try { String fileName = getClass().getResource("/wsdl/any.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("anyInterface"); Definition model = generator.generateCORBABinding(); TypeMappingType mapType = (TypeMappingType)model.getExtensibilityElements().get(0); assertEquals(5, mapType.getStructOrExceptionOrUnion().size()); int strcnt = 0; int unioncnt = 0; for (CorbaType corbaType : mapType.getStructOrExceptionOrUnion()) { if (corbaType instanceof Struct) { strcnt++; } if (corbaType instanceof Union) { unioncnt++; } } assertNotNull(mapType); assertEquals(3, strcnt); assertEquals(2, unioncnt); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("anyInterfaceCORBABinding"); idlgen.setOutputFile("any.idl"); idlgen.generateIDL(model); File f = new File("any.idl"); assertTrue("any.idl should be generated", f.exists()); } finally { new File("any.idl").deleteOnExit(); } } @Test public void testMultipleBindings() throws Exception { String fileName = getClass().getResource("/wsdl/multiplePortTypes.wsdl").toString(); generator.setWsdlFile(fileName); generator.setAllBindings(true); Definition model = generator.generateCORBABinding(); assertEquals("All bindings should be generated.", 2, model.getAllBindings().size()); } @Test public void testAnonymousReturnParam() throws Exception { try { String fileName = getClass().getResource("/wsdl/factory_pattern.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("Number"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(3, typemap.getElementsByTagName("corba:struct").getLength()); } finally { new File("factory_pattern-corba.wsdl").deleteOnExit(); } } @Test public void testComplextypeDerivedSimpletype() throws Exception { try { String fileName = getClass().getResource("/wsdl/complex_types.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("TypeTestPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(8, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:fixed").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:array").getLength()); assertEquals(5, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(3, typemap.getElementsByTagName("corba:sequence").getLength()); } finally { new File("complex_types-corba.wsdl").deleteOnExit(); } } @Test public void testCorbaExceptionComplextype() throws Exception { try { String fileName = getClass().getResource("/wsdl/databaseService.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("Database"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(2, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:exception").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:anonsequence").getLength()); } finally { new File("databaseService-corba.wsdl").deleteOnExit(); } } @Test public void testSetCorbaAddress() throws Exception { try { String fileName = getClass().getResource("/wsdl/datetime.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("BasePortType"); Definition model = generator.generateCORBABinding(); QName name = new QName("http://schemas.apache.org/idl/datetime.idl", "BaseCORBAService", "tns"); Service service = model.getService(name); Port port = service.getPort("BaseCORBAPort"); AddressType addressType = (AddressType)port.getExtensibilityElements().get(0); String address = addressType.getLocation(); assertEquals("file:./Base.ref", address); generator.setAddress("corbaloc::localhost:40000/hw"); model = generator.generateCORBABinding(); service = model.getService(name); port = service.getPort("BaseCORBAPort"); addressType = (AddressType)port.getExtensibilityElements().get(0); address = addressType.getLocation(); assertEquals("corbaloc::localhost:40000/hw", address); } finally { new File("datetime-corba.wsdl").deleteOnExit(); } } @Test public void testSetCorbaAddressFile() throws Exception { try { URI fileName = getClass().getResource("/wsdl/datetime.wsdl").toURI(); generator.setWsdlFile(new File(fileName).getAbsolutePath()); generator.addInterfaceName("BasePortType"); Definition model = generator.generateCORBABinding(); QName name = new QName("http://schemas.apache.org/idl/datetime.idl", "BaseCORBAService", "tns"); Service service = model.getService(name); Port port = service.getPort("BaseCORBAPort"); AddressType addressType = (AddressType)port.getExtensibilityElements().get(0); String address = addressType.getLocation(); assertEquals("file:./Base.ref", address); URL idl = getClass().getResource("/wsdl/addressfile.txt"); String filename = new File(idl.toURI()).getAbsolutePath(); generator.setAddressFile(filename); model = generator.generateCORBABinding(); service = model.getService(name); port = service.getPort("BaseCORBAPort"); addressType = (AddressType)port.getExtensibilityElements().get(0); address = addressType.getLocation(); assertEquals("corbaloc::localhost:60000/hw", address); } finally { new File("datetime-corba.wsdl").deleteOnExit(); } } @Test public void testRestrictedStruct() throws Exception { try { URI fileName = getClass().getResource("/wsdl/restrictedStruct.wsdl").toURI(); generator.setWsdlFile(new File(fileName).getAbsolutePath()); generator.addInterfaceName("TypeTestPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(7, typemap.getElementsByTagName("corba:struct").getLength()); assertEquals(3, typemap.getElementsByTagName("corba:union").getLength()); } finally { new File("restrictedStruct-corba.wsdl").deleteOnExit(); } } @Test public void testComplexRestriction() throws Exception { try { URI fileName = getClass().getResource("/wsdl/complexRestriction.wsdl").toURI(); generator.setWsdlFile(new File(fileName).getAbsolutePath()); generator.addInterfaceName("TypeTestPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:struct").getLength()); } finally { new File("complexRestriction-corba.wsdl").deleteOnExit(); } } @Test public void testListType() throws Exception { try { URI fileName = getClass().getResource("/wsdl/listType.wsdl").toURI(); generator.setWsdlFile(new File(fileName).getAbsolutePath()); generator.addInterfaceName("TypeTestPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:enum").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:sequence").getLength()); } finally { new File("listType-corba.wsdl").deleteOnExit(); } } @Test public void testImportSchemaInTypes() throws Exception { try { URI fileName = getClass().getResource("/wsdl/importType.wsdl").toURI(); generator.setWsdlFile(new File(fileName).getAbsolutePath()); generator.addInterfaceName("TypeTestPortType"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:enum").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:sequence").getLength()); } finally { new File("importType-corba.wsdl").deleteOnExit(); } } }
42.620393
105
0.609748
a13898b13a742893ccdb97b922d0090ad406f0c5
2,939
/* * ====================================================================== * PrintViewOperationsVisitor.java: Visit components and retrieve a * summary of performance and cost of system operations .. * * Modified by: Mark Austin June, 2012 * ====================================================================== */ package view; import model.*; public class PrintViewOperationsVisitor implements FeatureElementVisitor { String s = ""; private double totalPrice; private double totalPerformance; private boolean headingPrinted = false; public void visit( AbstractCompoundFeature compound ) { print ( (AbstractCompoundFeature) compound ); } public void visit( AbstractFeature feature ) {} public void visit( CompositeHierarchy composite ) {} public void start( CompositeHierarchy composite ) { // Print heading for the first time .... if ( headingPrinted == false ) { String s1 = String.format("------------------------------ \n" ); String s2 = String.format("Summary of Building Operations \n" ); String s3 = String.format("------------------------------ \n" ); String s4 = String.format("\n" ); s = s + s1 + s2 + s3 + s4; } // Reset heading flag ... headingPrinted = true; } public void finish( CompositeHierarchy composite ) {} // Assemble details of component operations ..... public void print( AbstractCompoundFeature af ) { totalPrice += af.getPrice(); totalPerformance += af.getPerformance(); // String representation of feature and price ... String s1 = String.format("Item: %17s : cost = %7.2f performance = %5.2f\n", af.getName(), af.getPrice(), af.getPerformance() ); s = s + s1; } // ================================================ // Set summary .... // ================================================ public void setSummary() { String s1 = String.format("\n" ); String s2 = String.format("-------------------------------------\n" ); String s3 = String.format("Total Cost = %7.2f \n", getTotalPrice() ); String s4 = String.format("Total Performance = %7.2f \n", getTotalPerformance() ); String s5 = String.format("-------------------------------------\n" ); s = s + s1 + s2 + s3 + s4 + s5; } // ================================================ // Retrieve text string of total cost .... // ================================================ public String getText() { return s; } // ================================================ // Return the internal state .... // ================================================ public double getTotalPrice() { return totalPrice; } public double getTotalPerformance() { return totalPerformance; } }
31.945652
88
0.474651
a23bbb24f25e15d3428db096d217f8d06b10ede8
1,562
package ch.uzh.ifi.hase.soprafs21.GameEntities.Movement; import ch.uzh.ifi.hase.soprafs21.GameEntities.Players.Player; import ch.uzh.ifi.hase.soprafs21.GameEntities.TicketWallet.Ticket; import ch.uzh.ifi.hase.soprafs21.network.Station; import javax.persistence.*; @Entity @Table(name = "MOVE") public class Move { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long moveId; @ManyToOne @JoinColumn(name = "roundId") private Round round; @OneToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "playerId") private Player player; @ManyToOne @JoinColumn(name = "From_stationId") private Station from; @ManyToOne @JoinColumn(name = "to_stationId") private Station to; private Ticket ticket; public void setMoveId(Long moveId) { this.moveId = moveId; } public void setRound(Round round) { this.round = round; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public Station getFrom() { return this.from; } public void setFrom(Station from) { this.from = from; } public Station getTo() { return to; } public void setTo(Station to) { this.to = to; } public Ticket getTicket() { return ticket; } public void setTicket(Ticket ticket) { this.ticket = ticket; } public void executeMove(){ this.player.setCurrentStation(this.to); } }
19.772152
66
0.637644
6bc3399b71bbf58e07e18d410ecc9c25421b6755
17,744
package controllers.publix; import daos.common.ComponentResultDao; import daos.common.StudyResultDao; import exceptions.publix.ForbiddenNonLinearFlowException; import exceptions.publix.ForbiddenReloadException; import exceptions.publix.PublixException; import general.common.Common; import general.common.StudyLogger; import models.common.*; import models.common.ComponentResult.ComponentState; import models.common.StudyResult.StudyState; import models.common.workers.Worker; import play.Logger; import play.Logger.ALogger; import play.db.jpa.JPAApi; import play.mvc.Controller; import play.mvc.Http.MultipartFormData; import play.mvc.Result; import scala.Option; import services.publix.PublixErrorMessages; import services.publix.PublixHelpers; import services.publix.PublixUtils; import services.publix.StudyAuthorisation; import services.publix.idcookie.IdCookieModel; import services.publix.idcookie.IdCookieService; import utils.common.HttpUtils; import utils.common.IOUtils; import utils.common.JsonUtils; import javax.inject.Singleton; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.sql.Timestamp; import java.util.Date; import java.util.Optional; import static play.libs.Files.TemporaryFile; import static play.mvc.Http.Request; /** * Abstract controller class for all controllers that implement the IPublix * interface. It defines common methods and constants. * * @author Kristian Lange */ @Singleton public abstract class Publix<T extends Worker> extends Controller implements IPublix { private static final ALogger LOGGER = Logger.of(Publix.class); protected final JPAApi jpa; protected final PublixUtils<T> publixUtils; protected final StudyAuthorisation<T> studyAuthorisation; protected final GroupChannel<T> groupChannel; protected final IdCookieService idCookieService; protected final PublixErrorMessages errorMessages; protected final StudyAssets studyAssets; protected final JsonUtils jsonUtils; protected final ComponentResultDao componentResultDao; protected final StudyResultDao studyResultDao; protected final StudyLogger studyLogger; protected final IOUtils ioUtils; public Publix(JPAApi jpa, PublixUtils<T> publixUtils, StudyAuthorisation<T> studyAuthorisation, GroupChannel<T> groupChannel, IdCookieService idCookieService, PublixErrorMessages errorMessages, StudyAssets studyAssets, JsonUtils jsonUtils, ComponentResultDao componentResultDao, StudyResultDao studyResultDao, StudyLogger studyLogger, IOUtils ioUtils) { this.jpa = jpa; this.publixUtils = publixUtils; this.studyAuthorisation = studyAuthorisation; this.groupChannel = groupChannel; this.idCookieService = idCookieService; this.errorMessages = errorMessages; this.studyAssets = studyAssets; this.jsonUtils = jsonUtils; this.componentResultDao = componentResultDao; this.studyResultDao = studyResultDao; this.studyLogger = studyLogger; this.ioUtils = ioUtils; } @Override public Result startComponent(Long studyId, Long componentId, Long studyResultId, String message) throws PublixException { LOGGER.info(".startComponent: studyId " + studyId + ", " + "componentId " + componentId + ", " + "studyResultId " + studyResultId + ", " + "message '" + message + "'"); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); Component component = publixUtils.retrieveComponent(study, componentId); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); publixUtils.setPreStudyStateByComponentId(studyResult, study, componentId); ComponentResult componentResult; try { componentResult = publixUtils.startComponent(component, studyResult, message); } catch (ForbiddenReloadException | ForbiddenNonLinearFlowException e) { return redirect(controllers.publix.routes.PublixInterceptor .finishStudy(studyId, studyResult.getId(), false, e.getMessage())); } idCookieService.writeIdCookie(worker, batch, studyResult, componentResult); return studyAssets.retrieveComponentHtmlFile(study.getDirName(), component.getHtmlFilePath()).asJava(); } @Override public Result getInitData(Long studyId, Long componentId, Long studyResultId) throws PublixException, IOException { LOGGER.info(".getInitData: studyId " + studyId + ", " + "componentId " + componentId + ", " + "studyResultId " + studyResultId); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); Component component = publixUtils.retrieveComponent(study, componentId); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); publixUtils.checkComponentBelongsToStudy(study, component); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); ComponentResult componentResult; try { componentResult = publixUtils.retrieveStartedComponentResult(component, studyResult); } catch (ForbiddenReloadException | ForbiddenNonLinearFlowException e) { return redirect(controllers.publix.routes.PublixInterceptor .finishStudy(studyId, studyResult.getId(), false, e.getMessage())); } if (studyResult.getStudyState() != StudyState.PRE) { studyResult.setStudyState(StudyState.DATA_RETRIEVED); } studyResultDao.update(studyResult); componentResult.setComponentState(ComponentState.DATA_RETRIEVED); componentResultDao.update(componentResult); return ok(jsonUtils.initData(batch, studyResult, study, component)); } @Override public Result setStudySessionData(Long studyId, Long studyResultId) throws PublixException { LOGGER.info(".setStudySessionData: studyId " + studyId + ", " + "studyResultId " + studyResultId); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); String studySessionData = request().body().asText(); studyResult.setStudySessionData(studySessionData); studyResultDao.update(studyResult); return ok(" "); // jQuery.ajax cannot handle empty responses } @Override public Result heartbeat(Long studyId, Long studyResultId) throws PublixException { IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); studyResult.setLastSeenDate(new Timestamp(new Date().getTime())); studyResultDao.update(studyResult); return ok(" "); // jQuery.ajax cannot handle empty responses } @Override public Result submitResultData(Long studyId, Long componentId, Long studyResultId) throws PublixException { LOGGER.info(".submitResultData: studyId " + studyId + ", " + "componentId " + componentId + ", " + "studyResultId " + studyResultId); return submitOrAppendResultData(studyId, componentId, studyResultId, false); } @Override public Result appendResultData(Long studyId, Long componentId, Long studyResultId) throws PublixException { LOGGER.info(".appendResultData: studyId " + studyId + ", " + "componentId " + componentId + ", " + "studyResultId " + studyResultId); return submitOrAppendResultData(studyId, componentId, studyResultId, true); } private Result submitOrAppendResultData(Long studyId, Long componentId, Long studyResultId, boolean append) throws PublixException { IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); Component component = publixUtils.retrieveComponent(study, componentId); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); publixUtils.checkComponentBelongsToStudy(study, component); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); Optional<ComponentResult> componentResult = publixUtils.retrieveCurrentComponentResult(studyResult); if (!componentResult.isPresent()) { String error = PublixErrorMessages.componentNeverStarted(studyId, componentId, "submitOrAppendResultData"); return redirect(routes.PublixInterceptor.finishStudy(studyId, studyResult.getId(), false, error)); } String postedResultData = request().body().asText(); String resultData; if (append) { String currentResultData = componentResult.get().getData(); resultData = currentResultData != null ? currentResultData + postedResultData : postedResultData; } else { resultData = postedResultData; } componentResult.get().setData(resultData); componentResult.get().setComponentState(ComponentState.RESULTDATA_POSTED); componentResultDao.update(componentResult.get()); studyLogger.logResultDataStoring(componentResult.get()); return ok(" "); // jQuery.ajax cannot handle empty responses } @Override public Result uploadResultFile(Request request, Long studyId, Long componentId, Long studyResultId, String filename) throws PublixException { if (!Common.isResultUploadsEnabled()) return forbidden("File upload not allowed. Contact your admin."); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); Component component = publixUtils.retrieveComponent(study, componentId); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); publixUtils.checkComponentBelongsToStudy(study, component); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); Optional<ComponentResult> componentResult = publixUtils.retrieveCurrentComponentResult(studyResult); if (!componentResult.isPresent()) { String error = PublixErrorMessages.componentNeverStarted(studyId, componentId, "uploadResultFile"); return redirect(routes.PublixInterceptor.finishStudy(studyId, studyResult.getId(), false, error)); } MultipartFormData<TemporaryFile> body = request.body().asMultipartFormData(); MultipartFormData.FilePart<TemporaryFile> filePart = body.getFile("file"); if (filePart == null) return badRequest("Missing file"); TemporaryFile tmpFile = filePart.getRef(); try { if (filePart.getFileSize() > Common.getResultUploadsMaxFileSize()) { return badRequest("File size too large"); } if (ioUtils.getResultUploadDirSize(studyResultId) > Common.getResultUploadsLimitPerStudyRun()) { return badRequest("Reached max file size limit per study run"); } if (!IOUtils.checkFilename(filename)) { return badRequest("Bad filename"); } Path destFile = ioUtils.getResultUploadFileSecurely( studyResultId, componentResult.get().getId(), filename).toPath(); tmpFile.moveFileTo(destFile, true); studyLogger.logResultUploading(destFile, componentResult.get()); } catch (IOException e) { return badRequest("File upload failed"); } return ok("File uploaded"); } @Override public Result downloadResultFile(Long studyId, Long studyResultId, String filename, Optional<Long> componentId) throws PublixException { IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); Component component = null; if (componentId.isPresent()) { component = publixUtils.retrieveComponent(study, componentId.get()); publixUtils.checkComponentBelongsToStudy(study, component); } StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); Optional<File> file = publixUtils.retrieveLastUploadedResultFile(studyResult, component, filename); return file.isPresent() ? ok(file.get(), false) : notFound("Result file not found: " + filename); } @Override public Result abortStudy(Long studyId, Long studyResultId, String message) throws PublixException { LOGGER.info(".abortStudy: studyId " + studyId + ", " + ", " + "studyResultId " + studyResultId + ", " + "message '" + message + "'"); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); if (!PublixHelpers.studyDone(studyResult)) { publixUtils.abortStudy(message, studyResult); groupChannel.closeGroupChannelAndLeaveGroup(studyResult); } idCookieService.discardIdCookie(studyResult.getId()); studyLogger.log(study, "Aborted study run", worker); if (HttpUtils.isAjax()) { return ok(" "); // jQuery.ajax cannot handle empty responses } else { return ok(views.html.publix.abort.render()); } } @Override public Result finishStudy(Long studyId, Long studyResultId, Boolean successful, String message) throws PublixException { LOGGER.info(".finishStudy: studyId " + studyId + ", " + "studyResultId " + studyResultId + ", " + "successful " + successful + ", " + "message '" + message + "'"); IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); StudyResult studyResult = publixUtils.retrieveStudyResult(worker, study, studyResultId); if (!PublixHelpers.studyDone(studyResult)) { publixUtils.finishStudyResult(successful, message, studyResult); groupChannel.closeGroupChannelAndLeaveGroup(studyResult); } idCookieService.discardIdCookie(studyResult.getId()); studyLogger.log(study, "Finished study run", worker); if (HttpUtils.isAjax()) { return ok(" "); // jQuery.ajax cannot handle empty responses } else { if (!successful) { return ok(views.html.publix.error.render(message)); } else { return redirect(routes.StudyAssets.endPage(studyId, Option.empty())); } } } @Override public Result log(Long studyId, Long componentId, Long studyResultId) throws PublixException { IdCookieModel idCookie = idCookieService.getIdCookie(studyResultId); Study study = publixUtils.retrieveStudy(studyId); Batch batch = publixUtils.retrieveBatch(idCookie.getBatchId()); T worker = publixUtils.retrieveTypedWorker(idCookie.getWorkerId()); studyAuthorisation.checkWorkerAllowedToDoStudy(worker, study, batch); String msg = request().body().asText().replaceAll("\\R+", " ").replaceAll("\\s+"," "); LOGGER.info("logging from client: study ID " + studyId + ", component ID " + componentId + ", worker ID " + worker.getId() + ", study result ID " + studyResultId + ", message '" + msg + "'."); return ok(" "); // jQuery.ajax cannot handle empty responses } }
49.983099
120
0.699842
3aca9008a7dcceda1388ce2b96ee6b77c4122384
6,581
package com.wepay.zktools.zookeeper; import com.wepay.zktools.zookeeper.internal.ZooKeeperClientImpl; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.io.Closeable; import java.util.List; import java.util.Set; import java.util.function.Consumer; /** * ZooKeeper client wrapper */ public interface ZooKeeperClient extends Closeable { static ZooKeeperClient create(String connectString, int sessionTimeout) throws ZooKeeperClientException { return new ZooKeeperClientImpl(connectString, sessionTimeout); } /** * Adds auth info to the zookeeper session * @param scheme * @param auth */ void addAuthInfo(String scheme, byte[] auth); /** * Sets a handler that is invoked when a session is connected. * @param handler * @return a watcher handle */ WatcherHandle onConnected(Handlers.OnConnected handler); /** * Sets a handler that is invoked when a session is disconnected. * @param handler * @return a watcher handle */ WatcherHandle onDisconnected(Handlers.OnDisconnected handler); /** * Sets a handler that is invoked when a zookeeper server is unreachable. * @param handler * @return a watcher handle */ WatcherHandle onConnectFailed(Handlers.OnConnectFailed handler); /** * Sets a handler that is invoked when a session is expired. * @param handler * @return a watcher handle */ WatcherHandle onSessionExpired(Handlers.OnSessionExpired handler); /** * Returns the current session {@link ZooKeeperSession}. * @return the current session {@link ZooKeeperSession} * @throws ZooKeeperClientException */ ZooKeeperSession session() throws ZooKeeperClientException; /** * Sets a handler that is invoked when the specified znode is changed. * @param znode * @param onNodeChanged * @param nodeSerializer * @param <T> Class of znode data * @return a watcher handle */ <T> WatcherHandle watch(ZNode znode, Handlers.OnNodeChanged<T> onNodeChanged, Serializer<T> nodeSerializer); /** * Sets a handler that is invoked when the specified znode is changed. * @param znode * @param onNodeChanged * @param nodeSerializer * @param removeOnDelete * @param <T> Class of znode data * @return a watcher handle */ <T> WatcherHandle watch(ZNode znode, Handlers.OnNodeChanged<T> onNodeChanged, Serializer<T> nodeSerializer, boolean removeOnDelete); /** * Sets a handler that is invoked when the specified znode is changed or its child is created/changed/deleted. * @param znode * @param onNodeOrChildChanged * @param nodeSerializer * @param childSerializer * @param <P> Class of znode data * @param <C> Class of child znode data * @return a watcher handle */ <P, C> WatcherHandle watch(ZNode znode, Handlers.OnNodeOrChildChanged<P, C> onNodeOrChildChanged, Serializer<P> nodeSerializer, Serializer<C> childSerializer); /** * Sets a handler that is invoked when the specified znode is changed or its child is created/changed/deleted. * @param znode * @param onNodeOrChildChanged * @param nodeSerializer * @param childSerializer * @param removeOnDelete * @param <P> Class of znode data * @param <C> Class of child znode data * @return a watcher handle */ <P, C> WatcherHandle watch(ZNode znode, Handlers.OnNodeOrChildChanged<P, C> onNodeOrChildChanged, Serializer<P> nodeSerializer, Serializer<C> childSerializer, boolean removeOnDelete); /** * Closes this client. */ void close(); ZNode createPath(ZNode znode) throws KeeperException, ZooKeeperClientException; ZNode createPath(ZNode znode, List<ACL> acl) throws KeeperException, ZooKeeperClientException; ZNode create(ZNode znode, CreateMode createMode) throws KeeperException, ZooKeeperClientException; ZNode create(ZNode znode, List<ACL> acl, CreateMode createMode) throws KeeperException, ZooKeeperClientException; <T> ZNode create(ZNode znode, T data, Serializer<T> serializer, CreateMode createMode) throws KeeperException, ZooKeeperClientException; <T> ZNode create(ZNode znode, T data, Serializer<T> serializer, List<ACL> acl, CreateMode createMode) throws KeeperException, ZooKeeperClientException; Stat exists(ZNode znode) throws KeeperException, ZooKeeperClientException; Set<ZNode> getChildren(ZNode znode) throws KeeperException, ZooKeeperClientException; <T> NodeData<T> getData(ZNode znode, Serializer<T> serializer) throws KeeperException, ZooKeeperClientException; <T> void setData(ZNode znode, T data, Serializer<T> serializer) throws KeeperException, ZooKeeperClientException; <T> void setData(ZNode znode, T data, Serializer<T> serializer, int version) throws KeeperException, ZooKeeperClientException; void delete(ZNode znode) throws KeeperException, ZooKeeperClientException; void delete(ZNode znode, int version) throws KeeperException, ZooKeeperClientException; void deleteRecursively(ZNode znode) throws KeeperException, ZooKeeperClientException; NodeACL getACL(ZNode znode) throws KeeperException, ZooKeeperClientException; Stat setACL(ZNode znode, List<ACL> acl, int version) throws KeeperException, ZooKeeperClientException; String getConnectString(); int getSessionTimeout(); /** * Executes an action mutually exclusive way. Locking (or synchronization) is done on the ephemeral node * designated by {@code lockNode}. {@code action} is an instance of {@link Consumer} that takes an instance of * {@link ZooKeeperSession}. All access to ZooKeeper from the {@code action} should use the {@code ZooKeeperSession} instance passed in. * @param lockNode znode to synchronize on * @param action a block of code executed mutually exclusive way. * @param <E> Class of the action specific exception * @throws E action specific exception * @throws KeeperException * @throws ZooKeeperClientException */ <E extends Exception> void mutex(ZNode lockNode, MutexAction<E> action) throws E, KeeperException, ZooKeeperClientException; }
38.261628
155
0.701717
4185c265a9ddfe041da8422d13a800b1a390ee36
1,117
package osp.leobert.utils.mocker.notation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * <p><b>Package:</b> osp.leobert.utils.mocker.notation </p> * <p><b>Project:</b> Mocker </p> * <p><b>Classname:</b> MockIntDef </p> * Created by leobert on 2020/11/19. */ @Retention(RUNTIME) @Target({ANNOTATION_TYPE}) public @interface MockCharDef { /** * Defines the allowed constants for this element */ char[] value() default {}; /** * Defines whether the constants can be used as a flag, or just as an enum (the default) */ boolean flag() default false; /** * Whether any other values are allowed. Normally this is * not the case, but this allows you to specify a set of * expected constants, which helps code completion in the IDE * and documentation generation and so on, but without * flagging compilation warnings if other values are specified. */ boolean open() default false; }
31.027778
92
0.692927
a99fde3781481d881814ebdf3e9395e77711a742
2,785
package tech.pcloud.configure.center.server.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import tecp.pcloud.configure.center.core.model.po.Profile; import tecp.pcloud.configure.center.core.model.po.Role; import tecp.pcloud.configure.center.core.model.rest.RestResult; import tecp.pcloud.configure.center.core.model.vo.ProfileInfo; import tecp.pcloud.configure.center.core.model.vo.RoleInfo; import tecp.pcloud.configure.center.core.model.vo.request.SearchPeametersRequest; import tecp.pcloud.configure.center.core.model.vo.request.parameter.NameSearchParameters; import tecp.pcloud.configure.center.core.model.vo.response.DataRowsResponse; import tecp.pcloud.configure.center.core.model.vo.response.OptionResponse; import tecp.pcloud.configure.center.core.service.ProfileManager; import tecp.pcloud.configure.center.core.service.RoleManager; import java.util.List; /** * @ClassName ProfileController * @Author pandong * @Date 2018/9/28 22:40 **/ @CrossOrigin("*") @RestController @RequestMapping("/data/profile") public class ProfileController extends AppController { @Autowired private ProfileManager profileManager; @RequestMapping(value = "/{profileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult<ProfileInfo> load(final @PathVariable("profileId") long profileId) { return success(profileManager.load(profileId)); } @RequestMapping(value = "/page", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult<DataRowsResponse> page(final @RequestBody SearchPeametersRequest<NameSearchParameters> request) { return success(profileManager.select(request)); } @RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult<List<OptionResponse>> all() { return success(profileManager.allActive()); } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult insert(final @RequestBody Profile profile) { profileManager.insert(profile); return success(); } @RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult update(final @RequestBody Profile profile) { profileManager.update(profile); return success(); } @RequestMapping(value = "/{profileId}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) public RestResult delete(final @PathVariable("profileId") long profileId) { profileManager.delete(profileId); return success(); } }
42.846154
119
0.770557
4bafdecc229ce36a99255c630e8369d3d2c83de9
1,019
package com.mcxiv.logger.formatted; import com.mcxiv.logger.util.ByteConsumer; import com.mcxiv.logger.util.StringsConsumer; import java.io.OutputStream; import java.io.PrintStream; abstract class Logger_StreamDependencyAdder extends Logger_LevelDependencyAdder { protected StringsConsumer writer; public Logger_StreamDependencyAdder(OutputStream stream) { super(); final PrintStream sw = new PrintStream(stream); writer = st -> { for (String s : st) sw.print(s); }; } public Logger_StreamDependencyAdder() { super(); writer = st -> { for (String s : st) System.out.print(s); }; } public Logger_StreamDependencyAdder(ByteConsumer consumer) { super(); writer = sts -> { for (String st : sts) for (byte b : st.getBytes()) consumer.consume(b); }; } public Logger_StreamDependencyAdder(StringsConsumer consumer) { super(); writer = consumer; } }
24.853659
83
0.633955
c4ce42a823f13a1502f3a2faa74190e5b114a176
1,976
package com.louis.kitty.dbms.service; import java.util.List; import java.util.Map; import com.louis.kitty.dbms.exception.DAOException; import com.louis.kitty.dbms.model.Column; import com.louis.kitty.dbms.model.ForeignKey; import com.louis.kitty.dbms.model.Index; import com.louis.kitty.dbms.model.PrimaryKey; import com.louis.kitty.dbms.model.Table; import com.louis.kitty.dbms.model.Trigger; import com.louis.kitty.dbms.vo.ConnParam; /** * 数据库元信息查询服务 * @author Louis * @date Nov 10, 2018 */ public interface DatabaseService { /** * 通用查询方法 * @param connParam 连接参数 * @param sql 要查询的sql语句 * @param params 查询条件数组 * @return * @throws DAOException */ List<Map<String, String>> query(ConnParam connParam, String sql, String[] params); /** * 查询表集合 * @param connParam 连接参数 * @return * @throws DAOException */ List<Table> getTables(ConnParam connParam); /** * 查询表的字段集 * @param connParam 连接参数 * @param tableName * @return * @throws DAOException */ List<Column> getColumns(ConnParam connParam, String tableName); /** * 查询主键集 * @param connParam 连接参数 * @param tableName * @return * @throws DAOException */ List<PrimaryKey> getPrimaryKeys(ConnParam connParam, String tableName); /** * 查询外键集 * @param connParam 连接参数 * @param tableName * @return * @throws DAOException */ List<ForeignKey> getForeignKeys(ConnParam connParam, String tableName); /** * 查询索引集 * @param connParam 连接参数 * @return * @throws DAOException */ List<Index> getIndexes(ConnParam connParam, String tableName); /** * 查询触发器集 * @param connParam 连接参数 * @param tableName * @return * @throws DAOExeception */ List<Trigger> getTriggers(ConnParam connParam, String tableName); /** * 测试数据库是否可以连接 * @param connParam * @return */ boolean canConnect(ConnParam connParam); }
21.247312
83
0.652834
2f7e42af41468418e6c9c8c0a8308c3026637f5d
3,309
/* * Copyright 2015-2016 OpenCB * * 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.opencb.commons.io.avro; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumWriter; import org.opencb.commons.ProgressLogger; import org.opencb.commons.io.DataWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.List; /** * Created on 09/11/15. * * @author Jacobo Coll &lt;[email protected]&gt; */ public class AvroDataWriter<T extends GenericRecord> implements DataWriter<T> { private Path outputPath; private boolean gzip; private DataFileWriter<T> avroWriter; private Schema schema; private ProgressLogger progressLogger; protected Logger logger = LoggerFactory.getLogger(this.getClass().toString()); public AvroDataWriter(Path outputPath, boolean gzip, Schema schema) { this.outputPath = outputPath; this.gzip = gzip; this.schema = schema; } public AvroDataWriter setProgressLogger(ProgressLogger progressLogger) { this.progressLogger = progressLogger; return this; } @Override public boolean open() { /** Open output stream **/ try { DatumWriter<T> datumWriter = new SpecificDatumWriter<>(); avroWriter = new DataFileWriter<>(datumWriter); avroWriter.setCodec(gzip ? CodecFactory.deflateCodec(CodecFactory.DEFAULT_DEFLATE_LEVEL) : CodecFactory.nullCodec()); avroWriter.create(schema, outputPath.toFile()); } catch (IOException e) { throw new UncheckedIOException(e); } return true; } @Override public boolean write(List<T> batch) { T last = null; try { for (T t : batch) { last = t; avroWriter.append(t); } logProgress(batch); } catch (IOException e) { logger.error("last element : " + last, e); throw new UncheckedIOException(e); } catch (RuntimeException e) { logger.error("last element : " + last, e); throw e; } return true; } protected void logProgress(List<T> batch) { if (progressLogger != null) { progressLogger.increment(batch.size()); } } @Override public boolean close() { try { avroWriter.close(); } catch (IOException e) { throw new UncheckedIOException(e); } return true; } }
29.810811
129
0.651859
efa182f77e60b60e698d28a80a5bfd8a167fa376
476
package com.moxi.hyblog.admin.annotion.AvoidRepeatableCommit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 避免重复提交 * */ /** * @author hzh * @since 2020-08-07 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AvoidRepeatableCommit { /** * 指定时间内不可重复提交,单位毫秒,默认1秒 */ long timeout() default 1000; }
19.833333
61
0.735294
87d0eba050c1fdcd8321aaead863013526b0aa5b
11,248
package com.lotaris.jee.validation.preprocessing; import com.lotaris.jee.validation.preprocessing.IPreprocessingConfig; import com.lotaris.jee.validation.preprocessing.IPreprocessor; import com.lotaris.jee.validation.preprocessing.ApiPreprocessingContext; import com.lotaris.jee.test.utils.PreprossessingAnswers; import com.lotaris.jee.validation.ApiErrorsException; import com.lotaris.jee.validation.IErrorCode; import com.lotaris.jee.validation.IValidator; import com.lotaris.rox.annotations.RoxableTest; import com.lotaris.rox.annotations.RoxableTestClass; import java.util.Arrays; import java.util.List; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static com.lotaris.jee.test.matchers.Matchers.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * @see ApiPreprocessingContext * @author Simon Oulevay ([email protected]) */ @RoxableTestClass(tags = {"preprocessing", "apiPreprocessingContext"}) public class ApiPreprocessingContextUnitTest { @Mock private IPreprocessor preprocessor; private ApiPreprocessingContext context; @Before public void setUp() { MockitoAnnotations.initMocks(this); context = createPreprocessingContext(); } @Test @RoxableTest(key = "b16890cc8750") public void apiPreprocessingContextShouldForwardProcessingToItsPreprocessor() throws ApiErrorsException { final Object objectToPreprocess = new Object(); when(preprocessor.process(anyObject(), any(IPreprocessingConfig.class))).thenReturn(true); assertThat(context.process(objectToPreprocess), isSuccessfulPreprocessingResult(true)); when(preprocessor.process(anyObject(), any(IPreprocessingConfig.class))).thenReturn(false); assertThat(createPreprocessingContext().process(objectToPreprocess), isSuccessfulPreprocessingResult(false)); } @Test @RoxableTest(key = "4b6d4b545765") public void apiPreprocessingContextShouldPassItselfToItsPreprocessorAsThePreprocessingContext() throws ApiErrorsException { when(preprocessor.process(anyObject(), any(IPreprocessingConfig.class))).thenReturn(true); context.process(new Object()); verify(preprocessor).process(anyObject(), same(context)); } @Test @RoxableTest(key = "4ff56a423d8a") public void apiPreprocessingContextShouldRegisterValidationGroups() { context.validateOnly(ValidationGroupA.class, ValidationGroupB.class); final Class[] validationGroups = context.getValidationGroups(); assertEquals(ValidationGroupA.class, validationGroups[0]); assertEquals(ValidationGroupB.class, validationGroups[1]); assertEquals(2, validationGroups.length); } @Test @RoxableTest(key = "3345ed6d8909") public void apiPreprocessingContextShouldRegisterValidators() { final List<IValidator> validators = Arrays.asList(mock(IValidator.class), mock(IValidator.class)); context.validateWith(validators.toArray(new IValidator[0])); assertEquals(validators, context.getValidators()); } @Test @RoxableTest(key = "f20db7f8fe85") public void apiPreprocessingContextShouldEnablePatchValidation() { assertFalse("Patch validation should not be enabled by default", context.isPatchValidationEnabled()); assertSame("#validatePatch should return the context itself", context, context.validatePatch()); assertTrue("Patch validation should be enabled after calling #validatePatch", context.isPatchValidationEnabled()); } @Test @RoxableTest(key = "992a5beffc99") public void apiPreprocessingContextShouldHaveAnEmptyUnprocessableEntityApiErrorResponseByDefault() { assertEquals(ApiPreprocessingContext.UNPROCESSABLE_ENTITY, context.getApiErrorResponse().getHttpStatusCode()); assertFalse(context.hasErrors()); assertFalse(context.getApiErrorResponse().hasErrors()); } @Test @RoxableTest(key = "50a577358551") public void apiPreprocessingContextShouldOnlyBeProcessableOnce() throws ApiErrorsException { when(preprocessor.process(anyObject(), any(IPreprocessingConfig.class))).thenReturn(true); assertThat(context.process(new Object()), isSuccessfulPreprocessingResult(true)); try { assertThat(context.process(new Object()), isSuccessfulPreprocessingResult(false)); fail("Expected an illegal state exception when trying to reuse context"); } catch (IllegalStateException ise) { // success } } @Test @RoxableTest(key = "b49215985574") public void apiPreprocessingContextShouldNotBeSuccessfulWhenUnprocessed() { try { context.isSuccessful(); fail("Context should have thrown an illegal state exception when trying to get the result before processing"); } catch (IllegalStateException ise) { // success } } @Test @RoxableTest(key = "e3e186c9ca32") public void apiPreprocessingContextShouldBuildValidationContextWithItsApiErrorResponseAsTheErrorCollector() { // check that the context has an API error response assertNotNull(context.getApiErrorResponse()); // add an error to the validation context context.getValidationContext().addError(null, null, errorCode(1), "foo"); // check that the error was added to the API error response through the validation context assertThat(context.getApiErrorResponse(), isApiErrorResponseObject(422).withError(1, null, "foo")); } @Test @RoxableTest(key = "da639176bb96") public void apiPreprocessingContextShouldThrowAnApiErrorsExceptionIfErrorsAreAddedToTheValidationContext() { // add an error during preprocessing doAnswer(new PreprossessingAnswers.PreprossessingWithErrorAnswer(errorCode(2), "foo")).when(preprocessor).process(anyObject(), same(context)); // make sure the exception is thrown try { context.process(new Object()); fail("Expected an API error exception to be thrown when errors are added to the validation context by the preprocessor; nothing was thrown"); } catch (ApiErrorsException aee) { assertThat(aee, isApiErrorsException(422).withError(2, null, "foo")); assertSame("Expected the API error response of the exception to be the internal API error response of the context", context.getApiErrorResponse(), aee.getErrorResponse()); } } @Test @RoxableTest(key = "2ed5d7cc5278") public void apiPreprocessingContextShouldNotThrowAnApiErrorsExceptionIfDisabled() { // add an error during preprocessing doAnswer(new PreprossessingAnswers.PreprossessingWithErrorAnswer(new IErrorCode() { @Override public int getCode() { return 10; } @Override public int getDefaultHttpStatusCode() { return 422; } }, "")).when(preprocessor).process(anyObject(), same(context)); // disable the exception and make sure it is not thrown try { assertThat(context.failOnErrors(false).process(new Object()), isSuccessfulPreprocessingResult(true)); } catch (ApiErrorsException aee) { fail("Expected API error exception to be disabled; it was thrown when errors are added to the validation context by the preprocessor"); } } @Test @RoxableTest(key = "6825a51caee9") public void apiPreprocessingContextShouldReturnCollectedErrors() throws ApiErrorsException { // add two errors during preprocessing doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((IPreprocessingConfig) invocation.getArguments()[1]).getValidationContext().addError(null, null, errorCode(1), "foo"); ((IPreprocessingConfig) invocation.getArguments()[1]).getValidationContext().addError(null, null, errorCode(2), "bar"); return true; } }).when(preprocessor).process(anyObject(), same(context)); final ApiPreprocessingContext result = context.failOnErrors(false).process(new Object()); assertThat(result, isSuccessfulPreprocessingResult(true)); assertTrue("Preprocessing result should indicate that errors were collected", result.hasErrors()); assertThat(result.getApiErrorResponse(), isApiErrorResponseObject(422).withError(1, null, "foo").withError(2, null, "bar")); } @Test @RoxableTest(key = "8834b48ef974") public void apiPreprocessingContextShouldReturnCollectedErrorsWhenThereAreNone() throws ApiErrorsException { when(preprocessor.process(anyObject(), any(IPreprocessingConfig.class))).thenReturn(true); final ApiPreprocessingContext result = context.failOnErrors(false).process(new Object()); assertThat(result, isSuccessfulPreprocessingResult(true)); assertFalse("Preprocessing result should indicate that no errors were collected", result.hasErrors()); assertThat(result.getApiErrorResponse(), isApiErrorResponseObject(422)); } @Test @RoxableTest(key = "311f9c8c7f61") public void apiPreprocessingContextShouldAddStateObjectsToTheValidationContext() { try { context.getValidationContext().getState(Object.class); fail("Expected IllegalArgumentException to be thrown when getting an unregistered state"); } catch (IllegalArgumentException iae) { } try { context.getValidationContext().getState(ArrayList.class); fail("Expected IllegalArgumentException to be thrown when getting an unregistered state"); } catch (IllegalArgumentException iae) { } try { context.getValidationContext().getState(Map.class); fail("Expected IllegalArgumentException to be thrown when getting an unregistered state"); } catch (IllegalArgumentException iae) { } final Object state1 = new Object(); context.withState(state1, Object.class); assertSame(state1, context.getValidationContext().getState(Object.class)); final List state2 = new ArrayList(); final Map state3 = new HashMap(); context.withStates(state2, state3); assertSame(state2, context.getValidationContext().getState(ArrayList.class)); assertSame(state3, context.getValidationContext().getState(HashMap.class)); } private IErrorCode errorCode(final int code) { return new IErrorCode() { @Override public int getCode() { return code; } @Override public int getDefaultHttpStatusCode() { return 422; } }; } private ApiPreprocessingContext createPreprocessingContext() { return new ApiPreprocessingContext(preprocessor); } private static Matcher<ApiPreprocessingContext> isSuccessfulPreprocessingResult(final boolean successful) { return new BaseMatcher<ApiPreprocessingContext>() { @Override public boolean matches(Object item) { final ApiPreprocessingContext result = (ApiPreprocessingContext) item; return result != null && result.isSuccessful() == successful; } @Override public void describeTo(Description description) { description.appendText(successful ? "successful preprocessing result" : "failed preprocessing result"); } @Override public void describeMismatch(Object item, Description description) { if (item == null) { description.appendText("preprocessing result is null"); } else { description.appendText(successful ? "preprocessing result is not successful" : "preprocessing result is successful"); } } }; } private static interface ValidationGroupA { } private static interface ValidationGroupB { } }
36.75817
144
0.778894
6bd0618904d4b5409da9911a070ee6c533873dad
27,605
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.file.meta; import alluxio.ProcessUtils; import alluxio.conf.PropertyKey; import alluxio.conf.ServerConfiguration; import alluxio.master.journal.JournalContext; import alluxio.master.journal.JournalUtils; import alluxio.master.journal.Journaled; import alluxio.master.journal.checkpoint.CheckpointInputStream; import alluxio.master.journal.checkpoint.CheckpointName; import alluxio.master.metastore.InodeStore; import alluxio.proto.journal.File.AsyncPersistRequestEntry; import alluxio.proto.journal.File.CompleteFileEntry; import alluxio.proto.journal.File.DeleteFileEntry; import alluxio.proto.journal.File.InodeDirectoryEntry; import alluxio.proto.journal.File.InodeFileEntry; import alluxio.proto.journal.File.InodeLastModificationTimeEntry; import alluxio.proto.journal.File.NewBlockEntry; import alluxio.proto.journal.File.PersistDirectoryEntry; import alluxio.proto.journal.File.RenameEntry; import alluxio.proto.journal.File.SetAclEntry; import alluxio.proto.journal.File.SetAttributeEntry; import alluxio.proto.journal.File.UpdateInodeDirectoryEntry; import alluxio.proto.journal.File.UpdateInodeEntry; import alluxio.proto.journal.File.UpdateInodeEntry.Builder; import alluxio.proto.journal.File.UpdateInodeFileEntry; import alluxio.proto.journal.Journal.JournalEntry; import alluxio.resource.CloseableIterator; import alluxio.resource.LockResource; import alluxio.security.authorization.AclEntry; import alluxio.security.authorization.DefaultAccessControlList; import alluxio.util.StreamUtils; import alluxio.util.proto.ProtoUtils; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Supplier; /** * Class for managing persistent inode tree state. * * This class owns all persistent inode tree state, and all inode tree modifications must go through * this class. To modify the inode tree, create a journal entry and call one of the applyAndJournal * methods. */ public class InodeTreePersistentState implements Journaled { private static final Logger LOG = LoggerFactory.getLogger(InodeTreePersistentState.class); private final InodeStore mInodeStore; private final InodeLockManager mInodeLockManager; /** * A set of inode ids representing pinned inode files. These are not part of the journaled state, * but this class keeps the set of pinned inodes up to date whenever the inode tree is modified. * * This class owns this set, and no other class can modify the set. */ private final PinnedInodeFileIds mPinnedInodeFileIds = new PinnedInodeFileIds(); /** A set of inode ids whose replication max value is non-default. */ private final ReplicationLimitedFileIds mReplicationLimitedFileIds = new ReplicationLimitedFileIds(); /** Counter for tracking how many inodes we have. */ private final InodeCounter mInodeCounter = new InodeCounter(); /** A set of inode ids whose persistence state is {@link PersistenceState#TO_BE_PERSISTED}. */ private final ToBePersistedFileIds mToBePersistedIds = new ToBePersistedFileIds(); /** * TTL bucket list. The list is owned by InodeTree, and is only shared with * InodeTreePersistentState so that the list can be updated whenever inode tree state changes. */ // TODO(andrew): Move ownership of the ttl bucket list to this class private final TtlBucketList mTtlBuckets; /** * @param inodeStore file store which holds inode metadata * @param lockManager manager for inode locks * @param ttlBucketList reference to the ttl bucket list so that the list can be updated when the * inode tree is modified */ public InodeTreePersistentState(InodeStore inodeStore, InodeLockManager lockManager, TtlBucketList ttlBucketList) { mInodeStore = inodeStore; mInodeLockManager = lockManager; mTtlBuckets = ttlBucketList; } /** * @return an unmodifiable view of the replication limited file ids */ public Set<Long> getReplicationLimitedFileIds() { return Collections.unmodifiableSet(mReplicationLimitedFileIds); } /** * @return the root of the inode tree */ public InodeDirectory getRoot() { return mInodeStore.get(0).map(Inode::asDirectory).orElse(null); } /** * @return the pinned inode file ids; */ public Set<Long> getPinnedInodeFileIds() { return Collections.unmodifiableSet(mPinnedInodeFileIds); } /** * @return the number of inodes in the tree */ public long getInodeCount() { return mInodeCounter.get(); } /** * @return an unmodifiable view of the files with persistence state * {@link PersistenceState#TO_BE_PERSISTED} */ public Set<Long> getToBePersistedIds() { return Collections.unmodifiableSet(mToBePersistedIds); } /** * Deletes an inode (may be either a file or directory). * * @param context journal context supplier * @param entry delete file entry */ public void applyAndJournal(Supplier<JournalContext> context, DeleteFileEntry entry) { // Unlike most entries, the delete file entry must be applied *before* making the in-memory // change. This is because delete file and create file are performed with only a read lock on // the parent directory. As soon as we do the in-memory-delete, another thread could re-create a // directory with the same name, and append a journal entry for the inode creation. This would // ruin journal replay because we would see two create file entries in a row for the same file // name. The opposite order is safe. We will never append the delete entry for a file before its // creation entry because delete requires a write lock on the deleted file, but the create // operation holds that lock until after it has appended to the journal. try { context.get().append(JournalEntry.newBuilder().setDeleteFile(entry).build()); applyDelete(entry); } catch (Throwable t) { // Delete entries should always apply cleanly, but if it somehow fails, we are in a state // where we've journaled the delete, but failed to make the in-memory update. We don't yet // have a way to recover from this, so we give a fatal error. ProcessUtils.fatalError(LOG, t, "Failed to apply entry %s", entry); } } /** * Allocates and returns the next block ID for the indicated inode. * * @param context journal context supplier * @param entry new block entry * @return the new block id */ public long applyAndJournal(Supplier<JournalContext> context, NewBlockEntry entry) { try { long id = applyNewBlock(entry); context.get().append(JournalEntry.newBuilder().setNewBlock(entry).build()); return id; } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Renames an inode. * * @param context journal context supplier * @param entry rename entry */ public void applyAndJournal(Supplier<JournalContext> context, RenameEntry entry) { try { applyRename(entry); context.get().append(JournalEntry.newBuilder().setRename(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Sets an ACL for an inode. * * @param context journal context supplier * @param entry set acl entry */ public void applyAndJournal(Supplier<JournalContext> context, SetAclEntry entry) { try { applySetAcl(entry); context.get().append(JournalEntry.newBuilder().setSetAcl(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Updates an inode's state. This is used for state common to both files and directories. * * @param context journal context supplier * @param entry update inode entry */ public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeEntry entry) { try { applyUpdateInode(entry); context.get().append(JournalEntry.newBuilder().setUpdateInode(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Updates an inode directory's state. * * @param context journal context supplier * @param entry update inode directory entry */ public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeDirectoryEntry entry) { try { applyUpdateInodeDirectory(entry); context.get().append(JournalEntry.newBuilder().setUpdateInodeDirectory(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Updates an inode file's state. * * @param context journal context supplier * @param entry update inode file entry */ public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeFileEntry entry) { try { applyUpdateInodeFile(entry); context.get().append(JournalEntry.newBuilder().setUpdateInodeFile(entry).build()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry); throw t; // fatalError will usually system.exit } } /** * Adds an inode to the inode tree. * * @param context journal context supplier * @param inode an inode to add and create a journal entry for * @param path path of the new inode */ public void applyAndJournal(Supplier<JournalContext> context, MutableInode<?> inode, String path) { try { applyCreateInode(inode); context.get().append(inode.toJournalEntry( Preconditions.checkNotNull(path))); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", inode); throw t; // fatalError will usually system.exit } } /** * Updates last access time for Inode without journaling. The caller should apply the journal * entry separately. * * @param inodeId the id of the target inode * @param accessTime the new value for last access time * @return the journal entry that represents the update */ public UpdateInodeEntry applyInodeAccessTime(long inodeId, long accessTime) { UpdateInodeEntry entry = UpdateInodeEntry.newBuilder().setId(inodeId) .setLastAccessTimeMs(accessTime).build(); applyUpdateInode(entry); return entry; } //// /// Apply Implementations. These methods are used for journal replay, so they are not allowed to /// fail. They are also used when making metadata changes during regular operation. //// private void applyDelete(DeleteFileEntry entry) { long id = entry.getId(); Inode inode = mInodeStore.get(id).get(); // The recursive option is only used by old versions. if (inode.isDirectory() && entry.getRecursive()) { Queue<InodeDirectory> dirsToDelete = new ArrayDeque<>(); dirsToDelete.add(inode.asDirectory()); while (!dirsToDelete.isEmpty()) { InodeDirectory dir = dirsToDelete.poll(); mInodeStore.removeInodeAndParentEdge(inode); mInodeCounter.decrementAndGet(); for (Inode child : mInodeStore.getChildren(dir)) { if (child.isDirectory()) { dirsToDelete.add(child.asDirectory()); } else { mInodeStore.removeInodeAndParentEdge(inode); mInodeCounter.decrementAndGet(); } } } } else { mInodeStore.removeInodeAndParentEdge(inode); mInodeCounter.decrementAndGet(); } updateTimestampsAndChildCount(inode.getParentId(), entry.getOpTimeMs(), -1); mPinnedInodeFileIds.remove(id); mReplicationLimitedFileIds.remove(id); mToBePersistedIds.remove(id); mTtlBuckets.remove(inode); } private void applyCreateDirectory(InodeDirectoryEntry entry) { applyCreateInode(MutableInodeDirectory.fromJournalEntry(entry)); } private void applyCreateFile(InodeFileEntry entry) { applyCreateInode(MutableInodeFile.fromJournalEntry(entry)); } private long applyNewBlock(NewBlockEntry entry) { MutableInodeFile inode = mInodeStore.getMutable(entry.getId()).get().asFile(); long newBlockId = inode.getNewBlockId(); mInodeStore.writeInode(inode); return newBlockId; } private void applySetAcl(SetAclEntry entry) { MutableInode<?> inode = mInodeStore.getMutable(entry.getId()).get(); List<AclEntry> entries = StreamUtils.map(ProtoUtils::fromProto, entry.getEntriesList()); switch (entry.getAction()) { case REPLACE: // fully replace the acl for the path inode.replaceAcl(entries); break; case MODIFY: inode.setAcl(entries); break; case REMOVE: inode.removeAcl(entries); break; case REMOVE_ALL: inode.removeExtendedAcl(); break; case REMOVE_DEFAULT: inode.setDefaultACL(new DefaultAccessControlList(inode.getACL())); break; default: LOG.warn("Unrecognized acl action: " + entry.getAction()); } mInodeStore.writeInode(inode); } private void applyUpdateInode(UpdateInodeEntry entry) { Optional<MutableInode<?>> inodeOpt = mInodeStore.getMutable(entry.getId()); if (!inodeOpt.isPresent()) { if (isJournalUpdateAsync(entry)) { // do not throw if the entry is journaled asynchronously return; } throw new IllegalStateException("Inode " + entry.getId() + " not found"); } MutableInode<?> inode = inodeOpt.get(); if (entry.hasTtl()) { // Remove before updating the inode. #remove relies on the inode having the same // TTL as when it was inserted. mTtlBuckets.remove(inode); } inode.updateFromEntry(entry); if (entry.hasTtl()) { mTtlBuckets.insert(Inode.wrap(inode)); } if (entry.hasPinned() && inode.isFile()) { if (entry.getPinned()) { MutableInodeFile file = inode.asFile(); List<String> mediaList = ServerConfiguration.getList( PropertyKey.MASTER_TIERED_STORE_GLOBAL_MEDIUMTYPE, ","); if (entry.getMediumTypeList().isEmpty()) { // if user does not specify a pinned media list, any location is OK file.setMediumTypes(new HashSet<>()); } else { for (String medium : entry.getMediumTypeList()) { if (mediaList.contains(medium)) { file.getMediumTypes().add(medium); } } } // when we pin a file with default min replication (zero), we bump the min replication // to one in addition to setting pinned flag, and adjust the max replication if it is // smaller than min replication. if (file.getReplicationMin() == 0) { file.setReplicationMin(1); if (file.getReplicationMax() == 0) { file.setReplicationMax(alluxio.Constants.REPLICATION_MAX_INFINITY); } } mPinnedInodeFileIds.add(entry.getId()); } else { // when we unpin a file, set the min replication to zero too. inode.asFile().setReplicationMin(0); mPinnedInodeFileIds.remove(entry.getId()); } } mInodeStore.writeInode(inode); updateToBePersistedIds(inode); } /** * @param entry the update inode journal entry to be checked * @return whether the journal entry might be applied asynchronously out of order */ private boolean isJournalUpdateAsync(UpdateInodeEntry entry) { return entry.getAllFields().size() == 2 && entry.hasId() && entry.hasLastAccessTimeMs(); } private void applyUpdateInodeDirectory(UpdateInodeDirectoryEntry entry) { MutableInode<?> inode = mInodeStore.getMutable(entry.getId()).get(); Preconditions.checkState(inode.isDirectory(), "Encountered non-directory id in update directory entry %s", entry); inode.asDirectory().updateFromEntry(entry); mInodeStore.writeInode(inode); } private void applyUpdateInodeFile(UpdateInodeFileEntry entry) { MutableInode<?> inode = mInodeStore.getMutable(entry.getId()).get(); Preconditions.checkState(inode.isFile(), "Encountered non-file id in update file entry %s", entry); if (entry.hasReplicationMax()) { if (entry.getReplicationMax() == alluxio.Constants.REPLICATION_MAX_INFINITY) { mReplicationLimitedFileIds.remove(inode.getId()); } else { mReplicationLimitedFileIds.add(inode.getId()); } } inode.asFile().updateFromEntry(entry); mInodeStore.writeInode(inode); } //// /// Deprecated Entries //// private void applyAsyncPersist(AsyncPersistRequestEntry entry) { applyUpdateInode(UpdateInodeEntry.newBuilder().setId(entry.getFileId()) .setPersistenceState(PersistenceState.TO_BE_PERSISTED.name()).build()); } private void applyCompleteFile(CompleteFileEntry entry) { applyUpdateInode(UpdateInodeEntry.newBuilder().setId(entry.getId()) .setLastModificationTimeMs(entry.getOpTimeMs()).setOverwriteModificationTime(true) .setUfsFingerprint(entry.getUfsFingerprint()).build()); applyUpdateInodeFile(UpdateInodeFileEntry.newBuilder().setId(entry.getId()) .setLength(entry.getLength()).addAllSetBlocks(entry.getBlockIdsList()).build()); } private void applyInodeLastModificationTime(InodeLastModificationTimeEntry entry) { // This entry is deprecated, use UpdateInode instead. applyUpdateInode(UpdateInodeEntry.newBuilder().setId(entry.getId()) .setLastModificationTimeMs(entry.getLastModificationTimeMs()).build()); } private void applyPersistDirectory(PersistDirectoryEntry entry) { // This entry is deprecated, use UpdateInode instead. applyUpdateInode(UpdateInodeEntry.newBuilder().setId(entry.getId()) .setPersistenceState(PersistenceState.PERSISTED.name()).build()); } private void applySetAttribute(SetAttributeEntry entry) { Builder builder = UpdateInodeEntry.newBuilder(); builder.setId(entry.getId()); if (entry.hasGroup()) { builder.setGroup(entry.getGroup()); } if (entry.hasOpTimeMs()) { builder.setLastModificationTimeMs(entry.getOpTimeMs()); } if (entry.hasOwner()) { builder.setOwner(entry.getOwner()); } if (entry.hasPermission()) { builder.setMode((short) entry.getPermission()); } if (entry.hasPersisted()) { if (entry.getPersisted()) { builder.setPersistenceState(PersistenceState.PERSISTED.name()); } else { builder.setPersistenceState(PersistenceState.NOT_PERSISTED.name()); } } if (entry.hasPinned()) { builder.setPinned(entry.getPinned()); } if (entry.hasTtl()) { builder.setTtl(entry.getTtl()); builder.setTtlAction(entry.getTtlAction()); } if (entry.hasUfsFingerprint()) { builder.setUfsFingerprint(entry.getUfsFingerprint()); } applyUpdateInode(builder.build()); } //// // Helper methods //// private void applyCreateInode(MutableInode<?> inode) { if (inode.isDirectory() && inode.getName().equals(InodeTree.ROOT_INODE_NAME)) { // This is the root inode. Clear all the state, and set the root. mInodeStore.clear(); mInodeStore.writeNewInode(inode); mInodeCounter.set(1); mPinnedInodeFileIds.clear(); mReplicationLimitedFileIds.clear(); mToBePersistedIds.clear(); updateToBePersistedIds(inode); return; } // inode should be added to the inode store before getting added to its parent list, because it // becomes visible at this point. mInodeStore.writeNewInode(inode); mInodeCounter.incrementAndGet(); mInodeStore.addChild(inode.getParentId(), inode); // Only update size, last modified time is updated separately. updateTimestampsAndChildCount(inode.getParentId(), Long.MIN_VALUE, 1); if (inode.isFile()) { MutableInodeFile file = inode.asFile(); if (file.getReplicationMin() > 0) { mPinnedInodeFileIds.add(file.getId()); file.setPinned(true); } if (file.getReplicationMax() != alluxio.Constants.REPLICATION_MAX_INFINITY) { mReplicationLimitedFileIds.add(file.getId()); } } // Update indexes. if (inode.isFile() && inode.isPinned()) { mPinnedInodeFileIds.add(inode.getId()); } // Add the file to TTL buckets, the insert automatically rejects files w/ Constants.NO_TTL mTtlBuckets.insert(Inode.wrap(inode)); updateToBePersistedIds(inode); } private void applyRename(RenameEntry entry) { if (entry.hasDstPath()) { entry = rewriteDeprecatedRenameEntry(entry); } MutableInode<?> inode = mInodeStore.getMutable(entry.getId()).get(); long oldParent = inode.getParentId(); long newParent = entry.getNewParentId(); mInodeStore.removeChild(oldParent, inode.getName()); inode.setName(entry.getNewName()); mInodeStore.addChild(newParent, inode); inode.setParentId(newParent); mInodeStore.writeInode(inode); if (oldParent == newParent) { updateTimestampsAndChildCount(oldParent, entry.getOpTimeMs(), 0); } else { updateTimestampsAndChildCount(oldParent, entry.getOpTimeMs(), -1); updateTimestampsAndChildCount(newParent, entry.getOpTimeMs(), 1); } } /** * Updates the last modification time and last access time for the indicated inode directory, * and updates its child count. * * If the inode's timestamps are already greater than the specified time, the inode's timestamps * will not be changed. * * @param id the inode to update * @param opTimeMs the time of the operation that modified the inode * @param deltaChildCount the change in inode directory child count */ private void updateTimestampsAndChildCount(long id, long opTimeMs, long deltaChildCount) { try (LockResource lr = mInodeLockManager.lockUpdate(id)) { MutableInodeDirectory inode = mInodeStore.getMutable(id).get().asDirectory(); boolean madeUpdate = false; if (inode.getLastModificationTimeMs() < opTimeMs) { inode.setLastModificationTimeMs(opTimeMs); madeUpdate = true; } if (inode.getLastAccessTimeMs() < opTimeMs) { inode.setLastAccessTimeMs(opTimeMs); madeUpdate = true; } if (deltaChildCount != 0) { inode.setChildCount(inode.getChildCount() + deltaChildCount); madeUpdate = true; } if (madeUpdate) { mInodeStore.writeInode(inode); } } } private void updateToBePersistedIds(MutableInode<?> inode) { if (inode.getPersistenceState() == PersistenceState.TO_BE_PERSISTED) { mToBePersistedIds.add(inode.getId()); } else { mToBePersistedIds.remove(inode.getId()); } } private RenameEntry rewriteDeprecatedRenameEntry(RenameEntry entry) { Preconditions.checkState(!entry.hasNewName(), "old-style rename entries should not have the newName field set"); Preconditions.checkState(!entry.hasNewParentId(), "old-style rename entries should not have the newParentId field set"); Path path = Paths.get(entry.getDstPath()); Path parent = path.getParent(); Path filename = path.getFileName(); if (parent == null) { throw new NullPointerException("path parent cannot be null"); } if (filename == null) { throw new NullPointerException("path filename cannot be null"); } return RenameEntry.newBuilder().setId(entry.getId()) .setNewParentId(getIdFromPath(parent)) .setNewName(filename.toString()) .setOpTimeMs(entry.getOpTimeMs()).build(); } private long getIdFromPath(Path path) { Inode curr = getRoot(); for (Path component : path) { curr = mInodeStore.getChild(curr.asDirectory(), component.toString()).get(); } return curr.getId(); } @Override public boolean processJournalEntry(JournalEntry entry) { if (entry.hasDeleteFile()) { applyDelete(entry.getDeleteFile()); } else if (entry.hasInodeDirectory()) { applyCreateDirectory(entry.getInodeDirectory()); } else if (entry.hasInodeFile()) { applyCreateFile(entry.getInodeFile()); } else if (entry.hasNewBlock()) { applyNewBlock(entry.getNewBlock()); } else if (entry.hasRename()) { applyRename(entry.getRename()); } else if (entry.hasSetAcl()) { applySetAcl(entry.getSetAcl()); } else if (entry.hasUpdateInode()) { applyUpdateInode(entry.getUpdateInode()); } else if (entry.hasUpdateInodeDirectory()) { applyUpdateInodeDirectory(entry.getUpdateInodeDirectory()); } else if (entry.hasUpdateInodeFile()) { applyUpdateInodeFile(entry.getUpdateInodeFile()); // Deprecated entries } else if (entry.hasAsyncPersistRequest()) { applyAsyncPersist(entry.getAsyncPersistRequest()); } else if (entry.hasCompleteFile()) { applyCompleteFile(entry.getCompleteFile()); } else if (entry.hasInodeLastModificationTime()) { applyInodeLastModificationTime(entry.getInodeLastModificationTime()); } else if (entry.hasPersistDirectory()) { applyPersistDirectory(entry.getPersistDirectory()); } else if (entry.hasSetAttribute()) { applySetAttribute(entry.getSetAttribute()); } else { return false; } return true; } @Override public void resetState() { mInodeStore.clear(); mReplicationLimitedFileIds.clear(); mPinnedInodeFileIds.clear(); } @Override public void writeToCheckpoint(OutputStream output) throws IOException, InterruptedException { // mTtlBuckets must come after mInodeStore so that it can query the inode store to resolve inode // ids to inodes. JournalUtils.writeToCheckpoint(output, Arrays.asList(mInodeStore, mPinnedInodeFileIds, mReplicationLimitedFileIds, mToBePersistedIds, mTtlBuckets, mInodeCounter)); } @Override public void restoreFromCheckpoint(CheckpointInputStream input) throws IOException { // mTtlBuckets must come after mInodeStore so that it can query the inode store to resolve inode // ids to inodes. JournalUtils.restoreFromCheckpoint(input, Arrays.asList(mInodeStore, mPinnedInodeFileIds, mReplicationLimitedFileIds, mToBePersistedIds, mTtlBuckets, mInodeCounter)); } @Override public CloseableIterator<JournalEntry> getJournalEntryIterator() { return InodeTreeBufferedIterator.create(mInodeStore, getRoot()); } @Override public CheckpointName getCheckpointName() { return CheckpointName.INODE_TREE; } }
37.103495
100
0.703315
f32c16697b9719604e3544d494636ee305ed2d21
1,262
package lab3_sebastianramirezdiegovarela; public class Persona { private String nombre,apellido; private int años_profesional,salario; public Persona() { } public Persona(String nombre, String apellido, int años_profesional, int salario) { this.nombre = nombre; this.apellido = apellido; this.años_profesional = años_profesional; this.salario = salario; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public int getAños_profesional() { return años_profesional; } public void setAños_profesional(int años_profesional) { this.años_profesional = años_profesional; } public int getSalario() { return salario; } public void setSalario(int salario) { this.salario = salario; } @Override public String toString() { return "Persona{" + "nombre=" + nombre + ", apellido=" + apellido + ", a\u00f1os_profesional=" + años_profesional + ", salario=" + salario + '}'; } }
22.945455
153
0.628368
fd931136702e2e470676c1fbfa7c771495fdfe23
959
package com.wulai.knowledge; import com.WulaiClient; import com.exceptions.ClientException; import com.exceptions.ServerException; import com.module.response.knowledge.KnowledgeItemsList; import org.apache.http.client.methods.CloseableHttpResponse; import java.util.HashMap; public class QueryKnowledgeItemsList { private int page; private int pageSize; public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setPage(int page) { this.page = page; } public KnowledgeItemsList request(WulaiClient wulaiClient) throws ServerException, ClientException { HashMap<String, Object> params = new HashMap<>(); params.put("page", page); params.put("page_size", pageSize); CloseableHttpResponse httpResponse = wulaiClient.executeRequest("/qa/knowledge-items/list", params); return wulaiClient.getResponse(httpResponse, KnowledgeItemsList.class); } }
29.060606
108
0.734098
29936504dd000108a0e9231d83bf5bcdbd913f2c
218
package com.katsuraf.demoarchitecture.ui.view; import java.util.List; public interface IKeywordsView extends ILoadDataView { void showKeywords(List<String> keywords); void showKeywordsView(boolean isShow); }
24.222222
54
0.793578
085fbb71938431a03cbf6c8cbcded9cfe6739f59
379
package org.ormfux.common.db.generators; /** * A generator that does nothing but throwing an Exception. */ public final class NoValueGenerator implements ValueGenerator<Void> { /** * @throws UnsupportedOperationException */ @Override public Void generate(final Object previousValue) { throw new UnsupportedOperationException(); } }
22.294118
69
0.693931
3d31e66b1af73a7ad99ed8cfa93929acdc20125a
4,444
package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; import io.swagger.annotations.*; import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic; import org.openecomp.sdc.be.components.upgrade.UpgradeRequest; import org.openecomp.sdc.be.components.upgrade.UpgradeStatus; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Controller; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "policy types resource") @Controller @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AutomatedUpgradeEndpoint extends BeGenericServlet { private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class); private final UpgradeBusinessLogic businessLogic; public AutomatedUpgradeEndpoint(UpgradeBusinessLogic businessLogic) { this.businessLogic = businessLogic; } @POST @Path("/{componentType}/{componentId}/automatedupgrade") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Autometed upgrade", httpMethod = "POST", notes = "....", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) public Response autometedUpgrade(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "json describes upgrade request", required = true) String data) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(POST) Start handle request of {}", url); try { List<UpgradeRequest> inputsToUpdate = JsonParserUtils.toList(data, UpgradeRequest.class); if (log.isDebugEnabled()) { log.debug("Received upgrade requests size is {}", inputsToUpdate == null ? 0 : inputsToUpdate.size()); } UpgradeStatus actionResponse = businessLogic.automatedUpgrade(componentId, inputsToUpdate, userId); return actionResponse.getStatus() == ActionStatus.OK ? buildOkResponse(actionResponse) : buildErrorResponse(actionResponse.getError()); } catch (Exception e) { log.error("#autometedUpgrade - Exception occurred during autometed Upgrade", e); return buildGeneralErrorResponse(); } } @GET @Path("/{componentType}/{componentId}/dependencies") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Autometed upgrade", httpMethod = "POST", notes = "....", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) public Response getComponentDependencies(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(GET) Start handle request of {}", url); try { return businessLogic.getComponentDependencies(componentId, userId) .either(this::buildOkResponse, this::buildErrorResponse); } catch (Exception e) { log.error("#getServicesForComponent - Exception occurred during autometed Upgrade", e); return buildGeneralErrorResponse(); } } }
49.377778
257
0.710396
146a9c7b38a48ba42683c9fb3df814d6d7b555fb
4,367
package com.base12innovations.android.fireroad.activity; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.base12innovations.android.fireroad.MainActivity; import com.base12innovations.android.fireroad.R; import com.base12innovations.android.fireroad.models.doc.Document; import com.base12innovations.android.fireroad.models.doc.DocumentManager; import com.base12innovations.android.fireroad.models.doc.RoadDocument; import com.base12innovations.android.fireroad.models.doc.User; import com.base12innovations.android.fireroad.utils.TaskDispatcher; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class ImportActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_import); final Uri data = getIntent().getData(); if (data != null) { getIntent().setData(null); TaskDispatcher.inBackground(new TaskDispatcher.TaskNoReturn() { @Override public void perform() { try { RoadDocument doc = importData(data); if (doc != null) { User.currentUser().initialize(ImportActivity.this); User.currentUser().setCurrentDocument(doc); } else { showError(); return; } TaskDispatcher.onMain(new TaskDispatcher.TaskNoReturn() { @Override public void perform() { // launch home Activity (with FLAG_ACTIVITY_CLEAR_TOP) here… Intent i = new Intent(ImportActivity.this, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); showError(); } } }); } } private void showError() { TaskDispatcher.onMain(new TaskDispatcher.TaskNoReturn() { @Override public void perform() { AlertDialog.Builder b = new AlertDialog.Builder(ImportActivity.this); b.setTitle("Invalid File"); b.setMessage("There was a problem importing the file."); b.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); finish(); } }); b.show(); } }); } private RoadDocument importData(Uri data) throws Exception { final String scheme = data.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { ContentResolver cr = getContentResolver(); InputStream is = cr.openInputStream(data); if (is == null) return null; StringBuffer buf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String str; while ((str = reader.readLine()) != null) { buf.append(str + "\n"); } is.close(); DocumentManager roadDocManager = new DocumentManager(Document.ROAD_DOCUMENT_TYPE, getFilesDir(), this); String baseName = data.getLastPathSegment(); baseName = baseName.substring(0, baseName.lastIndexOf('.')); RoadDocument newDoc = (RoadDocument)roadDocManager.getNewDocument(roadDocManager.noConflictName(baseName)); newDoc.parse(buf.toString()); newDoc.save(); return newDoc; } return null; } }
39.342342
119
0.569041
6f798fa23007e36deca680ae91a3a5e6d09c251b
600
package org.springframework.boot.test.mock.mockito.example; /** * Example bean for mocking tests that calls {@link ExampleGenericService}. * * @author Phillip Webb */ public class ExampleGenericStringServiceCaller { private final ExampleGenericService<String> stringService; public ExampleGenericStringServiceCaller( ExampleGenericService<String> stringService) { this.stringService = stringService; } public ExampleGenericService<String> getStringService() { return this.stringService; } public String sayGreeting() { return "I say " + this.stringService.greeting(); } }
21.428571
75
0.771667
97415748e722f1c4a02e1d2e7a85de510e3a5a25
612
package com.jamieswhiteshirt.clothesline.api; import net.minecraft.world.World; import net.minecraftforge.fml.common.eventhandler.Event; public class NetworkManagerCreatedEvent extends Event { private final World world; private final INetworkManager networkManager; public NetworkManagerCreatedEvent(World world, INetworkManager networkManager) { this.world = world; this.networkManager = networkManager; } public World getWorld() { return world; } public INetworkManager getNetworkManager() { return networkManager; } }
26.608696
85
0.70915
a18589d8644a43a88a7d0e4c4361e6a1b361a9fc
457
package bence.prognyelvek.transition.conditions; import bence.prognyelvek.contexts.ContextView; public class DeterministicCondition<T, O> extends AbstractCondition<T, O> { private final boolean result; public DeterministicCondition(final String name, final boolean result) { super(name); this.result = result; } @Override public boolean checkAgainst(final ContextView<T, O> context) { return result; } }
24.052632
76
0.713348
bfef7117154a6136f8962cc61ca1410825d28266
7,078
/* * MIT License * * Copyright (c) 2021 Imanity * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.fairy.locale; import com.google.common.base.Preconditions; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.fairy.bean.*; import org.fairy.config.yaml.YamlConfiguration; import org.fairy.storage.DataClosable; import org.fairy.storage.PlayerStorage; import org.fairy.util.CC; import org.fairy.util.FileUtil; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @Service(name = "locale") public class LocaleService { private Map<String, Locale> locales; @Getter private Locale defaultLocale; private Yaml yaml; @Setter private PlayerLocaleStorage localeStorage; private LocalizationConfiguration localizationConfiguration; @PreInitialize public void onPreInitialize() { ComponentRegistry.registerComponentHolder(new ComponentHolder() { @Override public Class<?>[] type() { return new Class[] {LocaleDirectory.class}; } @Override public void onEnable(Object instance) { loadLocaleDirectory((LocaleDirectory) instance); } }); } @PostInitialize public void onPostInitialize() { this.localizationConfiguration = new LocalizationConfiguration(); this.localizationConfiguration.loadAndSave(); this.locales = new ConcurrentHashMap<>(); this.defaultLocale = this.getOrRegister(this.localizationConfiguration.getDefaultLocale()); this.yaml = new Yaml(); } public void loadLocaleDirectory(LocaleDirectory localeDirectory) { final File directory = localeDirectory.directory(); if (!directory.exists()) { directory.mkdirs(); final String resourceDirectory = localeDirectory.resourceDirectory(); if (resourceDirectory != null) { FileUtil.forEachDirectoryInResources(localeDirectory.getClass(), resourceDirectory, (name, inputStream) -> { final File file = new File(directory, name); FileUtil.writeInputStreamToFile(inputStream, file); }); } } for (File file : directory.listFiles()) { String name = FilenameUtils.removeExtension(file.getName()); this.registerFromYaml(name, localeDirectory.config(file)); } final String defaultLocale = localeDirectory.defaultLocale(); File defaultLocaleFile = new File(directory, defaultLocale + ".yml"); if (!defaultLocaleFile.exists()) { this.registerFromYaml(defaultLocale, localeDirectory.config(defaultLocaleFile)); } } public Locale getOrRegister(String name) { Locale locale = this.locales.get(name); if (locale == null) { locale = this.registerLocale(name); } return locale; } public Locale registerLocale(String name) { final Locale locale = new Locale(name); this.locales.put(name, locale); return locale; } public Locale unregisterLocale(String name) { return this.locales.remove(name); } public Locale registerFromYml(File file) { try { return this.registerFromYml(new FileInputStream(file)); } catch (Throwable throwable) { throw new RuntimeException("Something wrong while loading file for locale", throwable); } } public Locale registerFromYml(InputStream inputStream) { Map<String, Object> map = this.yaml.load(inputStream); String name = map.get("locale").toString(); Locale locale = this.getOrRegister(name); locale.registerEntries("", map); return locale; } public Locale registerFromYaml(String name, YamlConfiguration yamlConfiguration) { try { final Map<String, Object> entries = yamlConfiguration.loadEntries(); Locale locale = this.getOrRegister(name); locale.registerEntries("", entries); return locale; } catch (IOException e) { throw new RuntimeException(e); } } public Locale getLocaleByName(String name) { if (this.locales.containsKey(name)) { return this.locales.get(name); } return null; } public Locale getLocale(UUID uuid) { return this.localeStorage.find(uuid).getLocale(); } public <Player> Locale getLocale(Player player) { return this.localeStorage.find(this.localeStorage.getUuidByPlayer(player)).getLocale(); } public void setLocale(UUID uuid, @NonNull Locale locale) { try (DataClosable<LocaleData> data = this.localeStorage.findAndSave(uuid)) { data.val().setLocale(locale); } } public <Player> void setLocale(Player player, @NonNull Locale locale) { this.setLocale(this.localeStorage.getUuidByPlayer(player), locale); } public void setLocale(UUID uuid, @NonNull String localeName) { final Locale locale = this.getLocaleByName(localeName); Preconditions.checkNotNull(locale, "Couldn't find locale with name " + localeName); this.setLocale(uuid, locale); } public <Player> void setLocale(Player player, @NonNull String localeName) { this.setLocale(this.localeStorage.getUuidByPlayer(player), localeName); } public String translate(UUID uuid, String key) { return CC.translate(this.getLocale(uuid).get(key)); } public <Player> String translate(Player player, String key) { return this.translate(this.localeStorage.getUuidByPlayer(player), key); } }
33.386792
124
0.675615
b08d6824e517c0380954663fb0ce0c05f8cddb29
44,440
/** * Copyright (c) 2016-present, RxJava Contributors. * * 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.reactivex.rxjava3.flowable; import static org.junit.Assert.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import org.junit.*; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.exceptions.*; import io.reactivex.rxjava3.functions.*; import io.reactivex.rxjava3.internal.functions.Functions; import io.reactivex.rxjava3.processors.*; import io.reactivex.rxjava3.schedulers.Schedulers; import io.reactivex.rxjava3.subscribers.TestSubscriber; import io.reactivex.rxjava3.testsupport.TestHelper; /** * Verifies the operators handle null values properly by emitting/throwing NullPointerExceptions. */ public class FlowableNullTests extends RxJavaTest { Flowable<Integer> just1 = Flowable.just(1); //*********************************************************** // Static methods //*********************************************************** @Test(expected = NullPointerException.class) public void ambVarargsOneIsNull() { Flowable.ambArray(Flowable.never(), null).blockingLast(); } @Test public void ambIterableIteratorNull() { Flowable.amb(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }).test().assertError(NullPointerException.class); } @Test public void ambIterableOneIsNull() { Flowable.amb(Arrays.asList(Flowable.never(), null)) .test() .assertError(NullPointerException.class); } @Test(expected = NullPointerException.class) public void combineLatestIterableIteratorNull() { Flowable.combineLatestDelayError(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }, new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return 1; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void combineLatestIterableOneIsNull() { Flowable.combineLatestDelayError(Arrays.asList(Flowable.never(), null), new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return 1; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void combineLatestIterableFunctionReturnsNull() { Flowable.combineLatestDelayError(Arrays.asList(just1), new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return null; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void concatIterableIteratorNull() { Flowable.concat(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void concatIterableOneIsNull() { Flowable.concat(Arrays.asList(just1, null)).blockingLast(); } @Test(expected = NullPointerException.class) public void concatArrayOneIsNull() { Flowable.concatArray(just1, null).blockingLast(); } @Test(expected = NullPointerException.class) public void deferFunctionReturnsNull() { Flowable.defer(new Supplier<Publisher<Object>>() { @Override public Publisher<Object> get() { return null; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void errorFunctionReturnsNull() { Flowable.error(new Supplier<Throwable>() { @Override public Throwable get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void fromArrayOneIsNull() { Flowable.fromArray(1, null).blockingLast(); } @Test(expected = NullPointerException.class) public void fromCallableReturnsNull() { Flowable.fromCallable(new Callable<Object>() { @Override public Object call() throws Exception { return null; } }).blockingLast(); } @Test public void fromFutureReturnsNull() { FutureTask<Object> f = new FutureTask<>(Functions.EMPTY_RUNNABLE, null); f.run(); TestSubscriber<Object> ts = new TestSubscriber<>(); Flowable.fromFuture(f).subscribe(ts); ts.assertNoValues(); ts.assertNotComplete(); ts.assertError(NullPointerException.class); } @Test(expected = NullPointerException.class) public void fromFutureTimedReturnsNull() { FutureTask<Object> f = new FutureTask<>(Functions.EMPTY_RUNNABLE, null); f.run(); Flowable.fromFuture(f, 1, TimeUnit.SECONDS).blockingLast(); } @Test(expected = NullPointerException.class) public void fromIterableIteratorNull() { Flowable.fromIterable(new Iterable<Object>() { @Override public Iterator<Object> iterator() { return null; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void fromIterableValueNull() { Flowable.fromIterable(Arrays.asList(1, null)).blockingLast(); } @Test(expected = NullPointerException.class) public void generateConsumerEmitsNull() { Flowable.generate(new Consumer<Emitter<Object>>() { @Override public void accept(Emitter<Object> s) { s.onNext(null); } }).blockingLast(); } @Test(expected = NullPointerException.class) public void generateStateConsumerInitialStateNull() { BiConsumer<Integer, Emitter<Integer>> generator = new BiConsumer<Integer, Emitter<Integer>>() { @Override public void accept(Integer s, Emitter<Integer> o) { o.onNext(1); } }; Flowable.generate(null, generator); } @Test(expected = NullPointerException.class) public void generateStateFunctionInitialStateNull() { Flowable.generate(null, new BiFunction<Object, Emitter<Object>, Object>() { @Override public Object apply(Object s, Emitter<Object> o) { o.onNext(1); return s; } }); } @Test(expected = NullPointerException.class) public void generateStateConsumerNull() { Flowable.generate(new Supplier<Integer>() { @Override public Integer get() { return 1; } }, (BiConsumer<Integer, Emitter<Object>>)null); } @Test public void generateConsumerStateNullAllowed() { BiConsumer<Integer, Emitter<Integer>> generator = new BiConsumer<Integer, Emitter<Integer>>() { @Override public void accept(Integer s, Emitter<Integer> o) { o.onComplete(); } }; Flowable.generate(new Supplier<Integer>() { @Override public Integer get() { return null; } }, generator).blockingSubscribe(); } @Test public void generateFunctionStateNullAllowed() { Flowable.generate(new Supplier<Object>() { @Override public Object get() { return null; } }, new BiFunction<Object, Emitter<Object>, Object>() { @Override public Object apply(Object s, Emitter<Object> o) { o.onComplete(); return s; } }).blockingSubscribe(); } @Test public void justNull() throws Exception { @SuppressWarnings("rawtypes") Class<Flowable> clazz = Flowable.class; for (int argCount = 1; argCount < 10; argCount++) { for (int argNull = 1; argNull <= argCount; argNull++) { Class<?>[] params = new Class[argCount]; Arrays.fill(params, Object.class); Object[] values = new Object[argCount]; Arrays.fill(values, 1); values[argNull - 1] = null; Method m = clazz.getMethod("just", params); try { m.invoke(null, values); Assert.fail("No exception for argCount " + argCount + " / argNull " + argNull); } catch (InvocationTargetException ex) { if (!(ex.getCause() instanceof NullPointerException)) { Assert.fail("Unexpected exception for argCount " + argCount + " / argNull " + argNull + ": " + ex); } } } } } @Test(expected = NullPointerException.class) public void mergeIterableIteratorNull() { Flowable.merge(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }, 128, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void mergeIterableOneIsNull() { Flowable.merge(Arrays.asList(just1, null), 128, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void mergeArrayOneIsNull() { Flowable.mergeArray(128, 128, just1, null).blockingLast(); } @Test(expected = NullPointerException.class) public void mergeDelayErrorIterableIteratorNull() { Flowable.mergeDelayError(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }, 128, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void mergeDelayErrorIterableOneIsNull() { Flowable.mergeDelayError(Arrays.asList(just1, null), 128, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void mergeDelayErrorArrayOneIsNull() { Flowable.mergeArrayDelayError(128, 128, just1, null).blockingLast(); } @Test(expected = NullPointerException.class) public void usingFlowableSupplierReturnsNull() { Flowable.using(new Supplier<Object>() { @Override public Object get() { return 1; } }, new Function<Object, Publisher<Object>>() { @Override public Publisher<Object> apply(Object d) { return null; } }, Functions.emptyConsumer()).blockingLast(); } @Test(expected = NullPointerException.class) public void zipIterableIteratorNull() { Flowable.zip(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }, new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return 1; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void zipIterableFunctionReturnsNull() { Flowable.zip(Arrays.asList(just1, just1), new Function<Object[], Object>() { @Override public Object apply(Object[] a) { return null; } }).blockingLast(); } @Test(expected = NullPointerException.class) public void zipIterable2Null() { Flowable.zip((Iterable<Publisher<Object>>)null, new Function<Object[], Object>() { @Override public Object apply(Object[] a) { return 1; } }, true, 128); } @Test(expected = NullPointerException.class) public void zipIterable2IteratorNull() { Flowable.zip(new Iterable<Publisher<Object>>() { @Override public Iterator<Publisher<Object>> iterator() { return null; } }, new Function<Object[], Object>() { @Override public Object apply(Object[] a) { return 1; } }, true, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void zipIterable2FunctionReturnsNull() { Flowable.zip(Arrays.asList(just1, just1), new Function<Object[], Object>() { @Override public Object apply(Object[] a) { return null; } }, true, 128).blockingLast(); } //************************************************************* // Instance methods //************************************************************* @Test(expected = NullPointerException.class) public void bufferSupplierReturnsNull() { just1.buffer(1, 1, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void bufferTimedSupplierReturnsNull() { just1.buffer(1L, 1L, TimeUnit.SECONDS, Schedulers.single(), new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void bufferOpenCloseCloseReturnsNull() { just1.buffer(just1, new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void bufferBoundarySupplierReturnsNull() { just1.buffer(just1, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void collectInitialSupplierReturnsNull() { just1.collect(new Supplier<Object>() { @Override public Object get() { return null; } }, new BiConsumer<Object, Integer>() { @Override public void accept(Object a, Integer b) { } }).blockingGet(); } @Test(expected = NullPointerException.class) public void concatMapReturnsNull() { just1.concatMap(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void concatMapIterableReturnNull() { just1.concatMapIterable(new Function<Integer, Iterable<Object>>() { @Override public Iterable<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void concatMapIterableIteratorNull() { just1.concatMapIterable(new Function<Integer, Iterable<Object>>() { @Override public Iterable<Object> apply(Integer v) { return new Iterable<Object>() { @Override public Iterator<Object> iterator() { return null; } }; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void debounceFunctionReturnsNull() { just1.debounce(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void delayWithFunctionReturnsNull() { just1.delay(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void delayBothItemSupplierReturnsNull() { just1.delay(just1, new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void distinctSupplierReturnsNull() { just1.distinct(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Supplier<Collection<Object>>() { @Override public Collection<Object> get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void distinctFunctionReturnsNull() { just1.distinct(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingSubscribe(); } @Test public void distinctUntilChangedFunctionReturnsNull() { Flowable.range(1, 2).distinctUntilChanged(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).test().assertResult(1); } @Test(expected = NullPointerException.class) public void flatMapFunctionReturnsNull() { just1.flatMap(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapNotificationOnNextReturnsNull() { just1.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return null; } }, new Function<Throwable, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Throwable e) { return just1; } }, new Supplier<Publisher<Integer>>() { @Override public Publisher<Integer> get() { return just1; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapNotificationOnCompleteReturnsNull() { just1.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return just1; } }, new Function<Throwable, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Throwable e) { return just1; } }, new Supplier<Publisher<Integer>>() { @Override public Publisher<Integer> get() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapCombinerMapperReturnsNull() { just1.flatMap(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }, new BiFunction<Integer, Object, Object>() { @Override public Object apply(Integer a, Object b) { return 1; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapCombinerCombinerReturnsNull() { just1.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return just1; } }, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapIterableMapperReturnsNull() { just1.flatMapIterable(new Function<Integer, Iterable<Object>>() { @Override public Iterable<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapIterableMapperIteratorNull() { just1.flatMapIterable(new Function<Integer, Iterable<Object>>() { @Override public Iterable<Object> apply(Integer v) { return new Iterable<Object>() { @Override public Iterator<Object> iterator() { return null; } }; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapIterableMapperIterableOneNull() { just1.flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return Arrays.asList(1, null); } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void flatMapIterableCombinerReturnsNull() { just1.flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return Arrays.asList(1); } }, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } public void groupByKeyNull() { just1.groupBy(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void groupByValueReturnsNull() { just1.groupBy(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void liftReturnsNull() { just1.lift(new FlowableOperator<Object, Integer>() { @Override public Subscriber<? super Integer> apply(Subscriber<? super Object> s) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void mapReturnsNull() { just1.map(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingSubscribe(); } @Test public void onErrorResumeNextFunctionReturnsNull() { try { Flowable.error(new TestException()).onErrorResumeNext(new Function<Throwable, Publisher<Object>>() { @Override public Publisher<Object> apply(Throwable e) { return null; } }).blockingSubscribe(); fail("Should have thrown"); } catch (CompositeException ex) { List<Throwable> errors = ex.getExceptions(); TestHelper.assertError(errors, 0, TestException.class); TestHelper.assertError(errors, 1, NullPointerException.class); assertEquals(2, errors.size()); } } @Test public void onErrorReturnFunctionReturnsNull() { try { Flowable.error(new TestException()).onErrorReturn(new Function<Throwable, Object>() { @Override public Object apply(Throwable e) { return null; } }).blockingSubscribe(); fail("Should have thrown"); } catch (CompositeException ex) { List<Throwable> errors = TestHelper.compositeList(ex); TestHelper.assertError(errors, 0, TestException.class); TestHelper.assertError(errors, 1, NullPointerException.class, "The valueSupplier returned a null value"); } } @Test(expected = NullPointerException.class) public void publishFunctionReturnsNull() { just1.publish(new Function<Flowable<Integer>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Integer> v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void reduceFunctionReturnsNull() { Flowable.just(1, 1).reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return null; } }).toFlowable().blockingSubscribe(); } @Test(expected = NullPointerException.class) public void reduceSeedFunctionReturnsNull() { just1.reduce(1, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return null; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void reduceWithSeedNull() { just1.reduceWith(null, new BiFunction<Object, Integer, Object>() { @Override public Object apply(Object a, Integer b) { return 1; } }); } @Test(expected = NullPointerException.class) public void reduceWithSeedReturnsNull() { just1.reduceWith(new Supplier<Object>() { @Override public Object get() { return null; } }, new BiFunction<Object, Integer, Object>() { @Override public Object apply(Object a, Integer b) { return 1; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void repeatWhenFunctionReturnsNull() { just1.repeatWhen(new Function<Flowable<Object>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Object> v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replaySelectorNull() { just1.replay((Function<Flowable<Integer>, Flowable<Integer>>)null); } @Test(expected = NullPointerException.class) public void replaySelectorReturnsNull() { just1.replay(new Function<Flowable<Integer>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Integer> f) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replayBoundedSelectorReturnsNull() { just1.replay(new Function<Flowable<Integer>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Integer> v) { return null; } }, 1, 1, TimeUnit.SECONDS).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replayTimeBoundedSelectorReturnsNull() { just1.replay(new Function<Flowable<Integer>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Integer> v) { return null; } }, 1, TimeUnit.SECONDS, Schedulers.single()).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void retryWhenFunctionReturnsNull() { Flowable.error(new TestException()).retryWhen(new Function<Flowable<? extends Throwable>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<? extends Throwable> f) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void scanFunctionReturnsNull() { Flowable.just(1, 1).scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void scanSeedNull() { just1.scan(null, new BiFunction<Object, Integer, Object>() { @Override public Object apply(Object a, Integer b) { return 1; } }); } @Test(expected = NullPointerException.class) public void scanSeedFunctionReturnsNull() { just1.scan(1, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void scanSeedSupplierReturnsNull() { just1.scanWith(new Supplier<Object>() { @Override public Object get() { return null; } }, new BiFunction<Object, Integer, Object>() { @Override public Object apply(Object a, Integer b) { return 1; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void scanSeedSupplierFunctionReturnsNull() { just1.scanWith(new Supplier<Object>() { @Override public Object get() { return 1; } }, new BiFunction<Object, Integer, Object>() { @Override public Object apply(Object a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void startWithIterableIteratorNull() { just1.startWithIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void startWithIterableOneNull() { just1.startWithIterable(Arrays.asList(1, null)).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void startWithArrayOneNull() { just1.startWithArray(1, null).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void switchMapFunctionReturnsNull() { just1.switchMap(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void timeoutSelectorReturnsNull() { just1.timeout(new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void timeoutSelectorOtherNull() { just1.timeout(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return just1; } }, null); } @Test(expected = NullPointerException.class) public void timeoutFirstItemReturnsNull() { just1.timeout(Flowable.never(), new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void timestampUnitNull() { just1.timestamp(null, Schedulers.single()); } @Test(expected = NullPointerException.class) public void timestampSchedulerNull() { just1.timestamp(TimeUnit.SECONDS, null); } @Test(expected = NullPointerException.class) public void toListSupplierReturnsNull() { just1.toList(new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() { return null; } }).toFlowable().blockingSubscribe(); } @Test(expected = NullPointerException.class) public void toListSupplierReturnsNullSingle() { just1.toList(new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() { return null; } }).blockingGet(); } @Test public void toMapValueSelectorReturnsNull() { just1.toMap(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void toMapMapSupplierReturnsNull() { just1.toMap(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Supplier<Map<Object, Object>>() { @Override public Map<Object, Object> get() { return null; } }).blockingGet(); } @Test public void toMultiMapValueSelectorReturnsNullAllowed() { just1.toMap(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Function<Integer, Object>() { @Override public Object apply(Integer v) { return null; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void toMultimapMapSupplierReturnsNull() { just1.toMultimap(new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Function<Integer, Object>() { @Override public Object apply(Integer v) { return v; } }, new Supplier<Map<Object, Collection<Object>>>() { @Override public Map<Object, Collection<Object>> get() { return null; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void toMultimapMapCollectionSupplierReturnsNull() { just1.toMultimap(new Function<Integer, Integer>() { @Override public Integer apply(Integer v) { return v; } }, new Function<Integer, Integer>() { @Override public Integer apply(Integer v) { return v; } }, new Supplier<Map<Integer, Collection<Integer>>>() { @Override public Map<Integer, Collection<Integer>> get() { return new HashMap<>(); } }, new Function<Integer, Collection<Integer>>() { @Override public Collection<Integer> apply(Integer v) { return null; } }).blockingGet(); } @Test(expected = NullPointerException.class) public void windowOpenCloseOpenNull() { just1.window(null, new Function<Object, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Object v) { return just1; } }); } @Test(expected = NullPointerException.class) public void windowOpenCloseCloseReturnsNull() { Flowable.never().window(just1, new Function<Integer, Publisher<Object>>() { @Override public Publisher<Object> apply(Integer v) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void withLatestFromOtherNull() { just1.withLatestFrom(null, new BiFunction<Integer, Object, Object>() { @Override public Object apply(Integer a, Object b) { return 1; } }); } @Test(expected = NullPointerException.class) public void withLatestFromCombinerReturnsNull() { just1.withLatestFrom(just1, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void zipWithIterableNull() { just1.zipWith((Iterable<Integer>)null, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return 1; } }); } @Test(expected = NullPointerException.class) public void zipWithIterableCombinerReturnsNull() { just1.zipWith(Arrays.asList(1), new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void zipWithIterableIteratorNull() { just1.zipWith(new Iterable<Object>() { @Override public Iterator<Object> iterator() { return null; } }, new BiFunction<Integer, Object, Object>() { @Override public Object apply(Integer a, Object b) { return 1; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void zipWithIterableOneIsNull() { Flowable.just(1, 2).zipWith(Arrays.asList(1, null), new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return 1; } }).blockingSubscribe(); } @Test(expected = NullPointerException.class) public void zipWithPublisherNull() { just1.zipWith((Publisher<Integer>)null, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return 1; } }); } @Test(expected = NullPointerException.class) public void zipWithCombinerReturnsNull() { just1.zipWith(just1, new BiFunction<Integer, Integer, Object>() { @Override public Object apply(Integer a, Integer b) { return null; } }).blockingSubscribe(); } //********************************************* // Subject null tests //********************************************* @Test(expected = NullPointerException.class) public void asyncSubjectOnNextNull() { FlowableProcessor<Integer> processor = AsyncProcessor.create(); processor.onNext(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void asyncSubjectOnErrorNull() { FlowableProcessor<Integer> processor = AsyncProcessor.create(); processor.onError(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void behaviorSubjectOnNextNull() { FlowableProcessor<Integer> processor = BehaviorProcessor.create(); processor.onNext(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void behaviorSubjectOnErrorNull() { FlowableProcessor<Integer> processor = BehaviorProcessor.create(); processor.onError(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void publishSubjectOnNextNull() { FlowableProcessor<Integer> processor = PublishProcessor.create(); processor.onNext(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void publishSubjectOnErrorNull() { FlowableProcessor<Integer> processor = PublishProcessor.create(); processor.onError(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replaycSubjectOnNextNull() { FlowableProcessor<Integer> processor = ReplayProcessor.create(); processor.onNext(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void replaySubjectOnErrorNull() { FlowableProcessor<Integer> processor = ReplayProcessor.create(); processor.onError(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void serializedcSubjectOnNextNull() { FlowableProcessor<Integer> processor = PublishProcessor.<Integer>create().toSerialized(); processor.onNext(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void serializedSubjectOnErrorNull() { FlowableProcessor<Integer> processor = PublishProcessor.<Integer>create().toSerialized(); processor.onError(null); processor.blockingSubscribe(); } @Test(expected = NullPointerException.class) public void combineLatestDelayErrorIterableFunctionReturnsNull() { Flowable.combineLatestDelayError(Arrays.asList(just1), new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return null; } }, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void combineLatestDelayErrorIterableIteratorNull() { Flowable.combineLatestDelayError(new Iterable<Flowable<Object>>() { @Override public Iterator<Flowable<Object>> iterator() { return null; } }, new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return 1; } }, 128).blockingLast(); } @Test(expected = NullPointerException.class) public void combineLatestDelayErrorIterableOneIsNull() { Flowable.combineLatestDelayError(Arrays.asList(Flowable.never(), null), new Function<Object[], Object>() { @Override public Object apply(Object[] v) { return 1; } }, 128).blockingLast(); } }
33.139448
123
0.573087
16fd2f6019180a39ccf04d503d3f7b9c79c88fa0
1,748
package org.n52.emodnet.eurofleets.feeder.model; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.node.ObjectNode; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.n52.emodnet.eurofleets.feeder.JsonConstants; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = JsonConstants.TYPE) @JsonSubTypes({@JsonSubTypes.Type(name = "Feature", value = Feature.class)}) public class Feature implements Enveloped { private String id; private Geometry geometry; private ObjectNode properties; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonGetter(JsonConstants.ID) public String getId() { return id; } @JsonSetter(JsonConstants.ID) public void setId(String id) { this.id = id; } @JsonGetter(JsonConstants.GEOMETRY) public Geometry getGeometry() { return geometry; } @JsonSetter(JsonConstants.GEOMETRY) public void setGeometry(Geometry geometry) { this.geometry = geometry; } @JsonGetter(JsonConstants.PROPERTIES) @JsonInclude(JsonInclude.Include.NON_EMPTY) public ObjectNode getProperties() { return properties; } @JsonSetter(JsonConstants.PROPERTIES) public void setProperties(ObjectNode properties) { this.properties = properties; } @JsonIgnore @Override public Envelope getEnvelope() { return geometry.getEnvelopeInternal(); } }
29.627119
76
0.739703
754d2f27601e8803571ef1364c3968b70c2b6cc4
631
package lunch.finance.psd2.product.client; import lunch.finance.psd2.product.Product; import lunch.finance.psd2.product.ProductCache; import lunch.finance.psd2.product.ProductFeignConfiguration; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import static org.springframework.web.bind.annotation.RequestMethod.GET; @FeignClient(value = "http://product-stub:8010", fallback = ProductCache.class, configuration = ProductFeignConfiguration.class) public interface ProductClient { @RequestMapping(value = "", method = GET) Product getProduct(); }
37.117647
128
0.812995
f795fe52fbbe5bcd91a643df9af2f2e5262c1462
5,828
/* * @(#)LocaleServiceProvider.java 1.4 06/04/21 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.util.spi; import java.util.Locale; /** * <p> * This is the super class of all the locale sensitive service provider * interfaces (SPIs). * <p> * Locale sensitive service provider interfaces are interfaces that * correspond to locale sensitive classes in the <code>java.text</code> * and <code>java.util</code> packages. The interfaces enable the * construction of locale sensitive objects and the retrieval of * localized names for these packages. Locale sensitive factory methods * and methods for name retrieval in the <code>java.text</code> and * <code>java.util</code> packages use implementations of the provider * interfaces to offer support for locales beyond the set of locales * supported by the Java runtime environment itself. * <p> * <h4>Packaging of Locale Sensitive Service Provider Implementations</h4> * Implementations of these locale sensitive services are packaged using the * <a href="../../../../technotes/guides/extensions/index.html">Java Extension Mechanism</a> * as installed extensions. A provider identifies itself with a * provider-configuration file in the resource directory META-INF/services, * using the fully qualified provider interface class name as the file name. * The file should contain a list of fully-qualified concrete provider class names, * one per line. A line is terminated by any one of a line feed ('\n'), a carriage * return ('\r'), or a carriage return followed immediately by a line feed. Space * and tab characters surrounding each name, as well as blank lines, are ignored. * The comment character is '#' ('\u0023'); on each line all characters following * the first comment character are ignored. The file must be encoded in UTF-8. * <p> * If a particular concrete provider class is named in more than one configuration * file, or is named in the same configuration file more than once, then the * duplicates will be ignored. The configuration file naming a particular provider * need not be in the same jar file or other distribution unit as the provider itself. * The provider must be accessible from the same class loader that was initially * queried to locate the configuration file; this is not necessarily the class loader * that loaded the file. * <p> * For example, an implementation of the * {@link java.text.spi.DateFormatProvider DateFormatProvider} class should * take the form of a jar file which contains the file: * <pre> * META-INF/services/java.text.spi.DateFormatProvider * </pre> * And the file <code>java.text.spi.DateFormatProvider</code> should have * a line such as: * <pre> * <code>com.foo.DateFormatProviderImpl</code> * </pre> * which is the fully qualified class name of the class implementing * <code>DateFormatProvider</code>. * <h4>Invocation of Locale Sensitive Services</h4> * <p> * Locale sensitive factory methods and methods for name retrieval in the * <code>java.text</code> and <code>java.util</code> packages invoke * service provider methods when needed to support the requested locale. * The methods first check whether the Java runtime environment itself * supports the requested locale, and use its support if available. * Otherwise, they call the <code>getAvailableLocales()</code> methods of * installed providers for the appropriate interface to find one that * supports the requested locale. If such a provider is found, its other * methods are called to obtain the requested object or name. If neither * the Java runtime environment itself nor an installed provider supports * the requested locale, a fallback locale is constructed by replacing the * first of the variant, country, or language strings of the locale that's * not an empty string with an empty string, and the lookup process is * restarted. In the case that the variant contains one or more '_'s, the * fallback locale is constructed by replacing the variant with a new variant * which eliminates the last '_' and the part following it. Even if a * fallback occurs, methods that return requested objects or name are * invoked with the original locale before the fallback.The Java runtime * environment must support the root locale for all locale sensitive services * in order to guarantee that this process terminates. * <p> * Providers of names (but not providers of other objects) are allowed to * return null for some name requests even for locales that they claim to * support by including them in their return value for * <code>getAvailableLocales</code>. Similarly, the Java runtime * environment itself may not have all names for all locales that it * supports. This is because the sets of objects for which names are * requested can be large and vary over time, so that it's not always * feasible to cover them completely. If the Java runtime environment or a * provider returns null instead of a name, the lookup will proceed as * described above as if the locale was not supported. * * @since 1.6 * @version @(#)LocaleServiceProvider.java 1.4 06/04/21 */ public abstract class LocaleServiceProvider { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected LocaleServiceProvider() { } /** * Returns an array of all locales for which this locale service provider * can provide localized objects or names. * * @return An array of all locales for which this locale service provider * can provide localized objects or names. */ public abstract Locale[] getAvailableLocales(); }
50.241379
92
0.742622
483533418658eea10b9d0961bd2a26064a786b7f
3,781
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; public class TXTScan { Double precursor; //Precursor mass of isolated ion String file; //Filename int scanNum; //Number of scan boolean centroided; //Boolean if data is centroided int msLevel; //Integer of ms level String polarity; //polarity of scan Double retentionTime; //retention time of scan in seconds Double basePeakMZ; //Mass to charge of most intense peak Double injectionTime; //Injection time in ms ArrayList<ScanPeak> peakArray; //Peak array storing mz and intensity info Double precursorIonFraction; //Precursor ion fraction Double isolationWidth; //Isolation width in Th Double parentIonIntensity; //Intensity of parent ion selected for MS/MS boolean simScan; //True iff scan is a SIM scan Double sn; //Signal-to-noise ratio of MS/MS Double noise; //Noise level of ms/ms //Constructor public TXTScan(int scanNum, boolean centroided, int msLevel, String polarity, Double retentionTime, Double basePeakMZ, String file, Double precursor, String mzArray, String intArray, Double injectionTime, Double isolationWidth) { //Initialize variables peakArray = new ArrayList<ScanPeak>(); this.scanNum = scanNum; this.centroided = centroided; this.msLevel = msLevel; this.polarity = polarity; this.retentionTime = retentionTime; this.basePeakMZ = basePeakMZ; this.precursor = precursor; this.file = file; this.injectionTime = injectionTime; this.precursorIonFraction = 0.0; this.isolationWidth = isolationWidth; parentIonIntensity = 0.0; simScan = false; //Parse bite array into m/z and intensity info parseMZArray(mzArray, intArray); //Calculate PIF calcPIF(40.0); } //Calculate sn public void calcSN() { //Sort by intensity, highest to lowest Collections.sort(peakArray); if (peakArray.size() > 0) { this.sn = peakArray.get(0).intensity/peakArray.get(peakArray.size()-1).intensity; this.noise = peakArray.get(peakArray.size()-1).intensity; } else { this.sn = 0.0; this.noise = 0.0; } } //Calculate precursor ion fraction if ms2 public void calcPIF(Double ppmTol) { Double totalInt = 0.0; Double targetInt = 0.0; if (precursor>0.0) { for (int i=0; i<peakArray.size(); i++) { Double ppmDiff1 = (Math.abs(peakArray.get(i).mz-(precursor))/precursor)*1000000.0; totalInt += peakArray.get(i).intensity; if (ppmDiff1<ppmTol) { targetInt += peakArray.get(i).intensity; } } if (peakArray.size()>0) precursorIonFraction = targetInt/totalInt; else precursorIonFraction = 0.0; } } //Parse m/z array public void parseMZArray(String mzString, String intString) { String[] mzArray = mzString.substring(mzString.indexOf("]")+2).split(" "); String[] intArray = intString.substring(intString.indexOf("]")+2).split(" "); for (int i=0; i<intArray.length; i++) { if (i<mzArray.length) { Double mz = Double.valueOf(mzArray[i]); Double intensity = Double.valueOf(intArray[i]); peakArray.add(new ScanPeak(mz, intensity)); } } } //String reperesentation of scan metadata public String toString() { String result = ""; result += scanNum + ","; result += retentionTime/60.0 + ","; if (simScan) result += "SIM" + ","; else result += msLevel + ","; result += polarity + ","; result += precursor + ","; result += parentIonIntensity + ","; result += isolationWidth + ","; result += injectionTime + ","; result += precursorIonFraction + ","; result += basePeakMZ + ","; result += sn + ","; result += noise + ","; return result; } }
25.721088
86
0.672309
63ebd43d1d716ae863c7e76357328be72f4fa434
596
/* * Created on 04-Nov-2005 Authored by pickardt TODO New class comments */ package uk.co.bluegecko.core.swing.table.rendering; /** * Hint for row height. */ public class RowHeightHint extends RenderingHint< Integer > { private static final long serialVersionUID = 3896501292335647864L; /** * Create a row height hint. * * @param weight * weighting to use * @param value * row height to use */ public RowHeightHint( final HintWeight weight, final Integer value ) { super( RenderingType.HEIGHT, weight, value ); } }
20.551724
71
0.645973
04fa20e5818c92fb2152de753e05156eaf7b6a8a
455
package com.gildedrose; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(Mockito.class) public class GildedRoseTest { @Mock @Test public void foo() { Item[] items = new Item[] { new Item("Doomhammer", 0, 0) }; GildedRose app = new GildedRose(items); app.updateQuality(); assertEquals("Doomhammer", app.item(0).name); } }
21.666667
68
0.624176
60312386486d8b8109051ade82c416c86567f0fc
275
package io.upit.guice.security; import io.upit.security.AuthorizationException; import org.aopalliance.intercept.MethodInvocation; public interface MethodAuthorizer { void authorizeMethodInvocation(MethodInvocation methodInvocation) throws AuthorizationException; }
22.916667
100
0.847273
4a417bb2c9ae4cbede2cb567f2e4264340524874
6,023
/* * Copyright 2016 sadikovi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.sadikovi.netflowlib.predicate; import static org.hamcrest.CoreMatchers.containsString; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.github.sadikovi.netflowlib.predicate.Columns.ByteColumn; import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn; import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn; import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; public class JavaColumnSuite { @Test public void testColumnInit() { // initialize byte column and check min, max ByteColumn col1 = new ByteColumn("name", 1); assertEquals(col1.getColumnName(), "name"); assertEquals(col1.getColumnOffset(), 1); assertEquals(col1.getColumnType(), Byte.class); assertSame(Byte.class.cast(col1.getMin()), (byte) 0); assertSame(Byte.class.cast(col1.getMax()) - Byte.MAX_VALUE, 0); ByteColumn col2 = new ByteColumn("name", 1, (byte) 1, (byte) 2); assertEquals(col2.getColumnName(), "name"); assertEquals(col2.getColumnOffset(), 1); assertEquals(col2.getColumnType(), Byte.class); assertSame(Byte.class.cast(col2.getMin()), (byte) 1); assertSame(Byte.class.cast(col2.getMax()), (byte) 2); // initialize short column and check min, max ShortColumn col3 = new ShortColumn("name", 2); assertEquals(col3.getColumnName(), "name"); assertEquals(col3.getColumnOffset(), 2); assertEquals(col3.getColumnType(), Short.class); assertSame(Short.class.cast(col3.getMin()), (short) 0); assertSame(Short.class.cast(col3.getMax()) - Short.MAX_VALUE, 0); ShortColumn col4 = new ShortColumn("name", 2, (short) 10, (short) 100); assertEquals(col4.getColumnName(), "name"); assertEquals(col4.getColumnOffset(), 2); assertEquals(col4.getColumnType(), Short.class); assertSame(Short.class.cast(col4.getMin()), (short) 10); assertSame(Short.class.cast(col4.getMax()), (short) 100); IntColumn col5 = new IntColumn("name", 3); assertEquals(col5.getColumnName(), "name"); assertEquals(col5.getColumnOffset(), 3); assertEquals(col5.getColumnType(), Integer.class); assertSame(Integer.class.cast(col5.getMin()), 0); assertSame(Integer.class.cast(col5.getMax()) - Integer.MAX_VALUE, 0); IntColumn col6 = new IntColumn("name", 3, 10, 100); assertEquals(col6.getColumnName(), "name"); assertEquals(col6.getColumnOffset(), 3); assertEquals(col6.getColumnType(), Integer.class); assertSame(Integer.class.cast(col6.getMin()), 10); assertSame(Integer.class.cast(col6.getMax()), 100); LongColumn col7 = new LongColumn("name", 4); assertEquals(col7.getColumnName(), "name"); assertEquals(col7.getColumnOffset(), 4); assertEquals(col7.getColumnType(), Long.class); assertSame(Long.class.cast(col7.getMin()), (long) 0); assertSame(Long.class.cast(col7.getMax()) - Long.MAX_VALUE, (long) 0); LongColumn col8 = new LongColumn("name", 4, 10, 100); assertEquals(col8.getColumnName(), "name"); assertEquals(col8.getColumnOffset(), 4); assertEquals(col8.getColumnType(), Long.class); assertSame(Long.class.cast(col8.getMin()), (long) 10); assertSame(Long.class.cast(col8.getMax()), (long) 100); } @Test public void testWrongOffset() { try { new ByteColumn("name", -1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("Wrong offset")); } try { new ShortColumn("name", -1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("Wrong offset")); } try { new IntColumn("name", -1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("Wrong offset")); } try { new LongColumn("name", -1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("Wrong offset")); } } @Test public void testWrongMinMax() { try { new ByteColumn("name", 1, (byte) 2, (byte) 1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("is greater than")); } try { new ShortColumn("name", 1, (byte) 2, (byte) 1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("is greater than")); } try { new IntColumn("name", 1, (byte) 2, (byte) 1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("is greater than")); } try { new LongColumn("name", 1, (byte) 2, (byte) 1); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), containsString("is greater than")); } } @Test public void testEquality() { IntColumn col1 = new IntColumn("col1", 0); IntColumn col2 = new IntColumn("col1", 0); assertTrue(col1.equals(col2)); IntColumn col3 = new IntColumn("col2", 0); assertFalse(col1.equals(col3)); IntColumn col4 = new IntColumn("col1", 1); assertFalse(col1.equals(col4)); ShortColumn col5 = new ShortColumn("col1", 0); assertFalse(col1.equals(col5)); IntColumn col6 = new IntColumn("col1", 0, 10, 100); assertTrue(col1.equals(col6)); } }
35.639053
75
0.686037
50cb19bd8250fd4fc5229e00dee1035f226b3296
2,283
/* * @(#)Receipt.java 1.00 7 Oct 2016 * * Copyright (c) 2016 Michele Antonaci * * 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 com.taxy.core.model; import java.math.BigDecimal; import java.util.List; /** * Class <code>Receipt.java</code> is * * @author Michele Antonaci [email protected] * @version 1.00 7 Oct 2016 * */ public class Receipt { private List<Product> products; private BigDecimal salesTax; private BigDecimal totalPrice; public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public BigDecimal getSalesTax() { return salesTax; } public void setSalesTax(BigDecimal salesTax) { this.salesTax = salesTax; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("receipt [products="); builder.append(products); builder.append(", salesTax="); builder.append(salesTax); builder.append(", totalPrice="); builder.append(totalPrice); builder.append("]"); return builder.toString(); } }
28.5375
89
0.733684
00160ad97860d2f1ab5474ba91a326ebdd85a7ff
4,435
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Provides details on the response for a collateral proposal. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CollateralProposalResponseType1", propOrder = { "collPrpslId", "tp", "rspnTp", "rjctnRsn", "rjctnInf" }) public class CollateralProposalResponseType1 { @XmlElement(name = "CollPrpslId", required = true) protected String collPrpslId; @XmlElement(name = "Tp", required = true) @XmlSchemaType(name = "string") protected CollateralProposalResponse1Code tp; @XmlElement(name = "RspnTp", required = true) @XmlSchemaType(name = "string") protected Status4Code rspnTp; @XmlElement(name = "RjctnRsn") @XmlSchemaType(name = "string") protected RejectionReasonV021Code rjctnRsn; @XmlElement(name = "RjctnInf") protected String rjctnInf; /** * Gets the value of the collPrpslId property. * * @return * possible object is * {@link String } * */ public String getCollPrpslId() { return collPrpslId; } /** * Sets the value of the collPrpslId property. * * @param value * allowed object is * {@link String } * */ public CollateralProposalResponseType1 setCollPrpslId(String value) { this.collPrpslId = value; return this; } /** * Gets the value of the tp property. * * @return * possible object is * {@link CollateralProposalResponse1Code } * */ public CollateralProposalResponse1Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link CollateralProposalResponse1Code } * */ public CollateralProposalResponseType1 setTp(CollateralProposalResponse1Code value) { this.tp = value; return this; } /** * Gets the value of the rspnTp property. * * @return * possible object is * {@link Status4Code } * */ public Status4Code getRspnTp() { return rspnTp; } /** * Sets the value of the rspnTp property. * * @param value * allowed object is * {@link Status4Code } * */ public CollateralProposalResponseType1 setRspnTp(Status4Code value) { this.rspnTp = value; return this; } /** * Gets the value of the rjctnRsn property. * * @return * possible object is * {@link RejectionReasonV021Code } * */ public RejectionReasonV021Code getRjctnRsn() { return rjctnRsn; } /** * Sets the value of the rjctnRsn property. * * @param value * allowed object is * {@link RejectionReasonV021Code } * */ public CollateralProposalResponseType1 setRjctnRsn(RejectionReasonV021Code value) { this.rjctnRsn = value; return this; } /** * Gets the value of the rjctnInf property. * * @return * possible object is * {@link String } * */ public String getRjctnInf() { return rjctnInf; } /** * Sets the value of the rjctnInf property. * * @param value * allowed object is * {@link String } * */ public CollateralProposalResponseType1 setRjctnInf(String value) { this.rjctnInf = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
23.844086
89
0.607441
87777c6cdce2141d34b9f386034dc33486bf74ad
5,435
package it.fdepedis.quakereport.utils; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import java.net.MalformedURLException; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import androidx.core.content.ContextCompat; import it.fdepedis.quakereport.R; import it.fdepedis.quakereport.settings.EarthquakePreferences; import android.content.Context; import android.view.View; public class Utils { private static final String LOG_TAG = Utils.class.getName(); public static Context context; private static final String LIMIT = "1"; private static final String USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"; //"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=6&limit=10"; public static String refreshData(Context context){ //new EarthquakeLoader(context, uriBuilder.toString()); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); //String minMagnitude = sharedPrefs.getString(valueOf(R.string.settings_min_magnitude_key), valueOf(R.string.settings_min_magnitude_default)); String minMagnitude = sharedPrefs.getString( context.getString(R.string.settings_min_magnitude_key), context.getString(R.string.settings_min_magnitude_default)); String orderBy = sharedPrefs.getString( context.getString(R.string.settings_order_by_key), context.getString(R.string.settings_order_by_default)); String numItems = sharedPrefs.getString( context.getString(R.string.settings_num_item_key), context.getString(R.string.settings_num_item_default)); Log.d(LOG_TAG, "minMagnitude: " + minMagnitude ); Log.d(LOG_TAG, "orderBy: " + orderBy ); Log.d(LOG_TAG, "numItems: " + numItems ); Uri uriBuilder = Uri.parse(USGS_REQUEST_URL).buildUpon() .appendQueryParameter("format", "geojson") .appendQueryParameter("limit", numItems) .appendQueryParameter("minmag", minMagnitude) .appendQueryParameter("orderby", orderBy) .build(); Log.e(LOG_TAG, "uriBuilder: " + uriBuilder.toString() ); return uriBuilder.toString(); } public static URL getNotificationURLByTime(Context context) { String minMagNotification = EarthquakePreferences.getMinMagNotificationPreferences(context); // Costruisci una URL che abbia un solo elemento recente e con // una magnitudine di notifica indicata nelle preferences Uri uriBuilder = Uri.parse(USGS_REQUEST_URL).buildUpon() .appendQueryParameter("format", "geojson") .appendQueryParameter("limit", LIMIT) .appendQueryParameter("minmag", minMagNotification) .appendQueryParameter("orderby", "time") .build(); try{ URL quakeReportNotificationQueryUrlByTime = new URL(uriBuilder.toString()); Log.e(LOG_TAG, "quakeReportNotificationQueryUrlByTime: " + quakeReportNotificationQueryUrlByTime ); return quakeReportNotificationQueryUrlByTime; } catch (MalformedURLException e){ e.printStackTrace(); return null; } } public static String formatMagnitude(double magnitude) { DecimalFormat magnitudeFormat = new DecimalFormat("0.0"); return magnitudeFormat.format(magnitude); } public static String formatDate(Date dateObject) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); return dateFormat.format(dateObject); } public static String formatTime(Date dateObject) { SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); return timeFormat.format(dateObject); } public static int getMagnitudeColor(Context context, double magnitude) { int magnitudeColorResourceId; int magnitudeFloor = (int) Math.floor(magnitude); switch (magnitudeFloor) { case 0: case 1: magnitudeColorResourceId = R.color.magnitude1; break; case 2: magnitudeColorResourceId = R.color.magnitude2; break; case 3: magnitudeColorResourceId = R.color.magnitude3; break; case 4: magnitudeColorResourceId = R.color.magnitude4; break; case 5: magnitudeColorResourceId = R.color.magnitude5; break; case 6: magnitudeColorResourceId = R.color.magnitude6; break; case 7: magnitudeColorResourceId = R.color.magnitude7; break; case 8: magnitudeColorResourceId = R.color.magnitude8; break; case 9: magnitudeColorResourceId = R.color.magnitude9; break; default: magnitudeColorResourceId = R.color.magnitude10plus; break; } return ContextCompat.getColor(context, magnitudeColorResourceId); } }
37.743056
150
0.649678
b8003e63bc43efa2fdc8822540ffdc0d7f34d00f
270
package com.tvd12.ezyfoxserver.controller; import com.tvd12.ezyfoxserver.context.EzyZoneContext; import com.tvd12.ezyfoxserver.request.EzyStreamingRequest; public interface EzyStreamingController extends EzyController<EzyZoneContext, EzyStreamingRequest> { }
30
68
0.837037
96200b0a128e6434fc35cfa15cd1adada9a17308
181
package org.codelabor.example.validation.dao; import org.codelabor.example.validation.dto.PersonDto; public interface PersonDao { int insertPerson(PersonDto personDto); }
22.625
55
0.790055
f5a217caec1bb39c875bd03ac6c7c57d2c23b5c6
689
package net.brutus5000.deltaforge.api.dto; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Type; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import java.time.OffsetDateTime; import static net.brutus5000.deltaforge.api.dto.TagAssignmentDto.TYPE_NAME; @Data @EqualsAndHashCode(of = {"id", "channel", "tag"}) @ToString(of = {"id"}) @Type(TYPE_NAME) public class TagAssignmentDto { public static final String TYPE_NAME = "tagAssignment"; @Id private String id; private OffsetDateTime createdAt; private OffsetDateTime updatedAt; private ChannelDto channel; private TagDto tag; }
25.518519
75
0.769231
3222e7e36724152d028dd6179f31175e4d0feaf1
715
package com.fsmflying.study.quickstart2021; import org.junit.Test; import java.io.FileNotFoundException; import static org.junit.Assert.assertTrue; /** * Unit test for simple App. */ public class PathUtilsTest { /** * Rigorous Test :-) */ @Test public void shouldAnswerWithTrue() { assertTrue(true); } @Test public void test01() { try { System.out.println(PathUtils.getResourcePath("csdn.10.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(PathUtils.getTestResourcePath("csdn.10.txt")); System.out.println(PathUtils.getRelativeResourcePath("csdn.10.txt")); } }
22.34375
77
0.634965
714ce7c8b827ecd0af7c360e7abf9f76a8b738f9
1,620
package com.github.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * before(前置通知): 在方法开始执行前执行 * after(后置通知): 在方法执行后执行 * afterReturning(返回后通知): 在方法返回后执行 * afterThrowing(异常通知): 在抛出异常时执行 * around(环绕通知): 在方法执行前和执行后都会执行 */ @Aspect @Component public class LogAspect { private final Logger logger = LoggerFactory.getLogger(LogAspect.class); //1.定义切点 @Pointcut(value = "@annotation(com.github.annotation.Log)")//切入点描述 这个是controller包的切入点 public void pointcut(){}//签名,可以理解成这个切入点的一个名称 @Before("pointcut()") public void beginTransaction() { System.out.println("before beginTransaction"); } @After("pointcut()") public void commit() { System.out.println("after commit"); } @AfterReturning(value = "pointcut()", returning = "returnObject") public void afterReturning(JoinPoint joinPoint, Object returnObject) { System.out.println("afterReturning"); } @AfterThrowing("pointcut()") public void afterThrowing() { System.out.println("afterThrowing afterThrowing rollback"); } @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { try { System.out.println("around"); return joinPoint.proceed(); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { System.out.println("around"); } } }
27.457627
89
0.666667
5101413372708e7dfbb101622462a83589100dbe
2,394
package com.iovation.launchkey.sdk.integration.steps; import com.google.inject.Inject; import com.iovation.launchkey.sdk.domain.DirectoryUserTotp; import com.iovation.launchkey.sdk.integration.managers.DirectoryTotpManager; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class DirectoryTotpSteps { private final DirectoryTotpManager directoryTotpManager; @Inject public DirectoryTotpSteps(DirectoryTotpManager directoryTotpManager) { this.directoryTotpManager = directoryTotpManager; } @Given("I have created a User TOTP") @When("I make a User TOTP create request") public void iMakeAUserTOTPCreateRequest() throws Throwable { directoryTotpManager.generateUserTotp(); } @Then("the User TOTP create response contains a valid algorithm") public void theUserTOTPCreateResponseContainsForTheAlgorithm() throws Throwable { String actual = directoryTotpManager.getCurrentGenerateUserTotpResponse().getAlgorithm(); List<String> validAlgorithms = Arrays.asList("SHA1", "SHA256", "SHA512"); assertTrue(validAlgorithms.contains(actual)); } @Then("the User TOTP create response contains a valid amount of digits") public void theUserTOTPCreateResponseContainsAValidAmountOfDigits() throws Throwable { int actual = directoryTotpManager.getCurrentGenerateUserTotpResponse().getDigits(); assertTrue(actual >= 6); } @Then("the User TOTP create response contains a valid period") public void theUserTOTPCreateResponseContainsForThePeriod() throws Throwable { int actual = directoryTotpManager.getCurrentGenerateUserTotpResponse().getPeriod(); assertTrue(actual >= 30); } @Then("the User TOTP create response contains a valid secret") public void theUserTOTPCreateResponseContainsAValidSecret() throws Throwable { DirectoryUserTotp response = directoryTotpManager.getCurrentGenerateUserTotpResponse(); String actual = response.getSecret(); assertNotNull(actual); assertEquals(32, actual.length()); } @When("I make a User TOTP delete request") public void iMakeAUserTOTPDeleteRequest() throws Throwable { directoryTotpManager.removeTotpCodeForUser(); } }
39.245902
97
0.75188
30b1794d897450865fb7093777d7f8a3f0f5e62a
855
package org.bayofmany.jsonschema.compiler; import java.net.URI; import java.net.URISyntaxException; public class Util { public static String upperCaseFirst(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } public static URI uri(String value) { try { return new URI(value); } catch (URISyntaxException e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid URI: " + value); } } public static URI uri(URI parent, String relative) { if (!relative.startsWith("/")) { relative = "/" + relative; } if (parent.toString().contains("#")) { return uri(parent.toString() + relative); } else { return uri(parent.toString() + "#" + relative); } } }
25.909091
72
0.573099
6dc4df069ac80fb700d213a588e24cdc924702aa
1,057
package seedu.address.logic.commands; import static seedu.address.logic.commands.EmployeeCommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.ResetEmployeeSortCommand.SHOWING_RESET_MESSAGE; import static seedu.address.testutil.TypicalEmployees.getTypicalRhrhEmployees; import org.junit.jupiter.api.Test; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.Rhrh; import seedu.address.model.UserPrefs; import seedu.address.model.person.employee.EmployeeComparator; public class ResetEmployeeSortCommandTest { private final Model model = new ModelManager(getTypicalRhrhEmployees(), new UserPrefs()); @Test public void execute_sortsByNameAscending_success() { Model expectedModel = new ModelManager(new Rhrh(model.getRhrh()), new UserPrefs()); expectedModel.getSortableEmployeeList().sort(EmployeeComparator.getDefaultComparator()); assertCommandSuccess(new ResetEmployeeSortCommand(), model, SHOWING_RESET_MESSAGE, expectedModel); } }
39.148148
106
0.812677
83d78d0d3fa5ae94aa2484ed55444093e5929d71
349
package com.lf.gmall.wms.mapper; import com.lf.gmall.wms.entity.WareSkuEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品库存 * * @author lf * @email [email protected] * @date 2021-04-01 20:33:08 */ @Mapper public interface WareSkuMapper extends BaseMapper<WareSkuEntity> { }
19.388889
66
0.747851
1983aeb1269b3b837e25ebcf7d367e725474ace1
787
package com.base.nguyencse.java.network.api; import com.base.nguyencse.java.network.ApiCall; import com.base.nguyencse.java.network.ApiCallback; import com.base.nguyencse.java.network.ApiClient; import com.base.nguyencse.java.network.BaseNetworkApi; import com.base.nguyencse.java.network.response.DummyResponse; public class GetDummyApi extends BaseNetworkApi<DummyResponse> { private int page; private int num; public GetDummyApi(int page, int num) { this.page = page; this.num = num; } @Override protected ApiCall<DummyResponse> getApiCall() { return ApiClient.getInstance().getApiService().getDummyList(page, num); } public void requestData(ApiCallback<DummyResponse> apiCallback) { request(apiCallback); } }
28.107143
79
0.734435
92c665d63ec001cd09f26baad336ae7c9414f05c
1,652
package com.msdemo.v2.common.dtx.lock; import java.util.List; import com.msdemo.v2.common.exception.TransException; import com.msdemo.v2.common.lock.model.ResourceLock.LockLevel; public interface ITxnLockAgent { default void lock(String locker,String[] resourceIds,LockLevel level,int timeout){ for (String key:resourceIds){ lock(locker,key,level,timeout); } } //lock locally UnlockInfo lock(String locker,String resourceId,LockLevel level,int timeoutMillis) throws TxnLockException; void relock(UnlockInfo unlockInfo,int timeoutMillis) throws TxnLockException; //unlock locally or remotely void unlock(UnlockInfo unlockInfo); void unlock(List<UnlockInfo> unlockInfoList); void asyncUnlock(List<String> unlockInfoList); UnlockInfo buildUnlockInfo(String locker,String resourceId); public static class UnlockInfo{ public String sourceApplication; public String targetApplication; public String locker; public String resourceId; public int retryCount; } public static class TxnLockException extends TransException{ private static final long serialVersionUID = -3120434560340894147L; private static final String FAILED_MSM="resource: '%s', locker: '%s' failed"; public static final String LOCK_FAILED="0100"; public static final String UNLOCK_FAILED="0101"; public static final String RELOCK_FAILED="0101"; public TxnLockException(String code,String locker,String resourceId){ super(code,String.format(FAILED_MSM,resourceId,locker)); } public TxnLockException(String code,String locker,String resourceId, Exception e){ super(code,String.format(FAILED_MSM,resourceId,locker),e); } } }
33.714286
108
0.788741
32de67d7f30c129c0ade44567a21d82bc6b05f4c
2,016
package com.pard.modules.sys.controller; import com.pard.common.controller.GenericController; import com.pard.common.utils.StringUtils; import com.pard.modules.sys.entity.Area; import com.pard.modules.sys.entity.Office; import com.pard.modules.sys.service.OfficeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * Created by wawe on 17/5/22. */ @Controller @RequestMapping(value = "${adminPath}/sys/office") public class OfficeController extends GenericController { @Autowired private OfficeService officeService; @ModelAttribute public Office get(@RequestParam(required = false) String id) { Office office; if (StringUtils.isNotBlank(id)) { office = officeService.findOne(id); if (office != null) { if (office.getParent() == null) { office.setParent(new Office("0")); } if (office.getArea() == null) { office.setArea(new Area()); } return office; } } office = new Office(); office.setParent(new Office("0")); office.setArea(new Area()); return office; } @PreAuthorize("hasAuthority('sys:office:view')") @RequestMapping(value = {"list", ""}) public String list(Model model) { return "modules/sys/officeList"; } @PreAuthorize("hasAnyAuthority('sys:office:view', 'sys:office:add', 'sys:office:edit')") @RequestMapping(value = "form") public String form(Office office, Model model) { model.addAttribute("office", office); return "modules/sys/officeForm"; } }
34.169492
92
0.663194
feb569373505fa5552862dcc941fcd8042c68c6d
548
package testjava; import static org.junit.Assert.*; import org.junit.Test; import org.uqbarproject.jpa.java8.extras.WithGlobalEntityManager; import org.uqbarproject.jpa.java8.extras.test.AbstractPersistenceTest; public class ContextTest extends AbstractPersistenceTest implements WithGlobalEntityManager { @Test public void contextUp() { assertNotNull(entityManager()); } @Test public void contextUpWithTransaction() throws Exception { withTransaction(() -> {}); } //levanta el hibernate y revisa la configuracion de datos }
21.076923
93
0.781022
0ca8ca572212b39d83615fdf5da4d77c4a18e56c
644
package net.oswin.exercises.oop.inheritance; /** * Треугольник */ public class Triangle extends Shape { private int side1; private int side2; private double angle; public Triangle(int side1, int side2, double angle) { this.side1 = side1; this.side2 = side2; this.angle = angle; } @Override public double getSquare() { return side1 * side2 * Math.sin(angle * Math.PI / 180) / 2; } @Override public double getPerimeter() { return side1 + side2 + Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2) - 2 * side1 * side2 * Math.cos(angle * Math.PI / 180)); } }
23.851852
136
0.608696
f39afe8468f315c8987ca5150f48909791cac39c
1,122
package com.santiagolizardo.jerba.utilities; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.CacheFactory; import javax.cache.CacheManager; import com.google.appengine.api.memcache.jsr107cache.GCacheFactory; public class CacheSingleton { private static final int MINUTE = 60; private static final int HOUR = MINUTE * 60; private static final Logger LOGGER = Logger.getLogger(CacheSingleton.class .getName()); private static CacheSingleton singleton; public static CacheSingleton getInstance() { if (singleton == null) singleton = new CacheSingleton(); return singleton; } private Cache cache; private CacheSingleton() { Map<String, Object> props = new HashMap<>(); props.put(GCacheFactory.EXPIRATION_DELTA, HOUR * 8); try { CacheFactory cacheFactory = CacheManager.getInstance() .getCacheFactory(); cache = cacheFactory.createCache(props); } catch (CacheException e) { LOGGER.severe(e.getMessage()); } } public Cache getCache() { return cache; } }
22.44
75
0.746881
eb4240072a143a16fad2d9414cc4006d27b584ba
3,610
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 leap.orm.metadata; import leap.lang.Args; import leap.lang.Strings; import leap.lang.exception.ObjectExistsException; import leap.orm.sql.SqlCommand; import leap.orm.sql.SqlFragment; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DefaultSqlRegistry implements SqlRegistry { protected final Map<String, SqlFragment> fragmentsMap = new ConcurrentHashMap<>(); protected final Map<String, TypedCommands> commandsMap = new ConcurrentHashMap<>(); @Override public void addSqlFragment(String key, SqlFragment fragment) throws ObjectExistsException { Args.notEmpty(key,"fragment key"); Args.notNull(fragment,"sql fragment"); if(fragmentsMap.containsKey(key)){ throw new ObjectExistsException("The sql fragment '" + key + "' already exists"); } fragmentsMap.put(key, fragment); } @Override public SqlFragment tryGetSqlFragment(String key) { return fragmentsMap.get(key); } @Override public void addSqlCommand(String key, String dbType, SqlCommand cmd) throws ObjectExistsException { TypedCommands commands = commandsMap.get(key); if(null == commands) { commands = new TypedCommands(); commandsMap.put(key, commands); } if(Strings.isEmpty(dbType)) { if(null != commands.untyped) { throw new ObjectExistsException("The sql command '" + key + "' already exists!"); } commands.untyped = cmd; }else { if(commands.typed.containsValue(dbType.toLowerCase())) { throw new ObjectExistsException("The sql command '" + key + "' for db type '" + dbType + "' already exists!"); } commands.typed.put(dbType.toLowerCase(), cmd); } } @Override public SqlCommand tryGetSqlCommand(String key, String dbType) { TypedCommands commands = commandsMap.get(key); if(null == commands) { return null; } if(Strings.isEmpty(dbType)) { return commands.untyped; }else { SqlCommand command = commands.typed.get(dbType.toLowerCase()); if(null == command) { command = commands.untyped; } return command; } } @Override public SqlCommand removeSqlCommand(String key, String dbType) { TypedCommands commands = commandsMap.get(key); if(null == commands) { return null; } if(Strings.isEmpty(dbType)) { SqlCommand command = commands.untyped; commands.untyped = null; return command; }else { return commands.typed.remove(dbType.toLowerCase()); } } protected static final class TypedCommands { SqlCommand untyped; Map<String, SqlCommand> typed = new HashMap<>(); } }
32.818182
126
0.633795
c19eb69cc6cd174e383bc9490421319163b6dc0a
1,566
package com.markly.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * todo * * @author hq * @date 2021-05-21 */ @ConditionalOnProperty(name = "swagger.enable", havingValue = "true") public class Swagger2 { // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等 @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.markly")).paths(PathSelectors.any()) .build(); } // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() // 页面标题 .title("Spring Boot 测试使用 Swagger2 构建RESTful API") // 创建人信息 .contact(new Contact("MrZhang", "https://www.cnblogs.com/zs-notes/category/1258467.html", "[email protected]")) // 版本号 .version("1.0") // 描述 .description("API 描述") .build(); } }
32.625
127
0.653257
34f1d788377b37b59a9a78d7b56e0177d359ba75
201
package com.chdlsp.alice.interfaces.vo; import lombok.*; @Builder @NoArgsConstructor @AllArgsConstructor @Data public class KakaoUserInfoVO { String id; String email; String nickname; }
13.4
39
0.746269
db65a097fe25929b70f2e52be5707f666a8f7953
2,877
package mb.spoofax.lwb.eclipse.dynamicloading; import mb.cfg.CompileLanguageInput; import mb.cfg.CompileLanguageInputCustomizer; import mb.cfg.CompileLanguageSpecificationInputBuilder; import mb.cfg.CompileLanguageSpecificationShared; import mb.spoofax.compiler.adapter.AdapterProject; import mb.spoofax.compiler.adapter.AdapterProjectCompilerInputBuilder; import mb.spoofax.compiler.language.LanguageProject; import mb.spoofax.compiler.language.LanguageProjectCompilerInputBuilder; import mb.spoofax.compiler.platform.EclipseProjectCompiler; import mb.spoofax.compiler.util.Shared; import java.util.Optional; public class DynamicCompileLanguageInputCustomizer implements CompileLanguageInputCustomizer { @Override public void customize(Shared.Builder builder) { } @Override public void customize(LanguageProject.Builder builder) { } @Override public void customize(LanguageProjectCompilerInputBuilder baseBuilder) { } @Override public void customize(CompileLanguageSpecificationShared.Builder builder) { } @Override public void customize(CompileLanguageSpecificationInputBuilder languageCompilerInputBuilder) { } @Override public void customize(AdapterProject.Builder builder) { } @Override public void customize(AdapterProjectCompilerInputBuilder adapterBuilder) { } @Override public boolean customize(EclipseProjectCompiler.Input.Builder builder) { // Override several identifiers to `spoofax.lwb.eclipse.dynamicloading.*` versions, as their own implementations // are not available when dynamically loaded. builder.baseMarkerId("spoofax.lwb.eclipse.dynamicloading.marker"); builder.infoMarkerId("spoofax.lwb.eclipse.dynamicloading.marker.info"); builder.warningMarkerId("spoofax.lwb.eclipse.dynamicloading.marker.warning"); builder.errorMarkerId("spoofax.lwb.eclipse.dynamicloading.marker.error"); builder.contextId("spoofax.lwb.eclipse.dynamicloading.context"); builder.runCommandId("spoofax.lwb.eclipse.dynamicloading.runcommand"); builder.natureRelativeId(DynamicNature.relativeId); builder.natureId(DynamicNature.id); builder.addNatureCommandId("spoofax.lwb.eclipse.dynamicloading.nature.add"); builder.removeNatureCommandId("spoofax.lwb.eclipse.dynamicloading.nature.remove"); builder.toggleCommentCommandId("spoofax.lwb.eclipse.dynamicloading.togglecomment"); builder.projectBuilderRelativeId(DynamicProjectBuilder.relativeId); builder.projectBuilderId(DynamicProjectBuilder.id); return true; } @Override public Optional<EclipseProjectCompiler.Input.Builder> getDefaultEclipseProjectInput() { return Optional.of(EclipseProjectCompiler.Input.builder()); } @Override public void customize(CompileLanguageInput.Builder builder) { } }
39.958333
120
0.78415
78cd8212b6ba387066a9feef7a8fe19aee8a97cd
4,355
package com.pj.squashrestapp.dto.scoreboard; import com.pj.squashrestapp.dto.BonusPointsAggregatedForSeason; import com.pj.squashrestapp.dto.PlayerDto; import com.pj.squashrestapp.util.RoundingUtil; import java.math.BigDecimal; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.UUID; import lombok.EqualsAndHashCode; import lombok.Getter; /** */ @Getter @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class SeasonScoreboardRowDto implements Comparable<SeasonScoreboardRowDto> { @EqualsAndHashCode.Include private final PlayerDto player; private final Map<Integer, Integer> roundNumberToXpMapAll; private final Map<Integer, Integer> roundNumberToXpMapPretenders; private final int bonusPoints; private BigDecimal average; private int attendices; private int totalPoints; private int countedPoints; private int countedPointsPretenders; private int eightBestPoints; private int pointsWon; private int pointsLost; private int pointsBalance; private int setsWon; private int setsLost; private int setsBalance; private int matchesWon; private int matchesLost; private int matchesBalance; public SeasonScoreboardRowDto( final PlayerDto player, final BonusPointsAggregatedForSeason bonusPointsAggregatedForSeason) { this.player = player; this.roundNumberToXpMapAll = new HashMap<>(); this.roundNumberToXpMapPretenders = new HashMap<>(); final UUID currentPlayerUuid = player.getUuid(); this.bonusPoints = bonusPointsAggregatedForSeason.forPlayer(currentPlayerUuid); } public static double getAverageAsDouble(final SeasonScoreboardRowDto seasonScoreboardRowDto) { return (double) seasonScoreboardRowDto.totalPoints / seasonScoreboardRowDto.attendices; } public void addXpForRound(final int roundNumber, final Integer xpEarned) { this.roundNumberToXpMapAll.put(roundNumber, xpEarned); } public void addXpForRoundPretendents(final int roundNumber, final Integer xpEarned) { this.roundNumberToXpMapPretenders.put(roundNumber, xpEarned); } public void calculateFinishedRow(final int countedRounds) { final int totalPointsForRounds = getTotalPointsForRounds(roundNumberToXpMapAll); this.totalPoints = totalPointsForRounds + bonusPoints; final int numberOfRoundsThatCount = countedRounds; final int countedPointsForRounds = getPointsForNumberOfRounds(roundNumberToXpMapAll, numberOfRoundsThatCount); this.countedPointsPretenders = getPointsForNumberOfRounds(roundNumberToXpMapPretenders, numberOfRoundsThatCount); final int eightBestPointsForRounds = getPointsForNumberOfRounds(roundNumberToXpMapAll, 8); this.countedPoints = countedPointsForRounds + bonusPoints; this.eightBestPoints = eightBestPointsForRounds + bonusPoints; this.attendices = roundNumberToXpMapAll.size(); this.average = RoundingUtil.round((float) totalPoints / attendices, 1); } private int getTotalPointsForRounds(final Map<Integer, Integer> roundNumberToXpMap) { return roundNumberToXpMap.values().stream().mapToInt(points -> points).sum(); } private int getPointsForNumberOfRounds( final Map<Integer, Integer> roundNumberToXpMap, final int numberOfRounds) { return roundNumberToXpMap.values().stream() .sorted(Comparator.reverseOrder()) .limit(numberOfRounds) .mapToInt(points -> points) .sum(); } @Override public int compareTo(final SeasonScoreboardRowDto that) { return Comparator.comparingInt(SeasonScoreboardRowDto::getCountedPoints) .thenComparingInt(SeasonScoreboardRowDto::getTotalPoints) .thenComparingDouble(SeasonScoreboardRowDto::getAverageAsDouble) .reversed() .compare(this, that); } public void addScoreboardRow(final RoundGroupScoreboardRow scoreboardRow) { this.pointsWon += scoreboardRow.getPointsWon(); this.pointsLost += scoreboardRow.getPointsLost(); this.pointsBalance += scoreboardRow.getPointsBalance(); this.setsWon += scoreboardRow.getSetsWon(); this.setsLost += scoreboardRow.getSetsLost(); this.setsBalance += scoreboardRow.getSetsBalance(); this.matchesWon += scoreboardRow.getMatchesWon(); this.matchesLost += scoreboardRow.getMatchesLost(); this.matchesBalance += scoreboardRow.getMatchesBalance(); } }
36.90678
100
0.779334
e34cfee577540e587fb2a77a6746608f853875a3
706
package com.movit.rwe.modules.bi.base.entity.hive; /** * * @Project : az-rwe-bi-web * @Title : TherapeuticArea.java * @Package com.movit.rwe.common.entity * @Description : 治疗领域 * @author Yuri.Zheng * @email [email protected] * @date 2016年3月1日 下午1:45:14 * */ public class TherapeuticArea { private String guid; private String name; private String code; public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
14.708333
50
0.664306
f0217bde60b32576a658627023a4b4c3cfea079c
1,290
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("iz") @Implements("HorizontalAlignment") public enum HorizontalAlignment implements Enumerated { @ObfuscatedName("q") @ObfuscatedSignature( signature = "Liz;" ) field3461(0, 0), @ObfuscatedName("w") @ObfuscatedSignature( signature = "Liz;" ) @Export("HorizontalAlignment_centered") HorizontalAlignment_centered(2, 1), @ObfuscatedName("e") @ObfuscatedSignature( signature = "Liz;" ) field3460(1, 2); @ObfuscatedName("p") @ObfuscatedGetter( intValue = 1984645021 ) @Export("value") public final int value; @ObfuscatedName("k") @ObfuscatedGetter( intValue = -2141408149 ) @Export("id") final int id; HorizontalAlignment(int var3, int var4) { this.value = var3; this.id = var4; } @ObfuscatedName("e") @ObfuscatedSignature( signature = "(I)I", garbageValue = "320353268" ) @Export("rsOrdinal") public int rsOrdinal() { return this.id; } @ObfuscatedName("q") @ObfuscatedSignature( signature = "(I)I", garbageValue = "-71692752" ) static int method4701() { return ++Messages.Messages_count - 1; } }
20.15625
55
0.720155
76dcfef8ed8848f7f65304e0efb2210f4a4d3566
820
package com.leyou.user.api; import com.leyou.user.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; //@FeignClient(value = "user-service",path = "api/user") @FeignClient(value = "user-service",path = "api/user/inner") public interface UserApi { @GetMapping("queryUserByUsernameAndPassword") public User queryUserByUsernameAndPassword( @RequestParam(value = "username") String username, @RequestParam(value = "password") String password ); @GetMapping("queryUserByUsername") public User queryUserByUsername( @RequestParam(value = "username") String username ); }
34.166667
62
0.74878
1dc2501fca4ec5f2dd35cf14d12b3c6401d7f276
1,036
/* * Copyright (c) 2020. 代码由Cyberhan编写,不保证其准确性,仅供参考。 * 注意:代码不可进行商业用途,本项目遵寻Apache 2.0开源协议。 * 本人有权对开源协议进行修改和更换。 */ package cn.hselfweb.webpub.webpubmiddleware.utils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; /** * 静态数据配置 */ public class StaticData { //代理转发基本URl public static String BASE_URl = "http://127.0.0.1:8888"; //基本Http请求头 @NotNull public static HttpEntity<String> Get_Entity() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<String>(headers); } //带有body的 @NotNull @Contract("_ -> new") public static <T> HttpEntity<T> Get_Enitity_withBody(T t) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<T>(t, headers); } }
25.9
63
0.706564
2a14ccd10897a6aabd6da09ffd0545750c2d2327
1,332
package org.bukkit.block.data.type; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Waterlogged; import org.jetbrains.annotations.NotNull; /** * This class encompasses the 'north', 'east', 'south', 'west', height flags * which are used to set the height of a wall. * * 'up' denotes whether the well has a center post. */ public interface Wall extends Waterlogged { /** * Gets the value of the 'up' property. * * @return the 'up' value */ boolean isUp(); /** * Sets the value of the 'up' property. * * @param up the new 'up' value */ void setUp(boolean up); /** * Gets the height of the specified face. * * @param face to check * @return if face is enabled */ @NotNull Height getHeight(@NotNull BlockFace face); /** * Set the height of the specified face. * * @param face to set * @param height the height */ void setHeight(@NotNull BlockFace face, @NotNull Height height); /** * The different heights a face of a wall may have. */ public enum Height { /** * No wall present. */ NONE, /** * Low wall present. */ LOW, /** * Tall wall present. */ TALL; } }
20.8125
76
0.555556
987346983ca6bd94ac7cf0c702373d0920fa1fd4
1,147
package forms; import java.security.NoSuchAlgorithmException; import com.avaje.ebean.Model.Finder; import models.User; import play.data.validation.Constraints; /** * Formのコンストラクタに渡されると、実際にフォームをPOSTする前に、 * このvalidate()メソッドを実行し、ユーザ/パスワードの組み合わせが正しいかどうかを判断してくれる * * @author yu-yama * */ public class LoginForm { @Constraints.Required private String username; @Constraints.Required private String password; // クエリを作成する為のfindヘルパー public static Finder<Long, User> user = new Finder<>(User.class); public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String validate() throws NoSuchAlgorithmException { if (authenticate(username, password) == null) { return "Invalid user or password"; } return null; } public static User authenticate(String username, String password) throws java.security.NoSuchAlgorithmException { return user.where().eq("username", username).eq("password", password).findUnique(); } }
20.854545
114
0.74891
e9930cded1ae361bddf01a16629355b30f4e2363
2,292
/* * (C) Copyright 2020 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * Anahide Tchertchian */ package org.nuxeo.ecm.automation.server; import org.nuxeo.common.xmap.Context; import org.nuxeo.common.xmap.XAnnotatedObject; import org.nuxeo.common.xmap.registry.MapRegistry; import org.nuxeo.ecm.automation.core.Constants; import org.nuxeo.runtime.logging.DeprecationLogger; import org.w3c.dom.Element; /** * Registry to handle specific id on chains as well as disablement. * * @since 11.5 */ public class RestBindingRegistry extends MapRegistry { @Override protected String computeId(Context ctx, XAnnotatedObject xObject, Element element) { // generate the new instance in all cases, to check if this is a chain RestBinding ob = (RestBinding) xObject.newInstance(ctx, element); String name = ob.name; // adjust id return ob.chain ? Constants.CHAIN_ID_PREFIX + name : name; } @Override protected Boolean shouldEnable(Context ctx, XAnnotatedObject xObject, Element element, String extensionId) { // handle deprecated disablement if (element.hasAttribute("disabled")) { String message = String.format( "Usage of the \"disabled\" attribute on RestBinding contribution '%s'," + " in extension '%s', is deprecated: use the \"enable\" attribute instead.", computeId(ctx, xObject, element), extensionId); DeprecationLogger.log(message, "11.5"); RestBinding ob = (RestBinding) xObject.newInstance(ctx, element); return !ob.isDisabled; } return super.shouldEnable(ctx, xObject, element, extensionId); } }
38.2
112
0.688045
cf05e641cad1737d98ec6c45c1ea38bc0ac041e9
396
package com.esceer.sdw.repository; import com.esceer.sdw.model.Sensor; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SensorRepository extends MongoRepository<Sensor, String> { Optional<Sensor> findByName(String name); boolean existsByName(String name); }
24.75
75
0.813131
f4d4ed0326f0742815de8d6f23af34f1ed4259b8
5,099
package com.leetcode.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.leetcode.common.PageReqBody; import com.leetcode.model.discuss.DiscussTopics; import com.leetcode.model.discuss.Topic; import com.leetcode.model.discuss.TopicReqBody; import com.leetcode.model.response.APIResponse; import com.leetcode.service.DiscussService; import com.leetcode.util.ImageUtil; import org.apache.http.entity.StringEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import static com.leetcode.util.CommonUtil.*; import static com.leetcode.util.HttpUtil.getErrorIfFailed; import static com.leetcode.util.HttpUtil.post; import static com.leetcode.util.RequestParamUtil.*; @Service public class DiscussServiceImpl implements DiscussService { private static final Logger LOGGER = LoggerFactory.getLogger(DiscussServiceImpl.class); private static final String UPDATE_TOPIC_OPERATION = "updateTopic"; private static final String CREATE_TOPIC_OPERATION = "createTopicForQuestion"; private static final String DELETE_TOPIC_OPERATION = "deleteTopic"; private static final String UPLOAD_IMAGE_URL = "https://leetcode.com/storage/upload/image"; private static final String PROBLEM_REFER = "https://leetcode.com/problems/"; @Override public APIResponse getTopics(PageReqBody req) { APIResponse errorStatus = checkPageParam(req); if (errorStatus != null) return errorStatus; StringEntity requestBody = buildDiscussReqBody(req); // CookieStore cookieStore = getCookies(req.getUri()); String res = post(requestBody); APIResponse error = getErrorIfFailed(res); if (error != null) return error; JSONObject j = JSONObject.parseObject(res).getJSONObject("data"); j = j.getJSONObject("questionTopicsList"); DiscussTopics topicsList = JSON.parseObject(j.toString(), DiscussTopics.class); return new APIResponse(topicsList); } @Override public APIResponse getTopic(int topicId, String cookies) { // CookieStore cookieStore = getCookies(problemUri); StringEntity body = buildDiscussTopicsReqBody(topicId); String res = post(body, cookies); APIResponse error = getErrorIfFailed(res); if (error != null) return error; JSONObject j = JSONObject.parseObject(res); j = j.getJSONObject("data").getJSONObject("topic"); Topic topic = JSON.parseObject(j.toString(), Topic.class); return new APIResponse(topic); } @Override public APIResponse createTopic(TopicReqBody req) { APIResponse error = checkParams(req, CREATE_TOPIC_OPERATION); if (error != null) return error; StringEntity entity = buildCreateTopicReqBody(req); return topicPost(req, entity, CREATE_TOPIC_OPERATION); } @Override public APIResponse updateTopic(TopicReqBody req) { APIResponse error = checkParams(req, UPDATE_TOPIC_OPERATION); if (error != null) return error; StringEntity entity = buildUpdateTopicReqBody(req); return topicPost(req, entity, UPDATE_TOPIC_OPERATION); } @Override public APIResponse deleteTopic(TopicReqBody req) { APIResponse error = checkParams(req, DELETE_TOPIC_OPERATION); if (error != null) return error; StringEntity requestBody = buildDeleteTopicReqBody(req); return topicPost(req, requestBody, DELETE_TOPIC_OPERATION); } @Override public APIResponse uploadImage(String cookies, MultipartFile file) { APIResponse cookieStatus = checkCookie(cookies); if (cookieStatus != null) return cookieStatus; try { return ImageUtil.upload(UPLOAD_IMAGE_URL, PROBLEM_REFER, cookies, file); } catch (IOException e) { LOGGER.error("IOException ", e); } return new APIResponse(500, "Upload failure. Please try again"); } private APIResponse topicPost(TopicReqBody req, StringEntity entity, String operation) { String res = post(req.getUri(), req.getCookies(), entity); APIResponse e; if ((e = getErrorIfFailed(res)) != null) return e; return getResponseStatus(operation, res); } private APIResponse checkParams(TopicReqBody req, String operation) { if (!isCookieValid(req.getCookies())) { return new APIResponse(400, "User cookie is invalid"); } if (req.getId() == null) { return new APIResponse(400, "Id is required"); } if (StringUtils.isEmpty(req.getTitle()) && !operation.equals(DELETE_TOPIC_OPERATION)) { return new APIResponse(400, "Title is required"); } if (StringUtils.isEmpty(req.getContent()) && !operation.equals(DELETE_TOPIC_OPERATION)) { return new APIResponse(400, "Content is required"); } return null; } }
41.455285
97
0.705432
12b80c84c45d8d157b0f95e04999f5a81417e6cd
814
public class codigodelpseudocodigo { public static void main(String[] args){ //Inicio //0) Creación de Variables //tipo nombre; int areadelcuadrado; int ladoadelcuadrado; //1) Leemos el tamaño del valor de lado A del cuadrado ladoadelcuadrado=3; //2) Tenemos el tipo de figura que es cuadrado //3) Tenemos la fórmula del cálculo del área //4) Calcular Área del Cuadrado: //4) Area = (valor de lado A del cuadrado) * (valor de lado A del cuadrado) areadelcuadrado=ladoadelcuadrado*ladoadelcuadrado; //5) Mostrar mensaje el "Area es" System.out.println("Area del cuadrado es:"); //5) Mostrar el valor de Area System.out.println(areadelcuadrado); // Fin } }
31.307692
87
0.608108
b6c26e454d53d3ab3bfc64c94dca40b80ca2908a
2,743
/* * Copyright 2016 The Error Prone 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 com.google.errorprone.fixes; import com.google.common.collect.ImmutableList; /** * Helper class for accumulating a branching tree of alternative fixes designed to help build as set * of potential fixes with different options in them. * * <p>Consider building a list of fixes from a set of operations A followed by B or C then D or E. * The resulting list should be ABD, ACD, ABE, ACE. * * <pre>{@code * BranchedSuggestedFixes a = BranchedSuggestedFixes.builder() * .startWith(A) * .then() * .addOption(B) * .addOption(C) * .then() * .addOption(D) * .addOption(E) * .build(); * }</pre> * * This class assumes that in order to build a valid set of fixes you must make some progress at * each branch. So two calls to branch with no merges in between will result in an empty list of * fixes at the end. * * @author [email protected] (Andrew Rice) */ public class BranchedSuggestedFixes { private final ImmutableList<SuggestedFix> fixes; private BranchedSuggestedFixes(ImmutableList<SuggestedFix> fixes) { this.fixes = fixes; } public ImmutableList<SuggestedFix> getFixes() { return fixes; } public static Builder builder() { return new Builder(); } /** Builder class for BranchedSuggestedFixes */ public static class Builder { private ImmutableList.Builder<SuggestedFix> builder = ImmutableList.builder(); private ImmutableList<SuggestedFix> savedList = ImmutableList.of(); public Builder startWith(SuggestedFix fix) { savedList = ImmutableList.of(); builder = ImmutableList.<SuggestedFix>builder().add(fix); return this; } public Builder addOption(SuggestedFix fix) { if (!savedList.isEmpty()) { for (SuggestedFix s : savedList) { builder.add(SuggestedFix.builder().merge(s).merge(fix).build()); } } return this; } public Builder then() { savedList = builder.build(); builder = ImmutableList.builder(); return this; } public BranchedSuggestedFixes build() { return new BranchedSuggestedFixes(builder.build()); } } }
29.494624
100
0.693766
de109c2c4d3b82be18855a0aa4a320db41f1a46a
168
package ru.doublebyte.trendingstream; import org.junit.jupiter.api.Test; public class ApplicationTest { @Test public void main() throws Exception { } }
14
41
0.714286
057ec1a6783327045aefa09d58f75e2466c67c5d
6,956
package com.starlight.intrepid; import com.logicartisan.common.core.thread.SharedThreadPool; import com.starlight.intrepid.auth.ConnectionArgs; import com.starlight.intrepid.auth.UserContextInfo; import com.starlight.intrepid.exception.IntrepidRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.net.InetAddress; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; /** * */ class ListenerRegistrationManager implements ConnectionListener { private static final Logger LOG = LoggerFactory.getLogger( ListenerRegistrationManager.class ); private final Intrepid intrepid_instance; private final Lock listeners_map_lock = new ReentrantLock(); private final Map<VMID,Set<ListenerInfo>> listeners_map = new HashMap<>(); ListenerRegistrationManager( @Nonnull Intrepid intrepid_instance ) { this.intrepid_instance = Objects.requireNonNull( intrepid_instance ); } @Override public void connectionOpened( @Nonnull InetAddress host, int port, Object attachment, @Nonnull VMID source_vmid, @Nonnull VMID vmid, UserContextInfo user_context, VMID previous_vmid, @Nonnull Object connection_type_description, byte ack_rate_sec ) { listeners_map_lock.lock(); try { // Deal with remapped VMID Set<ListenerInfo> old_listeners = null; if ( previous_vmid != null ) { old_listeners = listeners_map.remove( previous_vmid ); } Set<ListenerInfo> listeners = listeners_map.get( vmid ); if ( listeners == null ) { if ( old_listeners == null ) return; listeners_map.put( vmid, old_listeners ); listeners = old_listeners; } else if ( old_listeners != null ) { listeners.addAll( old_listeners ); } for( ListenerInfo info : listeners ) { SharedThreadPool.INSTANCE.execute( () -> info.addListener( true ) ); } } finally { listeners_map_lock.unlock(); } } @Override public void connectionClosed( @Nonnull InetAddress host, int port, @Nonnull VMID source_vmid, @Nullable VMID vmid, @Nullable Object attachment, boolean will_attempt_reconnect, @Nullable UserContextInfo user_context ) { listeners_map_lock.lock(); try { Set<ListenerInfo> listeners = listeners_map.get( vmid ); if ( listeners == null ) return; listeners.forEach( ListenerInfo::markOffline ); } finally { listeners_map_lock.unlock(); } } @Override public void connectionOpening( @Nonnull InetAddress host, int port, Object attachment, ConnectionArgs args, @Nonnull Object connection_type_description ) {} @Override public void connectionOpenFailed( @Nonnull InetAddress host, int port, Object attachment, Exception error, boolean will_retry ) {} <L,P,R> ListenerRegistration keepListenerRegistered( @Nonnull L listener, final @Nonnull VMID vmid, @Nonnull P proxy, @Nonnull BiFunction<P,L,R> add_method, @Nullable BiConsumer<P,L> remove_method, @Nonnull Consumer<R> return_value_handler ) throws IllegalArgumentException { final ListenerInfo<L,P,R> info = new ListenerInfo<>( proxy, listener, add_method, remove_method, return_value_handler ); info.addListener( false ); listeners_map_lock.lock(); try { boolean first_listener = listeners_map.isEmpty(); Set<ListenerInfo> listeners = listeners_map.computeIfAbsent( vmid, k -> new HashSet<>() ); listeners.add( info ); if ( first_listener ) { intrepid_instance.addConnectionListener( this ); } } finally { listeners_map_lock.unlock(); } return new ListenerRegistration() { @Override public void remove() { info.removeListener(); listeners_map_lock.lock(); try { Set<ListenerInfo> listeners = listeners_map.get( vmid ); if ( listeners == null ) return; listeners.remove( info ); if ( listeners.isEmpty() ) { listeners_map.remove( vmid ); } if ( listeners_map.isEmpty() ) { intrepid_instance.removeConnectionListener( ListenerRegistrationManager.this ); } } finally { listeners_map_lock.unlock(); } } @Override public boolean isCurrentlyConnected() { return info.isConnected(); } }; } <P,L> ListenerRegistration keepListenerRegistered( final @Nonnull L listener, final @Nonnull VMID vmid, final @Nonnull P proxy, final @Nonnull BiConsumer<P,L> add_method, final @Nullable BiConsumer<P,L> remove_method ) throws IllegalArgumentException { return keepListenerRegistered( listener, vmid, proxy, ( BiFunction<P,L,Void> ) ( p, l ) -> { add_method.accept( p, l ); return null; }, remove_method, ( not_used ) -> {} ); } private static class ListenerInfo<L,P,R> { private final P proxy; private final L listener; private final BiFunction<P,L,R> add_method; private final BiConsumer<P,L> remove_method; private final Consumer<R> return_value_handler; private final AtomicBoolean connected = new AtomicBoolean( false ); private final AtomicReference<ScheduledFuture<?>> deferred_add_listener_slot = new AtomicReference<>(); ListenerInfo( P proxy, L listener, BiFunction<P,L,R> add_method, BiConsumer<P,L> remove_method, Consumer<R> return_value_handler ) { this.proxy = proxy; this.listener = listener; this.add_method = add_method; this.remove_method = remove_method; this.return_value_handler = return_value_handler; } void addListener( boolean schedule_on_fail ) { removeScheduledAddTask(); try { R return_value = add_method.apply( proxy, listener ); if ( return_value_handler != null ) { return_value_handler.accept( return_value ); } connected.set( true ); } catch( Throwable ex ) { LOG.warn( "Error re-registering listener (listener={} add_method={} " + "proxy={})", listener, add_method, proxy, ex ); connected.set( false ); if ( schedule_on_fail ) { deferred_add_listener_slot.set( SharedThreadPool.INSTANCE.schedule( () -> addListener( true ), 1, TimeUnit.SECONDS ) ); } else throw ex; } } void removeListener() { removeScheduledAddTask(); try { remove_method.accept( proxy, listener ); } catch( IntrepidRuntimeException ex ) { // ignore this } connected.set( false ); } void markOffline() { removeScheduledAddTask(); connected.set( false ); } boolean isConnected() { return connected.get(); } private void removeScheduledAddTask() { ScheduledFuture<?> future = deferred_add_listener_slot.getAndSet( null ); if ( future != null ) { future.cancel( false ); } } } }
25.955224
90
0.716647