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
|
|---|---|---|---|---|---|
7888eadb6ba3f965445872fe81aaf4cdc28ea986
| 3,537
|
package gs;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.response.DefaultResponseCreator;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import static gs.util.ResponseCreatorWithWait.withSuccessAfter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.IsAnything.anything;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoTests {
private MockRestServiceServer mockServer;
@Autowired
private RestTemplate restTemplate;
@Autowired
private TestRestTemplate testRestTemplate;
@Before
public void setup() {
mockServer = MockRestServiceServer.bindTo(restTemplate).build();
}
@Test
public void remote_service_fault() {
mockServer.expect(requestTo("http://remote/service"))
.andRespond(withServerError());
ResponseEntity<String> response = testRestTemplate.getForEntity("/demo/1234", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
@Test
public void remote_service_lags() {
mockServer.expect(requestTo("http://remote/service"))
.andRespond(withSuccessAfter(20000));
ResponseEntity<String> response = testRestTemplate.getForEntity("/demo/1234", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
@Test
public void remote_service_contingency() throws Exception {
mockServer.expect(requestTo("http://remote/service"))
.andRespond(withBadRequest());
ResponseEntity<String> response = testRestTemplate.getForEntity("/demo/0000", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(getJsonBody(response).getString("message")).isEqualTo("unknown code");
}
@Test
public void invalid_input() throws Exception {
ResponseEntity<String> response = testRestTemplate.getForEntity("/demo/11", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(getJsonBody(response).getString("message")).isEqualTo("invalid code");
}
// helpers
private JSONObject getJsonBody(ResponseEntity<String> response) throws JSONException {
return new JSONObject(response.getBody());
}
}
| 36.463918
| 100
| 0.769013
|
47c54c6fb5d2b8f2ff13a320cd422e77d8afd104
| 3,966
|
/*
*
* * $Id: Template.jav,v 1.2 2005/10/07 23:46:50 clairetg Exp $
*
*
*
* Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University,
* all rights reserved.
*
* 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
* STANFORD UNIVERSITY 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.
*
* Except as contained in this notice, the name of Stanford University shall not
* be used in advertising or otherwise to promote the sale, use or other dealings
* in this Software without prior written authorization from Stanford University.
*
* /
*/
package org.lockss.plugin.silverchair.oup;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.silverchair.ScHtmlHttpResponseHandler.ScRetryableNetworkException;
import org.lockss.util.Constants;
import org.lockss.util.Logger;
import org.lockss.util.urlconn.CacheException;
import org.lockss.util.urlconn.CacheResultHandler;
import org.lockss.util.urlconn.CacheResultMap;
public class OupScHtmlHttpResponseHandler implements CacheResultHandler {
private static final Logger logger = Logger.getLogger(OupScHtmlHttpResponseHandler.class);
protected static final Pattern NON_FATAL_PAT =
Pattern.compile("\\.(bmp|css|eot|gif|ico|jpe?g|js|otf|png|svg|tif?f|ttf|woff|pdf)$");
@Override
public void init(final CacheResultMap map) throws PluginException {
logger.warning("Unexpected call to init()");
throw new UnsupportedOperationException("Unexpected call to ScHttpResponseHandler.init()");
}
@Override
public CacheException handleResult(final ArchivalUnit au, final String url, final int code) throws PluginException {
logger.debug(code + ": " + url);
Matcher mat = NON_FATAL_PAT.matcher(url);
switch (code) {
case 403:
//Do not fail the crawl for 403 errors at URLs like the one below should not be fatal
if (mat.find()) {
return new CacheException.NoRetryDeadLinkException("403 Forbidden (non-fatal)");
} else {
return new CacheException.RetrySameUrlException("403 Forbidden error");
}
case 500:
//Do not fail the crawl for 500 errors at URLs like the one below should not be fatal
if (mat.find()) {
return new CacheException.NoRetryDeadLinkException("500 Internal server (non-fatal)");
} else {
return new CacheException.RetrySameUrlException("500 Internal server error");
}
default:
logger.warning("Unexpected responseCode (" + code + ") in handleResult(): AU " + au.getName() + "; URL " + url);
throw new UnsupportedOperationException("Unexpected responseCode (" + code + ")");
}
}
@Override
public CacheException handleResult(final ArchivalUnit au, final String url, final Exception ex)
throws PluginException {
logger.debug(ex.getMessage() + ": " + url);
return new CacheException.RetrySameUrlException(ex.getMessage());
}
}
| 41.747368
| 120
| 0.732476
|
144fcef188aeef7fd514f482dc89aa025b71fec2
| 6,038
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author barokah
*/
public class SuratDAOREST implements SuratDAO {
List<Surat> listSurat;
public SuratDAOREST() {
listSurat = new ArrayList<>();
populateSurat();
}
@Override
public Surat getSurat(int index) {
return listSurat.get(index);
}
@Override
public List<Surat> getAllSurat() {
return listSurat;
}
private void populateSurat() {
try {
URL url = new URL(LoginDAOREST.ALAMAT + "api/surat");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.addRequestProperty("Authorization", LoginDAOREST.USER);
// Ambil value dari Input Stream ubah menjadi String
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
Reader in = new InputStreamReader(conn.getInputStream());
while (true) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0) {
break;
}
sb.append(buffer, 0, rsz);
}
// Mengubah String menjadi Object JSON kemudian mengubahnya ke Object Surat
JSONParser jp = new JSONParser();
JSONObject jo = (JSONObject) jp.parse(sb.toString());
JSONArray json = (JSONArray) jo.get("data");
System.out.println("Jumlah Data Surat yang diambil: " + jo.get("jumlah").toString());
listSurat.clear();
for (int i = 0; i < json.size(); i++) {
jo = (JSONObject) jp.parse(json.get(i).toString());
listSurat.add(new Surat(
jo.get("no_surat").toString(),
jo.get("tanggal_surat").toString(),
jo.get("nim").toString(),
jo.get("nama").toString(),
jo.get("tanggal_lahir").toString(),
jo.get("asal").toString(),
jo.get("jurusan").toString(),
(jo.get("nip") == null) ? "" : jo.get("nip").toString(),
(jo.get("dosen") == null) ? "" : jo.get("dosen").toString(),
jo.get("perusahaan").toString(),
jo.get("tanggal_mulai").toString(),
jo.get("tanggal_selesai").toString()));
}
conn.disconnect();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch (IOException | ParseException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
@Override
public void addSurat(String nim, String noSurat) {
try {
URL url = new URL(LoginDAOREST.ALAMAT + "api/surat/tambah/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Authorization", LoginDAOREST.USER);
String input = "{"
+ "\"nim\":\"" + nim
+ "\",\"no_surat\":\"" + noSurat
+ "\"}";
System.out.println(input);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
populateSurat();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
@Override
public void deleteSurat(String nim) {
try {
URL url = new URL(LoginDAOREST.ALAMAT + "api/surat/hapus/" + nim);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("DELETE");
conn.addRequestProperty("Authorization", LoginDAOREST.USER);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
populateSurat();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Application Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
| 39.207792
| 99
| 0.568069
|
66d749415ca9d1114c77805e02ced4b2b2949f36
| 1,954
|
package chapter3.recipe1;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.QueryStringDecoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import netty.cookbook.common.NettyServerUtil;
import netty.cookbook.common.http.BasicHttpResponseHandler;
import netty.cookbook.common.http.HttpEventHandler;
public class HttpServerWithRouter {
public static void main(String[] args) throws Exception {
String ip = "127.0.0.1";
int port = 8080;
Map<String, HttpEventHandler> routes = new LinkedHashMap<>();
routes.put("startsWith:/hello", (HttpRequest req, QueryStringDecoder q) -> {
String s = "Hello " ;//+ q.parameters().getOrDefault("name", Arrays.asList("guest")).get(0);
return HttpEventHandler.response(s, 200);
});
routes.put("endsWith:/date", (HttpRequest req, QueryStringDecoder q) -> {
System.out.println(req.headers().get(Names.COOKIE));
return HttpEventHandler.response(new Date(), 200);
});
routes.put("equals:/about", new BasicHttpResponseHandler("This is a Http Netty Server", 200));
HttpEventRoutingHandler routerHandler = new HttpEventRoutingHandler(routes);
ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("encoder", new HttpResponseEncoder());
p.addLast(routerHandler);
}
};
NettyServerUtil.newHttpServerBootstrap(ip, port, channelInitializer );
}
}
| 38.313725
| 101
| 0.747185
|
66f3e261ed1ff1e981f16327f2369555824f56b2
| 55,319
|
/**
* 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.ctakes.drugner;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.jcas.JCas;
import org.apache.ctakes.core.fsm.output.DateToken;
import org.apache.ctakes.core.util.FSUtil;
import org.apache.ctakes.drugner.elements.AssociatedPrimaryCodeElement;
import org.apache.ctakes.drugner.elements.ConfidenceScoreElement;
import org.apache.ctakes.drugner.elements.DosageElement;
import org.apache.ctakes.drugner.elements.DrugChangeStatusElement;
import org.apache.ctakes.drugner.elements.DurationElement;
import org.apache.ctakes.drugner.elements.FormElement;
import org.apache.ctakes.drugner.elements.FrequencyElement;
import org.apache.ctakes.drugner.elements.FrequencyUnitElement;
import org.apache.ctakes.drugner.elements.RouteElement;
import org.apache.ctakes.drugner.elements.StartDateElement;
import org.apache.ctakes.drugner.elements.StrengthElement;
import org.apache.ctakes.drugner.elements.StrengthUnitElement;
import org.apache.ctakes.drugner.elements.TextMentionElement;
import org.apache.ctakes.drugner.fsm.output.elements.DrugChangeStatusToken;
import org.apache.ctakes.drugner.fsm.output.elements.FrequencyUnitToken;
import org.apache.ctakes.drugner.fsm.output.elements.RouteToken;
import org.apache.ctakes.typesystem.type.textsem.DateAnnotation;
import org.apache.ctakes.drugner.type.DosagesAnnotation;
import org.apache.ctakes.drugner.type.DrugChangeStatusAnnotation;
import org.apache.ctakes.drugner.type.DurationAnnotation;
import org.apache.ctakes.drugner.type.FormAnnotation;
import org.apache.ctakes.drugner.type.FrequencyAnnotation;
import org.apache.ctakes.drugner.type.FrequencyUnitAnnotation;
import org.apache.ctakes.drugner.type.RouteAnnotation;
import org.apache.ctakes.drugner.type.StrengthAnnotation;
import org.apache.ctakes.drugner.type.StrengthUnitAnnotation;
/**
* Contains information from a single document - is not the result of data
* mining.
*/
public class DrugMention implements DrugModel {
/**
* The word(s) in the note that indicate the drug.
*/
public TextMentionElement drugMentionText;
public AssociatedPrimaryCodeElement associatedCodePrimary;
/**
* terminology unique identifier (e.g. RxNorm identifier). if not in the
* terminology, we will use the drug mention as the id.
*/
public AssociatedPrimaryCodeElement associatedCodeSecondary;
/**
* If there is a specific date in the note associated with the drug mention,
* the specific date. Also time might be capture by more general markers,
* e.g. "subsequently".
*/
public StartDateElement startDate;
public DateToken endDate;
/**
* e.g. 5 mg
*/
public DosageElement dosage;
/**
* e.g. twice daily
*/
public FrequencyElement frequency;
/**
* e.g. twice daily
*/
public FrequencyUnitElement frequencyUnit;
/**
* e.g. "for 2 weeks"
*/
public DurationElement duration;
/**
* e.g oral Topical Examples include medications applied onto the skin,
* asthma medications, enema, eye or ear drops, decongestants, vaginal
* creams. Enteral (oral) Most drugs taken by mouth such as tablets or
* capsules. Enteral (gastric) Examples include medications given through a
* gastric or duodenal tube. Enteral (rectal) Drugs in suppositories or
* enema form. Parenteral (intravenous) Parenteral (intra-arterial)
* Parenteral (intramuscular) Parenteral (intracardiac) Parenteral
* (subcutaneous) Medications such as insulin. Parenteral (intrathecal) Into
* the spinal canal. Parenteral (intraperitoneal) Parenteral (transdermal)
* Such as patches. Parenteral (transmucosal)
*/
public RouteElement route;
public StrengthElement strength;
/**
* Span the drug form, if available. The spanned mention needs to be mapped
* to the standard form available in the dropdown menu. In general don't
* infer. However, for a medication described in terms of cc or mL, the
* number of cc's or mL's is usually not a strength - for example "5 cc
* 0.5%" (or 5 mL 0.5%), indicates a strength of 0.5% -- for those, create a
* Form, with "cc" or "mL" spanned, and mapped to liquid, so that we capture
* the unit such as cc or mL.
*/
public StrengthUnitElement strengthUnit;
/**
* Span the drug form, if available. The spanned mention needs to be mapped
* to the standard form available in the dropdown menu. In general don't
* infer. However, for a medication described in terms of cc or mL, the
* number of cc's or mL's is usually not a strength - for example "5 cc
* 0.5%" (or 5 mL 0.5%), indicates a strength of 0.5% -- for those, create a
* Form, with "cc" or "mL" spanned, and mapped to liquid, so that we capture
* the unit such as cc or mL.
*/
public FormElement form;
/**
* aka change. - start: refers to an explicit mention of when the drug was
* started - stop: refers to an explicit mention of when the drug was
* stopped - increase and decrease: refer to explicit mentions of drug
* attribute changes - noChange: nothing is explicitly stated regarding
* changes. This will be the default case and does not need to be created.
* If there is some mention on the text such as "I told the patient to
* continue with his dosage of XXX 300 mg", then there would be textual
* evidence for noChange.
*/
public DrugChangeStatusElement changeStatus;
public ConfidenceScoreElement confidence;
public boolean findMaxValue = true;
/**
* regex pattern to look for, in this case alpha upper and lower characters
*/
private static final Pattern lookForAlpha = Pattern.compile("[a-zA-Z]+");
/**
* regex pattern to look for, in this case alpha upper and lower characters
*/
private static final Pattern lookForPercent = Pattern.compile("[%]");
public DrugMention(JCas jcas, int beginPos, int endPos) {
Iterator drugStatusTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, DrugChangeStatusAnnotation.type, beginPos, endPos);
while (drugStatusTokenItr.hasNext()){
DrugChangeStatusAnnotation focusToken = (DrugChangeStatusAnnotation) drugStatusTokenItr.next();
String localStatus = null;
if ((localStatus = findDrugChangeStatusElement(jcas, focusToken
.getBegin(), focusToken.getEnd())) == null) {
changeStatus = new DrugChangeStatusElement(focusToken
.getCoveredText(), focusToken.getBegin(),
focusToken.getEnd());
} else {
setDrugChangeStatusElement(localStatus, focusToken
.getBegin(), focusToken.getEnd());
}
}
if (changeStatus != null
&& (changeStatus.getDrugChangeStatus().equals(DrugChangeStatusToken.INCREASEFROM)
|| changeStatus.getDrugChangeStatus().equals(DrugChangeStatusToken.DECREASE))) {
findMaxValue = false;
}
Iterator dateTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DateAnnotation.type, beginPos, endPos);
while (dateTokenItr.hasNext()){
DateAnnotation focusToken = (DateAnnotation) dateTokenItr.next();
String localDate = null;
if ((localDate = findStartDateElement(jcas, focusToken.getBegin(),
focusToken.getEnd())) == null) {
startDate = new StartDateElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setStartDateElement(localDate, focusToken.getBegin(),
focusToken.getEnd());
}
}
Iterator doseTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DosagesAnnotation.type, beginPos, endPos);
while (doseTokenItr.hasNext()){
DosagesAnnotation focusToken = (DosagesAnnotation) doseTokenItr.next();
String localDose = null;
if ((localDose = findDosageElement(jcas, focusToken.getBegin(),
focusToken.getEnd())) == null) {
dosage = new DosageElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setDosageElement(localDose, focusToken.getBegin(),
focusToken.getEnd());
}
}
Iterator frequencyTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
FrequencyAnnotation.type, beginPos, endPos);
while (frequencyTokenItr.hasNext()){
FrequencyAnnotation focusToken = (FrequencyAnnotation) frequencyTokenItr.next();
String localFreq = null;
if ((localFreq = findFrequencyElement(jcas, focusToken
.getBegin(), focusToken.getEnd())) == null) {
frequency = new FrequencyElement(focusToken
.getCoveredText(), focusToken.getBegin(),
focusToken.getEnd());
} else if ((frequency != null && localFreq != null)
&& (frequency.getFrequencyMention().compareTo("") != 0)
&& (localFreq.compareTo("") != 0)
&& (parseIntValue(localFreq) > parseIntValue(frequency
.getFrequencyMention()) && findMaxValue == true)) {
// Need a way to find the largest frequency and/or convert
// it to factor daily dosage
setFrequencyElement(localFreq, focusToken.getBegin(),
focusToken.getEnd());
} else {
setFrequencyElement(localFreq, focusToken.getBegin(),
focusToken.getEnd());
}
}
Iterator frequencyUnitTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
FrequencyUnitAnnotation.type, beginPos, endPos);
while (frequencyUnitTokenItr.hasNext()){
FrequencyUnitAnnotation focusToken = (FrequencyUnitAnnotation) frequencyUnitTokenItr.next();
String localFreq = null;
if ((localFreq = findFrequencyUnitElement(jcas,
focusToken.getBegin(), focusToken.getEnd())) == null) {
frequencyUnit = new FrequencyUnitElement(focusToken
.getCoveredText(), focusToken.getBegin(),
focusToken.getEnd());
} else if (frequencyUnit == null
&& findMaxValue == true) {
// Need a way to find the largest frequency and/or convert
// it to factor daily dosage
setFrequencyUnitElement(localFreq, focusToken.getBegin(),
focusToken.getEnd());
}
}
Iterator strengthUnitTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, StrengthUnitAnnotation.type, beginPos, endPos);
while (strengthUnitTokenItr.hasNext()){
StrengthUnitAnnotation focusToken = (StrengthUnitAnnotation) strengthUnitTokenItr.next();
setStrengthUnitElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
}
Iterator strengthTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, StrengthAnnotation.type, beginPos, endPos);
while (strengthTokenItr.hasNext()){
StrengthAnnotation focusToken = (StrengthAnnotation) strengthTokenItr.next();
String localStrength = null;
if ((localStrength = findStrengthElement(jcas, focusToken
.getBegin(), focusToken.getEnd())) == null) {
strength = new StrengthElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
if (strength != null) {
// check for range and compare
int spacePosition = strength.getStrengthMention()
.indexOf(" ");
int spacePos = localStrength
.indexOf(" ");
if (spacePosition > 0 && spacePos > 0
&& parseDoubleValue(strength
.getStrengthMention().substring(0,
spacePosition)) < parseDoubleValue(localStrength
.substring(0, localStrength
.indexOf(" ")))&& findMaxValue == true) {
setStrengthElement(localStrength, focusToken
.getBegin(), focusToken.getEnd());
} else {
String stringRange = strength.getStrengthMention();
int hyphPosition = 0;
if ((stringRange.length() > 0)
&& (stringRange.indexOf('-') > 0)) {
hyphPosition = stringRange.indexOf('-');
Double firstValue = new Double(
parseDoubleValue(stringRange
.subSequence(0, hyphPosition)));
Double secondValue = new Double(
parseDoubleValue(stringRange
.substring(hyphPosition + 2)));
if (firstValue.doubleValue() >= secondValue
.doubleValue() && findMaxValue == true) {
setStrengthElement(firstValue.toString(),
focusToken.getBegin(), focusToken
.getEnd());
} else {
setStrengthElement(firstValue.toString(),
focusToken.getBegin(), focusToken
.getEnd());
}
}
}
} else if ((localStrength.length() > 0)
&& (localStrength.indexOf('-') > 0)) {
int hyphPosition = 0;
hyphPosition = localStrength.indexOf('-');
Double firstValue = new Double(
parseDoubleValue(localStrength.subSequence(0,
hyphPosition)));
Double secondValue = new Double(
parseDoubleValue(localStrength
.substring(hyphPosition + 2)));
if (firstValue.doubleValue() >= secondValue
.doubleValue() && findMaxValue == true) {
setStrengthElement(firstValue.toString(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setStrengthElement(firstValue.toString(),
focusToken.getBegin(), focusToken.getEnd());
}
setStrengthElement(localStrength,
focusToken.getBegin(), focusToken.getEnd());
} else {
setStrengthElement(localStrength,
focusToken.getBegin(), focusToken.getEnd());
}
}
}
Iterator formTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, FormAnnotation.type, beginPos, endPos);
while (formTokenItr.hasNext()){
FormAnnotation focusToken = (FormAnnotation) formTokenItr.next();
String localForm = null;
if ((localForm = findFormElement(jcas, focusToken.getBegin(),
focusToken.getEnd())) == null) {
form = new FormElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setFormElement(localForm, focusToken.getBegin(), focusToken
.getEnd());
}
}
Iterator routeTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, RouteAnnotation.type, beginPos, endPos);
while (routeTokenItr.hasNext()){
RouteAnnotation focusToken = (RouteAnnotation) routeTokenItr.next();
String localRoute = null;
if ((localRoute = findRouteElement(jcas, focusToken.getBegin(),
focusToken.getEnd())) == null) {
route = new RouteElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setRouteElement(localRoute, focusToken.getBegin(),
focusToken.getEnd());
}
}
Iterator durationTokenItr = FSUtil.getAnnotationsIteratorInSpan(jcas, DurationAnnotation.type, beginPos, endPos);
while (durationTokenItr.hasNext()){
DurationAnnotation focusToken = (DurationAnnotation) durationTokenItr.next();
String localDuration = null;
if ((localDuration = findDurationElement(jcas, focusToken
.getBegin(), focusToken.getEnd())) == null) {
duration = new DurationElement(focusToken.getCoveredText(),
focusToken.getBegin(), focusToken.getEnd());
} else {
setDurationElement(localDuration, focusToken.getBegin(),
focusToken.getEnd());
}
}
}
public void setPrimaryAssociatedCodeElement(String name, int beginOffset,
int endOffset) {
// need a method to find most suitable primary cui here
associatedCodePrimary = new AssociatedPrimaryCodeElement(name, beginOffset,
endOffset);
}
public void setSecondaryAssociatedCodeElement(String name, int beginOffset,
int endOffset) {
// need a method to find most suitable secondary cui here
associatedCodeSecondary = new AssociatedPrimaryCodeElement(name, beginOffset,
endOffset);
}
public void setStartDateElement(String date, int beginOffset, int endOffset) {
startDate = new StartDateElement(date, beginOffset, endOffset);
}
public void setEndDateElement(String name, int beginOffset, int endOffset) {
}
public void setDosageElement(String dose, int beginOffset, int endOffset) {
dosage = new DosageElement(dose, beginOffset, endOffset);
}
public void setFrequencyElement(String name, int beginOffset, int endOffset) {
frequency = new FrequencyElement(name, beginOffset, endOffset);
}
public void setFrequencyUnitElement(String name, int beginOffset,
int endOffset) {
frequencyUnit = new FrequencyUnitElement(name, beginOffset, endOffset);
}
public void setFormElement(String name, int beginOffset, int endOffset) {
form = new FormElement(name, beginOffset, endOffset);
}
public void setDurationElement(String name, int beginOffset, int endOffset) {
duration = new DurationElement(name, beginOffset, endOffset);
}
public void setRouteElement(String name, int beginOffset, int endOffset) {
route = new RouteElement(name, beginOffset, endOffset);
}
public void setDrugChangeStatusElement(String name, int beginOffset,
int endOffset) {
changeStatus = new DrugChangeStatusElement(name, beginOffset, endOffset);
}
public void setConfidenceScoreElement(double score, int beginOffset,
int endOffset) {
confidence = new ConfidenceScoreElement(score, beginOffset, endOffset);
}
public void setStrengthElement(String name, int beginOffset, int endOffset) {
strength = new StrengthElement(name, beginOffset, endOffset);
}
public String getStrengthUnitElement() {
// TODO Auto-generated method stub
if (strengthUnit != null)
return strengthUnit.getStrengthMention();
else
return null;
}
public void setStrengthUnitElement(String name, int beginOffset, int endOffset) {
// TODO Auto-generated method stub
strengthUnit = new StrengthUnitElement(name, beginOffset, endOffset);
}
public String getPrimaryAssociatedCodeElement() {
if (associatedCodePrimary != null)
return associatedCodePrimary.getCuiCode();
else
return null;
}
public String getSecondaryAssociatedCodeElement() {
if (associatedCodeSecondary != null)
return associatedCodeSecondary.getCuiCode();
else
return null;
}
public String getStartDateElement() {
if (startDate != null)
return startDate.getDate();
else return "";
}
public String getEndDateElement() {
return endDate.toString();
}
public String getDosageElement() {
if (dosage != null)
return dosage.getDosage();
else
return "1.0";
}
public String getFrequencyElement() {
if (frequency != null)
return frequency.getFrequencyMention();
else
return "1.0";
}
public String getFrequencyUnitElement() {
if (frequencyUnit != null)
return frequencyUnit.getFrequencyUnitMention();
else
return null;
}
public String getFormElement() {
if (form != null)
return form.getFormMention();
else
return null;
}
public String getDurationElement() {
if (duration != null)
return duration.getDuration();
else
return null;
}
public String getRouteElement() {
if (route != null)
return route.getRouteMention();
else
return null;
}
public String getDrugChangeStatusElement() {
if (changeStatus != null)
return changeStatus.getDrugChangeStatus();
else
return DrugChangeStatusElement.NOCHANGE_STATUS;
}
public String getStrengthElement() {
if (strength != null)
return strength.getStrengthMention();
else
return "";
}
public double getConfidenceScoreElement() {
if (confidence != null)
return confidence.getConfidenceScoreElement();
else
return 0;
}
private String findStartDateElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DateAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
DateAnnotation da = (DateAnnotation) firItr.next();
if (da.getBegin() == beginOffset)
return da.getCoveredText();
}
return null;
}
private String findEndDateElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsInSpanIterator(jcas,
DateAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
DateAnnotation da = (DateAnnotation) firItr.next();
if (da.getBegin() == beginOffset)
return da.getCoveredText();
}
return null;
}
private String findDosageElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DosagesAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
DosagesAnnotation da = (DosagesAnnotation) firItr.next();
if (da.getBegin() == beginOffset) {
int posSpace = da.getCoveredText().lastIndexOf(' ');
int posHyph = da.getCoveredText().lastIndexOf('-');
String lastTerm = da.getCoveredText();
int ofSpace = da.getCoveredText().indexOf("of");
if (ofSpace > 0)
lastTerm = da.getCoveredText().substring(0, ofSpace).trim();
if ((lastTerm.compareToIgnoreCase("one-half-tablet") == 0)
|| (lastTerm.compareToIgnoreCase("one-half") == 0)
|| (lastTerm.compareToIgnoreCase("1/2") == 0)
|| (lastTerm.compareToIgnoreCase("half-tablet") == 0)) {
return "0.5";
} else if (lastTerm.compareToIgnoreCase("one-and-a-half") == 0) {
return "1.5";
} else if ((lastTerm.compareToIgnoreCase("one-quarter") == 0)
|| (lastTerm.compareToIgnoreCase("one-fourth") == 0)
|| (lastTerm.compareToIgnoreCase("1/4") == 0)
|| (lastTerm.compareToIgnoreCase("a-fourth") == 0)) {
return ".25";
} else if ((lastTerm.compareToIgnoreCase("one-third") == 0)
|| (lastTerm.compareToIgnoreCase("thirds") == 0)
|| (lastTerm.compareToIgnoreCase("1/3") == 0)
|| (lastTerm.compareToIgnoreCase("a-third") == 0)) {
return ".33";
} else {
if (posSpace > 0)
lastTerm = lastTerm.substring(posSpace + 1);
else if (posHyph > 0)
lastTerm = lastTerm.substring(posHyph + 1);
}
return convertFromTextToNum(lastTerm);
}
}
return null;
}
private String findFormElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
FormAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
FormAnnotation da = (FormAnnotation) firItr.next();
if (da.getBegin() == beginOffset) {
if ((da.getCoveredText().compareToIgnoreCase(
FormElement.AEROSOL) == 0)
|| (da.getCoveredText().compareToIgnoreCase("aerosols") == 0))
return FormElement.AEROSOL;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.CREAM) == 0)
|| (da.getCoveredText().compareToIgnoreCase("creams") == 0))
return FormElement.CREAM;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.ELIXIR) == 0)
|| (da.getCoveredText().compareToIgnoreCase("elixirs") == 0))
return FormElement.ELIXIR;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.EMULSION) == 0)
|| (da.getCoveredText().compareToIgnoreCase(
"emulutions") == 0))
return FormElement.EMULSION;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.ENEMA) == 0)
|| (da.getCoveredText().compareToIgnoreCase("ememas") == 0))
return FormElement.ENEMA;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.GEL) == 0)
|| (da.getCoveredText().compareToIgnoreCase("gels") == 0))
return FormElement.GEL;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.IMPLANT) == 0)
|| (da.getCoveredText().compareToIgnoreCase("implants") == 0))
return FormElement.IMPLANT;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.INHALANT) == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("inhalants") == 0))
return FormElement.INHALANT;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.INJECTION) == 0)
|| (da.getCoveredText().compareToIgnoreCase(
"injections") == 0))
return FormElement.INJECTION;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.LIQUID) == 0)
|| (da.getCoveredText().compareToIgnoreCase("liquids") == 0))
return FormElement.LIQUID;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.LOTION) == 0)
|| (da.getCoveredText().compareToIgnoreCase("lotions") == 0))
return FormElement.LOTION;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.LOZENGE) == 0)
|| (da.getCoveredText().compareToIgnoreCase("lozenges") == 0))
return FormElement.LOZENGE;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.OINTMENT) == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("ointments") == 0))
return FormElement.OINTMENT;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.PATCH) == 0)
|| (da.getCoveredText().compareToIgnoreCase("patches") == 0))
return FormElement.PATCH;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.PILL) == 0)
|| (da.getCoveredText().compareToIgnoreCase("pills") == 0))
return FormElement.PILL;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.POWDER) == 0)
|| (da.getCoveredText().compareToIgnoreCase("powders") == 0))
return FormElement.POWDER;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SHAMPOO) == 0)
|| (da.getCoveredText().compareToIgnoreCase("shampoos") == 0))
return FormElement.SHAMPOO;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SOAP) == 0)
|| (da.getCoveredText().compareToIgnoreCase("soaps") == 0))
return FormElement.SOAP;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SOLUTION) == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("solutions") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("soln") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("concentrate") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("concentrat") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("conc") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("solu") == 0))
return FormElement.SOLUTION;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SPRAY) == 0)
|| (da.getCoveredText().compareToIgnoreCase("sprays") == 0)
|| (da.getCoveredText().compareToIgnoreCase(
"nebulizers") == 0)
|| (da.getCoveredText()
.compareToIgnoreCase("nebulizer") == 0))
return FormElement.SPRAY;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SUPPOSITORY) == 0)
|| (da.getCoveredText().compareToIgnoreCase(
"suppositories") == 0))
return FormElement.SUPPOSITORY;
else if ((da.getCoveredText().compareToIgnoreCase(FormElement.SYRINGE) == 0 )
|| (da.getCoveredText().compareToIgnoreCase("syrnge") == 0))
return FormElement.SYRINGE;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.SYRUP) == 0)
|| (da.getCoveredText().compareToIgnoreCase("syrups") == 0))
return FormElement.SYRUP;
else if ((da.getCoveredText().compareToIgnoreCase(
FormElement.TABLET) == 0)
|| (da.getCoveredText().compareToIgnoreCase("tablets") == 0)
// Capsule needs to be handled differently
// || (da.getCoveredText().compareToIgnoreCase("capsule") == 0)
// || (da.getCoveredText().compareToIgnoreCase("capsules") == 0)
// || (da.getCoveredText().compareToIgnoreCase("cap") == 0)
// || (da.getCoveredText().compareToIgnoreCase("caps") == 0)
|| (da.getCoveredText().compareToIgnoreCase("tab") == 0)
|| (da.getCoveredText().compareToIgnoreCase("tabs") == 0))
return FormElement.TABLET;
else if ((da.getCoveredText().compareToIgnoreCase(FormElement.CAPSULE) == 0)
|| (da.getCoveredText().compareToIgnoreCase("capsule") == 0)
|| (da.getCoveredText().compareToIgnoreCase("capsules") == 0)
|| (da.getCoveredText().compareToIgnoreCase("cap") == 0)
|| (da.getCoveredText().compareToIgnoreCase("caps") == 0))
return FormElement.CAPSULE;
return null;
}
}
return null;
}
private String findFrequencyElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
FrequencyAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
FrequencyAnnotation da = (FrequencyAnnotation) firItr.next();
if (da.getBegin() == beginOffset) {
int posSpace = da.getCoveredText().indexOf(' ');
int posHyph = da.getCoveredText().indexOf('-');
int lastPosHyph = da.getCoveredText().lastIndexOf('-');
String firstTerm = da.getCoveredText();
String lastTerm = da.getCoveredText();
if (posSpace > 0)
firstTerm = da.getCoveredText().substring(0, posSpace);
else if (posHyph > 0)
firstTerm = firstTerm.substring(0, posHyph);
if (lastPosHyph > 0){
lastTerm = lastTerm.substring(lastPosHyph+1, lastTerm.length());
//this.setFrequencyUnitElement(lastTerm, beginOffset+lastPosHyph+1, endOffset);
}
int lastSpace = lastTerm.lastIndexOf(' ');
if (lastSpace > 0)
lastTerm = lastTerm.substring(0, lastSpace);
while ((lastSpace = lastTerm.lastIndexOf(' ')) > 1)
lastTerm = lastTerm.substring(lastSpace+1);
String returnFirstValue = convertFromTextToNum(firstTerm);
String returnLastValue = convertFromTextToNum(lastTerm);
try {
if (new Double(returnFirstValue).intValue()
< new Double(returnLastValue).intValue() && findMaxValue){
return returnLastValue;
}
else
return returnFirstValue;
}
catch (NumberFormatException nfe){
return returnFirstValue;
}
}
}
return null;
}
private String findFrequencyUnitElement(JCas jcas, int beginOffset,
int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
FrequencyUnitAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
FrequencyUnitAnnotation da = (FrequencyUnitAnnotation) firItr
.next();
if (da.getBegin() == beginOffset && da.getPeriod() > holdLargestPeriod) {
holdLargestPeriod = da.getPeriod();
int posHyph = da.getCoveredText().lastIndexOf('-');
String lastTerm = da.getCoveredText();
int szString = lastTerm.toString().length();
if (posHyph > 0) {
lastTerm = lastTerm.substring(posHyph + 1, szString);
}
if (da.getPeriod() == FrequencyUnitToken.QUANTITY_ONE) {
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_TWO) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))) {
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 2.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("2.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_THREE) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))){
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 3.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("3.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_FOUR) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))) {
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 4.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("4.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_FIVE) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))){
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 5.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("5.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_SIX) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))) {
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 6.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("6.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_SEVEN) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))){
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 7.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("7.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_EIGHT) {
if (frequency != null
&& (frequency.getBeginOffset() != beginOffset && frequency
.getEndOffset() != endOffset)) {
if ((dosage == null
|| (dosage != null
&& convertFromTextToNum(
dosage.getDosage()).compareTo(
"1") == 0 && (dosage
.getBeginOffset() != beginOffset && dosage
.getEndOffset() != endOffset)))
&& (changeStatus != null && (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.OTHER) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.DECREASEFROM) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASE) != 0)
&& (changeStatus.getDrugChangeStatus().compareTo(DrugChangeStatusToken.INCREASEFROM) != 0))) {
setFrequencyElement(
frequency.getFrequencyMention(), frequency
.getBeginOffset(), frequency
.getEndOffset());
} else {
double updateFreq = new Double(frequency
.getFrequencyMention()).doubleValue() * 8.0;
setFrequencyElement(String.valueOf(updateFreq), beginOffset,
endOffset);
}
} else {
setFrequencyElement("8.0", beginOffset, endOffset);
}
return FrequencyUnitElement.DAILY;
} else if (da.getPeriod() == new Float(
FrequencyUnitToken.QUANTITY_EVERY_OTHER_DAY)
.floatValue()) {
return FrequencyUnitElement.EVERYOTHERDAY;
} else if (da.getPeriod() == new Float(
FrequencyUnitToken.QUANTITY_WEEKLY).floatValue()) {
return FrequencyUnitElement.WEEKLY;
} else if (da.getPeriod() == new Float(
FrequencyUnitToken.QUANTITY_MONTHLY).floatValue()) {
return FrequencyUnitElement.MONTHLY;
} else if (da.getPeriod() == FrequencyUnitToken.QUANTITY_PRN) {
return FrequencyUnitElement.ASNEEDED;
}
return lastTerm;
}
}
return null;
}
private String findDurationElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DurationAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
DurationAnnotation da = (DurationAnnotation) firItr.next();
if (da.getBegin() == beginOffset)
return da.getCoveredText();
}
return null;
}
private String findRouteElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
RouteAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
RouteAnnotation ra = (RouteAnnotation) firItr.next();
if (ra.getBegin() == beginOffset) {
if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.GASTRIC)
return RouteElement.GASTRIC;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.ORAL)
return RouteElement.ORAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRAARTERIAL)
return RouteElement.INTRAARTERIAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRACARDIAC)
return RouteElement.INTRACARDIAC;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRAMUSCULAR)
return RouteElement.INTRAMUSCULAR;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRAPERITONEAL)
return RouteElement.INTRAPERITONEAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRATHECAL)
return RouteElement.INTRATHECAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.INTRAVENOUS)
return RouteElement.INTRAVENOUS;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.RECTAL)
return RouteElement.RECTAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.SUBCUTANEOUS)
return RouteElement.SUBCUTANEOUS;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.TOPICAL)
return RouteElement.TOPICAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.TRANSDERMAL)
return RouteElement.TRANSDERMAL;
else if (new Integer(ra.getIntakeMethod()).intValue() == RouteToken.TRANSMUCOSAL)
return RouteElement.TRANSMUCOSAL;
return ra.getCoveredText();
}
}
return null;
}
private String findDrugChangeStatusElement(JCas jcas, int beginOffset,
int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
DrugChangeStatusAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
DrugChangeStatusAnnotation dcsa = (DrugChangeStatusAnnotation) firItr
.next();
if (dcsa.getBegin() == beginOffset) {
int posSpace = dcsa.getCoveredText().indexOf(' ');
int posHyph = dcsa.getCoveredText().indexOf('-');
String firstTerm = dcsa.getCoveredText();
if (posSpace > 0)
firstTerm = dcsa.getCoveredText().substring(0, posSpace);
if (posHyph > 0)
firstTerm = firstTerm.substring(0, posHyph);
return dcsa.getChangeStatus();//convertToChangeStatus(firstTerm);
}
}
return null;
}
private String findStrengthElement(JCas jcas, int beginOffset, int endOffset) {
Iterator firItr = FSUtil.getAnnotationsIteratorInSpan(jcas,
StrengthAnnotation.type, beginOffset, endOffset + 1);
while (firItr.hasNext()) {
StrengthAnnotation dcsa = (StrengthAnnotation) firItr.next();
String strength = dcsa.getCoveredText();
int findHyph = strength.indexOf('-');
if (findHyph > 0){
// large value in the range
strength = strength.substring(findHyph+1);
}
if (dcsa.getBegin() == beginOffset) {
return parseRegex(strength);
}
}
return null;
}
private String parseRegex(String stringGlob) {
if (stringGlob.matches("[0-9]*[\\.]*[0-9]+\\s[a-zA-Z]+")) {
// do nothing for now
} else if (stringGlob.matches("[0-9]*[\\.]*[0-9]+[-]+[a-zA-Z]+")) {
stringGlob = stringGlob.replaceAll("-", " ");
} else if (stringGlob.matches("[0-9]*[\\.]*[0-9]+[a-zA-Z]+")) {
int intRegex = indexOfRegex(stringGlob, lookForAlpha);
stringGlob = stringGlob.substring(0, intRegex) + " "
+ stringGlob.substring(intRegex);
} else if (stringGlob.matches("[0-9]*[\\.]*[0-9]+[\\%]")) {
int intRegex = indexOfRegex(stringGlob, lookForPercent);
stringGlob = stringGlob.substring(0, intRegex) + " "
+ stringGlob.substring(intRegex);
} else if (stringGlob.matches("[0-9]*[\\.]*[0-9]+[\\s][\\%]")) {
// do nothing for now
} else if (stringGlob.matches("[0-9]*[\\.]*[0-9]+[-]\\%")) {
stringGlob = stringGlob.replaceAll("-", "");
}
return stringGlob.trim().replace('\n', ' ').replaceAll(",", "").replaceAll("-", "");
}
public int parseIntValue(Object strength) {
String text = (String) strength;
String strengthNumText = "";
String subText = "";
boolean containsNums = false;
boolean doneHere = false;
int textSize = text.length();
int pos = 0;
Integer posInt = null;
while (!doneHere && (textSize > pos) && (textSize >= 1)) {
try {
String numString = text.substring(pos, pos + 1);
/*
* if (numString.compareTo(".") == 0) { subText =
* text.substring(pos + 1, textSize); pos++; }
*/
Integer posNum = Integer.decode(numString);
int checkInt = posNum.intValue();
if ((checkInt >= 0) && (checkInt <= 9)) {
containsNums = true;
subText = text.substring(pos + 1, textSize);
pos++;
strengthNumText = strengthNumText + numString;
} else
return 0;
}
catch (NullPointerException npe) {
return 0;
} catch (NumberFormatException nfe) {
if (!containsNums)
return 0;
else
doneHere = true;
}
}
return new Integer(strengthNumText).intValue();
}
public double parseDoubleValue(Object strength) {
String text = (String) strength;
String strengthNumText = "";
String subText = "";
boolean containsNums = false;
boolean doneHere = false;
int textSize = text.length();
int pos = 0;
Integer posInt = null;
while (!doneHere && (textSize > pos) && (textSize >= 1)) {
try {
String numString = text.substring(pos, pos + 1);
if (numString.compareTo(".") == 0) {
subText = text.substring(pos + 1, textSize);
pos++;
strengthNumText = strengthNumText + numString;
}
else {
Integer posNum = Integer.decode(numString);
int checkInt = posNum.intValue();
if ((checkInt >= 0) && (checkInt <= 9)) {
containsNums = true;
subText = text.substring(pos + 1, textSize);
pos++;
strengthNumText = strengthNumText + numString;
} else
return 0;
}
}
catch (NullPointerException npe) {
return 0;
} catch (NumberFormatException nfe) {
if (!containsNums)
return 0;
else
doneHere = true;
}
}
return new Double(strengthNumText).doubleValue();
}
public String convertFromTextToNum(String firstTerm) {
// First see if the text consists of a number range and take the
// greater of the two
int hyph = firstTerm.lastIndexOf('-');
if (hyph > 0){
firstTerm = firstTerm.substring(0, hyph);
int hyphChild = firstTerm.lastIndexOf('-');
if (hyphChild > 0 )
firstTerm = firstTerm.substring(0, hyphChild);
int lastHyph = firstTerm.indexOf('-');
if (lastHyph > 0)
firstTerm = firstTerm.substring(0, lastHyph);
}
int space = firstTerm.indexOf(' ');
if (space > 0)
firstTerm = firstTerm.substring(0, space);
if ((firstTerm.compareToIgnoreCase("first") == 0)
|| (firstTerm.compareToIgnoreCase("one") == 0)
|| (firstTerm.compareToIgnoreCase("daily") == 0)
|| (firstTerm.compareToIgnoreCase(FrequencyUnitElement.DAILY) == 0)
|| (firstTerm.compareToIgnoreCase("once") == 0)) {
return "1";
} else if ((firstTerm.compareToIgnoreCase("twice") == 0)
|| (firstTerm.compareToIgnoreCase("second") == 0)
|| (firstTerm.compareToIgnoreCase("two") == 0)) {
return "2";
} else if ((firstTerm.compareToIgnoreCase("third") == 0)
|| (firstTerm.compareToIgnoreCase("three") == 0)) {
return "3";
} else if ((firstTerm.compareToIgnoreCase("forth") == 0)
|| (firstTerm.compareToIgnoreCase("four") == 0)) {
return "4";
} else if ((firstTerm.compareToIgnoreCase("fifth") == 0)
|| (firstTerm.compareToIgnoreCase("five") == 0)) {
return "5";
} else if (firstTerm.compareToIgnoreCase("six") == 0) {
return "6";
} else if (firstTerm.compareToIgnoreCase("seven") == 0) {
return "7";
} else if (firstTerm.compareToIgnoreCase("eight") == 0) {
return "8";
} else if (firstTerm.compareToIgnoreCase("nine") == 0) {
return "9";
} else if (firstTerm.compareToIgnoreCase("ten") == 0) {
return "10";
} else if ((firstTerm.compareToIgnoreCase("half") == 0)
|| (firstTerm
.compareToIgnoreCase(FrequencyUnitElement.EVERYOTHERDAY) == 0)) {
return ".5";
} else if ((firstTerm.compareToIgnoreCase(FrequencyUnitElement.WEEKLY) == 0)
|| (firstTerm.compareToIgnoreCase("weekly") == 0)){
return ".14";
} else if ((firstTerm.compareToIgnoreCase(FrequencyUnitElement.MONTHLY) == 0)
|| (firstTerm.compareToIgnoreCase("monthly") == 0)){
return ".03";
} else if ((firstTerm.compareToIgnoreCase(FrequencyUnitElement.HOURLY) == 0)
|| (firstTerm.compareToIgnoreCase("hourly") == 0)){
return "24";
}else
return firstTerm;
}
public String convertToChangeStatus(String firstTerm) {
if ((firstTerm.compareToIgnoreCase(DrugChangeStatusElement.STOP_STATUS) == 0)
|| (firstTerm.compareToIgnoreCase("stopped") == 0)
|| (firstTerm.compareToIgnoreCase("past") == 0)
|| (firstTerm.compareToIgnoreCase("stopping") == 0)
|| (firstTerm.compareToIgnoreCase("discontinue") == 0)
|| (firstTerm.compareToIgnoreCase("discontinued") == 0)
|| (firstTerm.compareToIgnoreCase("DISCONTINUED MEDICATIONS") == 0)
|| (firstTerm.compareToIgnoreCase("DISCONTINUE MEDICATIONS") == 0)) {
return DrugChangeStatusElement.STOP_STATUS;
} else if ((firstTerm.compareToIgnoreCase("new") == 0)
|| (firstTerm.compareToIgnoreCase("new dose") == 0)
|| (firstTerm.compareToIgnoreCase("start") == 0)
|| (firstTerm.compareToIgnoreCase("started") == 0)
|| (firstTerm.compareToIgnoreCase("new medication") == 0)
|| (firstTerm.compareToIgnoreCase("NEW MEDICATIONS") == 0)) {
return DrugChangeStatusElement.START_STATUS;
} else if ((firstTerm.compareToIgnoreCase("increase") == 0)
|| (firstTerm.compareToIgnoreCase("increased") == 0)) {
return DrugChangeStatusElement.INCREASE_STATUS;
} else if ((firstTerm.compareToIgnoreCase("decrease") == 0)
|| (firstTerm.compareToIgnoreCase("lower") == 0)
|| (firstTerm.compareToIgnoreCase("decreased") == 0)) {
return DrugChangeStatusElement.DECREASE_STATUS;
} else if ((firstTerm.compareToIgnoreCase("then") == 0)
|| (firstTerm.compareToIgnoreCase("changed") == 0)
|| (firstTerm.compareToIgnoreCase("change") == 0)) {
return "change";
} else if ((firstTerm.compareToIgnoreCase("and") == 0)
|| (firstTerm.compareToIgnoreCase("plus") == 0)) {
return "add";
} else
return DrugChangeStatusElement.NOCHANGE_STATUS;
}
// -------------------------- PUBLIC STATIC METHODS
// --------------------------
public int getDosageBegin() {
return dosage.getBeginOffset();
}
public int getDosageEnd() {
return dosage.getEndOffset();
}
public int getFrequencyBegin() {
return frequency.getBeginOffset();
}
public int getFrequencyEnd() {
return frequency.getEndOffset();
}
public int getFUBegin() {
return frequencyUnit.getBeginOffset();
}
public int getFUENd() {
return frequencyUnit.getEndOffset();
}
public int getFormBegin() {
return form.getBeginOffset();
}
public int getFormEnd() {
return form.getEndOffset();
}
public int getDuratationBegin() {
return duration.getBeginOffset();
}
public int getDuratationEnd() {
return duration.getEndOffset();
}
public int getRouteBegin() {
return route.getBeginOffset();
}
public int getRouteEnd() {
return route.getEndOffset();
}
public int getStrengthUnitBegin() {
return strengthUnit.getBeginOffset();
}
public int getStrengthUnitEnd() {
return strengthUnit.getEndOffset();
}
public int getStrengthBegin() {
return strength.getBeginOffset();
}
public int getStrengthEnd() {
return strength.getEndOffset();
}
// Add drug change status offsets begin
public int getChangeStatusBegin() {
return changeStatus.getBeginOffset();
}
public int getChangeStatusEnd() {
return changeStatus.getEndOffset();
}
// Add drug change status offsets end
/**
* Scan a string for the first occurrence of some regex Pattern.
*
* @param lookForAlpha
* the pattern to look for
* @param lookIn
* the String to scan.
* @return offset relative to start of lookIn where it first found the
* pattern, -1 if not found.
*/
public static int indexOfRegex(String lookIn, Pattern lookFor) {
Matcher m = lookFor.matcher(lookIn);
if (m.find()) {
return m.start();
} else {
return -1;
}
}
private double holdLargestPeriod = -1;
}
| 36.394079
| 125
| 0.675392
|
020eade0b63b08f79b1aed12a8f405deb2e05bb9
| 1,957
|
package pramp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* https://www.pramp.com/challenge/W5EJq2Jld3t2ny9jyZXG
* @author baibhav <baibhavr@gmail.com>
* 12:17:27 PM Nov 11, 2021
*/
public class WordCountEngine {
/**
* Count {practice:3,just:1,by:1,perfect:2,get:1,only:1,youll:1,makes:1}
* Ordered
* { 1: makes,youll,only,get,by,just
* 2: perfect
* 3: practice
* }
*/
static String[][] wordCountEngine(String document) {
String[] words = document.replaceAll("\\p{P}", "").toLowerCase().split("\\s+");
Map<String, Integer> count = new HashMap<>();
Map<Integer, LinkedHashSet<String>> ordered = new LinkedHashMap<>();
for (int i = words.length - 1; i != -1; i--) {
String word = words[i];
if (count.containsKey(word)) {
int freq = count.get(word);
count.put(word, freq + 1);
ordered.get(freq++).remove(word);
if (!ordered.containsKey(freq))
ordered.put(freq, new LinkedHashSet<String>());
ordered.get(freq).add(word);
} else {
count.put(word, 1);
if (!ordered.containsKey(1))
ordered.put(1, new LinkedHashSet<String>());
ordered.get(1).add(word);
}
}
String[][] ans = new String[count.size()][];
int index = 0;
for (int i = words.length - 1; i > 0; i--) {
if (ordered.containsKey(i) && ordered.get(i).size() != 0) {
String freq = i + "";
List<String> list = new ArrayList<>(ordered.get(i));
Collections.reverse(list);
for (String w : list)
ans[index++] = new String[] { w, freq };
}
}
return ans;
}
public static void main(String[] args) {
String[][] ans = wordCountEngine("Practice makes perfect. you'll only get Perfect by practice. just practice!");
for (String[] tuple : ans)
System.out.println(Arrays.asList(tuple));
}
}
| 25.415584
| 114
| 0.635156
|
4164293ed34c474cb9d1c9055a45b51a92e5e558
| 386
|
package org.support.project.di;
import java.lang.reflect.Method;
public class TestAdvice2 implements org.support.project.aop.Advice<TestObject> {
@Override
public Object invoke(TestObject object, Method method, Object[] args) throws Throwable {
System.out.println("TestAdvice2 point cut");
// 実際のコードを呼び出し
Object ret = method.invoke(object, args);
return ret;
}
}
| 19.3
| 89
| 0.740933
|
6f733cba5a0df6bb7a2092a0fbb2d0877e9e1787
| 1,460
|
package org.openntf.domino.xots;
/**
* @author Paul Withers
* @since 2.5.0
*
*/
public class XotsContext {
private String contextApiPath;
private String openLogApiPath;
private String taskletClass;
/**
* Getter for contextApiPath
*
* @return String ApiPath of database to act upon
*/
public String getContextApiPath() {
return contextApiPath;
}
/**
* Setter for contextApiPath
*
* @param contextApiPath
* String ApiPath of database to act upon
*/
public void setContextApiPath(final String contextApiPath) {
this.contextApiPath = contextApiPath;
}
/**
* Getter for openLogApiPath
*
* @return String ApiPath of OpenLog database to log to
*/
public String getOpenLogApiPath() {
return openLogApiPath;
}
/**
* Setter for openLogApiPath
*
* @param openLogApiPath
* String ApiPath of OpenLog database to log to
*/
public void setOpenLogApiPath(final String openLogApiPath) {
this.openLogApiPath = openLogApiPath;
}
/**
* Getter for taskletClass
*
* @return String tasklet class to log for in OpenLog
*/
public String getTaskletClass() {
return taskletClass;
}
/**
* Setter for taskletClass
*
* @param taskletClass
* String tasklet class to log for in OpenLog
*/
public void setTaskletClass(final String taskletClass) {
this.taskletClass = taskletClass;
}
}
| 20.56338
| 62
| 0.65411
|
cc686121a9fac94fc9752cc884b5ca88838b8b79
| 7,121
|
/*
* JPPF.
* Copyright (C) 2005-2019 JPPF Team.
* http://www.jppf.org
*
* 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 test.org.jppf.test.runner;
import java.io.Serializable;
import java.util.*;
import org.jppf.utils.collections.*;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
/**
* Holds ther results of a JUnit runner as well as exceptions that occured
* outside of the runner scope.
* @author Laurent Cohen
*/
public class ResultHolder implements Serializable {
/**
* Explicit serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* Holds exceptions that occurred outside of the JUnit runner.
*/
private final List<ExceptionHolder> exceptions = new ArrayList<>();
/**
* Holds all failures.
*/
//private final Map<String, List<Failure>> failureMap = new TreeMap<>();
private final CollectionMap<String, Failure> failureMap = new LinkedListSortedMap<>();
/**
* Holds all ingored tests.
*/
//private final Map<String, List<Description>> ignoredMap = new TreeMap<>();
private final CollectionMap<String, Description> ignoredMap = new LinkedListSortedMap<>();
/**
* Holds all failures.
*/
//private final Map<String, List<Description>> successMap = new TreeMap<>();
private final CollectionMap<String, Description> successMap = new LinkedListSortedMap<>();
/**
* A sorted set of classes that were run.
*/
private final Set<String> classes = new TreeSet<>();
/**
*
*/
private transient Set<String> tests = new HashSet<>();
/**
* The test run start time.
*/
private long startTime = 0L;
/**
* The test run start time.
*/
private long endTime = 0L;
/**
* The count of failed tests.
*/
private int failureCount = 0;
/**
* The count of ignored tests.
*/
private int ignoredCount = 0;
/**
* The count of successful tests.
*/
private int successCount = 0;
/**
* Initialize this result holder.
*/
public ResultHolder() {
}
/**
* Add a new exception.
* @param holder holds the exception to add.
*/
public void addException(final ExceptionHolder holder) {
exceptions.add(holder);
}
/**
* Get the exceptions that occurred outside of the JUnit runner.
* @return a list of <code>ExceptionHolder</code> instances.
*/
public List<ExceptionHolder> getExceptions() {
return exceptions;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ResultHolder[");
sb.append("testsCount=").append(getTestsCount()).append(", failureCount=").append(failureCount).append(", successCount=").append(successCount);
sb.append(", failures=").append(failureMap).append(", successes=").append(successMap);
sb.append(", exceptions=").append(exceptions);
sb.append(']');
return sb.toString();
}
/**
* Add a test failure.
* @param failure the failure to add.
*/
public void addFailure(final Failure failure) {
final Description d = failure.getDescription();
//CollectionUtils.putInListMap(d.getClassName(), failure, failureMap);
failureMap.putValue(d.getClassName(), failure);
processDescription(d);
failureCount++;
}
/**
* Get the failures.
* @return a map of failed tests grouped by class name.
*/
public CollectionMap<String, Failure> getFailures() {
return failureMap;
}
/**
* Add an ignored test.
* @param desc the description of the ignored test.
*/
public void addIgnored(final Description desc) {
//CollectionUtils.putInListMap(desc.getClassName(), desc, ignoredMap);
ignoredMap.putValue(desc.getClassName(), desc);
processDescription(desc);
ignoredCount++;
}
/**
* Get the ignored tests.
* @return a map of ignored tests grouped by class name.
*/
public CollectionMap<String, Description> getIngored() {
return ignoredMap;
}
/**
* Add a successful test.
* @param desc the description of the successful test.
*/
public void addSuccess(final Description desc) {
//CollectionUtils.putInListMap(desc.getClassName(), desc, successMap);
successMap.putValue(desc.getClassName(), desc);
processDescription(desc);
successCount++;
}
/**
* Process the specified test description.
* @param desc the test description.
*/
private void processDescription(final Description desc) {
final String name = desc.getClassName();
final String testName = name + "." + desc.getMethodName();
if (!classes.contains(name)) classes.add(name);
if (!tests.contains(testName)) tests.add(testName);
}
/**
* Get the successful tests.
* @return a map of successful tests grouped by class name.
*/
public CollectionMap<String, Description> getSuccesses() {
return successMap;
}
/**
* Get the test run start time.
* @return the start time as a long.
*/
public long getStartTime() {
return startTime;
}
/**
* Set the test run start time.
* @param time the start time as a long.
*/
public void setStartTime(final long time) {
this.startTime = time;
}
/**
* Get the test run end time.
* @return the end time as a long.
*/
public long getEndTime() {
return endTime;
}
/**
* Set the test run end time.
* @param time the end time as a long.
*/
public void setEndTime(final long time) {
this.endTime = time;
}
/**
* Get the total number of tests.
* @return the number of tests as an int.
*/
public int getTestsCount() {
return failureCount + ignoredCount + successCount;
}
/**
* Get the count of failed tests.
* @return the count as an int.
*/
public int getFailureCount() {
return failureCount;
}
/**
* Get the count of ignored tests.
* @return the count as an int.
*/
public int getIgnoredCount() {
return ignoredCount;
}
/**
* Get the count of successful tests.
* @return the count as an int.
*/
public int getSuccessCount() {
return successCount;
}
/**
* Determine whether this result holder already has the specified test.
* @param desc the description of th etest to look for.
* @return <code>true</code> if the test already exists, <code>false</code> otherwise.
*/
public boolean hasTest(final Description desc) {
final String name = desc.getClassName() + "." + desc.getMethodName();
return tests.contains(name);
}
/**
* Get the sorted set of classes that were run.
* @return a set of string class names.
*/
public Set<String> getClasses() {
return classes;
}
}
| 26.472119
| 147
| 0.666058
|
2604f25f290dbd9e790878e1aadf816aba2e0940
| 2,667
|
package com.lanking.cloud.job.doQuestionRank.DAO.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.lanking.cloud.component.db.support.hibernate.Repo;
import com.lanking.cloud.component.db.support.hibernate.dao.AbstractHibernateDAO;
import com.lanking.cloud.domain.yoomath.stat.DoQuestionClassRank;
import com.lanking.cloud.job.doQuestionRank.DAO.DoQuestionClassRankDAO;
import com.lanking.cloud.sdk.data.CursorPage;
import com.lanking.cloud.sdk.data.CursorPageable;
import com.lanking.cloud.sdk.data.Params;
@Component
public class DoQuestionClassRankDAOImpl extends AbstractHibernateDAO<DoQuestionClassRank, Long>
implements DoQuestionClassRankDAO {
@Override
public DoQuestionClassRank findStudentInClassRank(long classId, int startDate, int endDate, long userId) {
Params param = Params.param();
param.put("classId", classId);
param.put("userId", userId);
param.put("startDate", startDate);
param.put("endDate", endDate);
return repo.find("$findStudentInClassRank", param).get();
}
@Override
public DoQuestionClassRank save(DoQuestionClassRank doQuestionClassRank) {
return repo.save(doQuestionClassRank);
}
@Override
public List<Long> getClassIds(int startDate, int endDate, int startindex, int size) {
Params param = Params.param();
param.put("startDate", startDate);
param.put("endDate", endDate);
param.put("startindex", startindex);
param.put("size", size);
return repo.find("$findClassIds", param).list(Long.class);
}
@Override
public List<DoQuestionClassRank> findStudentInClassRanks(List<Long> classIds, int startDate, int endDate) {
Params param = Params.param();
param.put("classIds", classIds);
param.put("startDate", startDate);
param.put("endDate", endDate);
return repo.find("$findStudentInClassRanks", param).list();
}
@Override
public List<DoQuestionClassRank> saves(List<DoQuestionClassRank> doQuestionClassRanks) {
return repo.save(doQuestionClassRanks);
}
@Override
public CursorPage<Long, DoQuestionClassRank> getAllRankPraiseByCursor(int startDate, int endDate,
CursorPageable<Long> pageable) {
Params param = Params.param();
param.put("startDate", startDate);
param.put("endDate", endDate);
return repo.find("$findAllRankPraiseByCursor", param).fetch(pageable);
}
@Autowired
@Qualifier("DoQuestionClassRankRepo")
@Override
public void setRepo(Repo<DoQuestionClassRank, Long> repo) {
this.repo = repo;
}
}
| 32.925926
| 109
| 0.753281
|
ba85b81d90767cecf51a77477a76fa00746b2ca1
| 416
|
package collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* 集合仅能存放引用类型元素,并且存放的是元素引用地址
*
* 如果存放基本类型则会转换为包装类进行保存。
* @author wm
*/
public class CollectionDemo3 {
public static void main(String[] args) {
Collection c=new ArrayList();
Point p=new Point(1,2);
c.add(p);
p.setX(2);
System.out.println(p);
System.out.println(c);
}
}
| 16
| 44
| 0.615385
|
c90f30740a6106b0ff76fa59ab78e1dd8d816190
| 998
|
package org.jeecg.modules.demo.trace.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jeecg.modules.demo.index.vo.MedicinalVO;
import java.util.List;
/**
* 追溯展示类
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "追溯结果集", description = "追溯结果集")
public class TraceVO {
/**
* 种植环节
*/
@ApiModelProperty(value = "种植环节")
private PlantTraceVO plantTraceVO;
/**
* 药材经营
*/
@ApiModelProperty(value = "药材经营")
private List<MedicineTraceVO> medicineVOList;
/**
* 饮片加工
*/
@ApiModelProperty(value = "饮片加工")
private YpProcessTraceVO ypProcessVO;
/**
* 饮片经营
*/
@ApiModelProperty(value = "饮片经营")
private List<YpBusinessTraceVO> ypBusinessTraceVOList;
/**
* 药材图片
*/
@ApiModelProperty(value = "药材图片")
private MedicinalVO medicinalImageVO;
}
| 19.568627
| 58
| 0.675351
|
76320384244037c632c750683dac6cac6574d2a0
| 4,774
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016. Diorite (by Bartłomiej Mazur (aka GotoFinal))
*
* 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.diorite.material.blocks;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.BlockFace;
import org.diorite.material.AttachableMat;
import org.diorite.material.BlockMaterialData;
import org.diorite.material.Material;
import org.diorite.material.PowerableMat;
/**
* Abstract class for all RedstoneTorch-based blocks
*/
public abstract class RedstoneTorchMat extends BlockMaterialData implements PowerableMat, AttachableMat
{
protected final BlockFace face;
public RedstoneTorchMat(final String enumName, final int id, final String minecraftId, final BlockFace face, final float hardness, final float blastResistance)
{
super(enumName, id, minecraftId, (face == BlockFace.SELF) ? "ITEM" : face.name(), combine(face), hardness, blastResistance);
this.face = face;
}
public RedstoneTorchMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final byte type, final BlockFace face, final float hardness, final float blastResistance)
{
super(enumName, id, minecraftId, maxStack, typeName, type, hardness, blastResistance);
this.face = face;
}
@Override
public RedstoneTorchMat getPowered(final boolean powered)
{
return getRedstoneTorch(powered);
}
@Override
public BlockFace getBlockFacing()
{
return this.face;
}
@Override
public abstract RedstoneTorchMat getType(final int type);
@Override
public abstract RedstoneTorchMat getType(final String type);
@Override
public abstract RedstoneTorchMat[] types();
@Override
public abstract RedstoneTorchMat getAttachedFace(final BlockFace face);
@Override
public abstract RedstoneTorchMat getBlockFacing(final BlockFace face);
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("face", this.face).toString();
}
protected static byte combine(final BlockFace face)
{
switch (face)
{
case SELF:
return 0x0;
case EAST:
return 0x2;
case SOUTH:
return 0x3;
case NORTH:
return 0x4;
case UP:
return 0x5;
default:
return 0x1;
}
}
/**
* Returns one of RedstoneTorch sub-type based on powered state.
* It will never return null.
*
* @param powered if RedstoneTorch should be powered.
*
* @return sub-type of RedstoneTorch
*/
public static RedstoneTorchMat getRedstoneTorch(final boolean powered)
{
if (powered)
{
return Material.REDSTONE_TORCH_ON;
}
else
{
return Material.REDSTONE_TORCH_OFF;
}
}
/**
* Returns one of RedstoneTorch sub-type based on powered state and {@link BlockFace}.
* It will never return null.
*
* @param powered if RedstoneTorch should be powered.
* @param face facing direction of torch.
*
* @return sub-type of RedstoneTorch
*/
public static RedstoneTorchMat getRedstoneTorch(final boolean powered, final BlockFace face)
{
if (powered)
{
return RedstoneTorchOnMat.getRedstoneTorchOn(face);
}
else
{
return RedstoneTorchOffMat.getRedstoneTorchOff(face);
}
}
}
| 32.256757
| 223
| 0.679095
|
85f5f81114777a520291d66a199989829b5b6ef0
| 10,784
|
/*-
* #%L
* Molecule Archive Suite (Mars) - core data storage and processing algorithms.
* %%
* Copyright (C) 2018 - 2022 Karl Duderstadt
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package de.mpg.biochem.mars.molecule.commands;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.decimal4j.util.DoubleRounder;
import org.scijava.app.StatusService;
import org.scijava.command.Command;
import org.scijava.command.DynamicCommand;
import org.scijava.log.LogService;
import org.scijava.menu.MenuConstants;
import org.scijava.module.MutableModuleItem;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;
import org.scijava.widget.ChoiceWidget;
import de.mpg.biochem.mars.metadata.MarsMetadata;
import de.mpg.biochem.mars.molecule.Molecule;
import de.mpg.biochem.mars.molecule.MoleculeArchive;
import de.mpg.biochem.mars.molecule.MoleculeArchiveIndex;
import de.mpg.biochem.mars.molecule.MoleculeArchiveProperties;
import de.mpg.biochem.mars.molecule.MoleculeArchiveService;
import de.mpg.biochem.mars.table.MarsTable;
import de.mpg.biochem.mars.util.LogBuilder;
import de.mpg.biochem.mars.util.MarsRegion;
import net.imagej.ops.Initializable;
@Plugin(type = Command.class, label = "Region Difference Calculator", menu = {
@Menu(label = MenuConstants.PLUGINS_LABEL,
weight = MenuConstants.PLUGINS_WEIGHT,
mnemonic = MenuConstants.PLUGINS_MNEMONIC), @Menu(label = "Mars",
weight = MenuConstants.PLUGINS_WEIGHT, mnemonic = 'm'), @Menu(
label = "Molecule", weight = 2, mnemonic = 'm'), @Menu(label = "Util",
weight = 7, mnemonic = 'u'), @Menu(
label = "Region Difference Calculator", weight = 10,
mnemonic = 'o') })
public class RegionDifferenceCalculatorCommand extends DynamicCommand implements
Command, Initializable
{
@Parameter
private LogService logService;
@Parameter
private StatusService statusService;
@Parameter
private MoleculeArchiveService moleculeArchiveService;
@Parameter
private UIService uiService;
@Parameter(callback = "archiveSelectionChanged", label = "MoleculeArchive")
private MoleculeArchive<Molecule, MarsMetadata, MoleculeArchiveProperties<Molecule, MarsMetadata>, MoleculeArchiveIndex<Molecule, MarsMetadata>> archive;
@Parameter(label = "X Column", choices = { "a", "b", "c" })
private String xColumn;
@Parameter(label = "Y Column", choices = { "a", "b", "c" })
private String yColumn;
@Parameter(label = "Region source:",
style = ChoiceWidget.RADIO_BUTTON_HORIZONTAL_STYLE, choices = { "Molecules",
"Metadata" })
private String regionSource;
@Parameter(label = "Region 1 name")
private String regionOneName;
@Parameter(label = "Region 2 name")
private String regionTwoName;
@Parameter(label = "Parameter Name")
private String ParameterName;
// -- Callback methods --
private void archiveSelectionChanged() {
ArrayList<String> columns = new ArrayList<String>();
columns.addAll(archive.properties().getColumnSet());
columns.sort(String::compareToIgnoreCase);
final MutableModuleItem<String> xColumnItems = getInfo().getMutableInput(
"xColumn", String.class);
xColumnItems.setChoices(columns);
final MutableModuleItem<String> yColumnItems = getInfo().getMutableInput(
"yColumn", String.class);
yColumnItems.setChoices(columns);
}
@Override
public void initialize() {
ArrayList<String> columns = new ArrayList<String>();
columns.addAll(moleculeArchiveService.getArchives().get(0).properties()
.getColumnSet());
columns.sort(String::compareToIgnoreCase);
final MutableModuleItem<String> xColumnItems = getInfo().getMutableInput(
"xColumn", String.class);
xColumnItems.setChoices(columns);
final MutableModuleItem<String> yColumnItems = getInfo().getMutableInput(
"yColumn", String.class);
yColumnItems.setChoices(columns);
}
@Override
public void run() {
// Let's keep track of the time it takes
double starttime = System.currentTimeMillis();
// Build log message
LogBuilder builder = new LogBuilder();
String log = LogBuilder.buildTitleBlock("Region Difference Calculator");
addInputParameterLog(builder);
log += builder.buildParameterList();
// Output first part of log message...
logService.info(log);
archive.getWindow().updateLockMessage("Calculating Region Differences...");
archive.logln(log);
if (regionSource.equals("Molecules")) {
// Loop through each molecule and add reversal difference value to
// parameters for each molecule
archive.getMoleculeUIDs().parallelStream().forEach(UID -> {
Molecule molecule = archive.get(UID);
if (!molecule.hasRegion(regionOneName) || !molecule.hasRegion(
regionTwoName)) return;
MarsTable datatable = molecule.getTable();
double region1_mean = datatable.mean(yColumn, xColumn, molecule
.getRegion(regionOneName).getStart(), molecule.getRegion(
regionOneName).getEnd());
double region2_mean = datatable.mean(yColumn, xColumn, molecule
.getRegion(regionTwoName).getStart(), molecule.getRegion(
regionTwoName).getEnd());
molecule.setParameter(ParameterName, region1_mean - region2_mean);
archive.put(molecule);
});
}
else {
// Before we start we should build a Map of region information from the
// image metadata records
// then we can use the map as we go through the molecules.
// This will be most efficient.
ConcurrentMap<String, MarsRegion> metadataRegionOneMap =
new ConcurrentHashMap<String, MarsRegion>();
ConcurrentMap<String, MarsRegion> metadataRegionTwoMap =
new ConcurrentHashMap<String, MarsRegion>();
archive.getMetadataUIDs().parallelStream().forEach(metaUID -> {
MarsMetadata metadata = archive.getMetadata(metaUID);
if (metadata.hasRegion(regionOneName)) metadataRegionOneMap.put(metaUID,
metadata.getRegion(regionOneName));
if (metadata.hasRegion(regionTwoName)) metadataRegionTwoMap.put(metaUID,
metadata.getRegion(regionTwoName));
});
// Loop through each molecule and add reversal difference value to
// parameters for each molecule
archive.getMoleculeUIDs().parallelStream().forEach(UID -> {
String metaUID = archive.getMetadataUIDforMolecule(UID);
if (!metadataRegionOneMap.containsKey(metaUID) && !metadataRegionTwoMap
.containsKey(metaUID)) return;
MarsRegion regionOne = metadataRegionOneMap.get(metaUID);
MarsRegion regionTwo = metadataRegionTwoMap.get(metaUID);
Molecule molecule = archive.get(UID);
MarsTable datatable = molecule.getTable();
double region1_mean = datatable.mean(yColumn, xColumn, regionOne
.getStart(), regionOne.getEnd());
double region2_mean = datatable.mean(yColumn, xColumn, regionTwo
.getStart(), regionTwo.getEnd());
molecule.setParameter(ParameterName, region1_mean - region2_mean);
archive.put(molecule);
});
}
logService.info("Time: " + DoubleRounder.round((System.currentTimeMillis() -
starttime) / 60000, 2) + " minutes.");
logService.info(LogBuilder.endBlock(true));
archive.logln("\n" + LogBuilder.endBlock(true));
archive.logln(" ");
}
private void addInputParameterLog(LogBuilder builder) {
builder.addParameter("MoleculeArchive", archive.getName());
builder.addParameter("X Column", xColumn);
builder.addParameter("Y Column", yColumn);
builder.addParameter("Region source", regionSource);
builder.addParameter("Region 1 name", regionOneName);
builder.addParameter("Region 2 name", regionTwoName);
builder.addParameter("Parameter Name", ParameterName);
}
public static double calcRegionDifference(Molecule molecule, String xColumn,
String yColumn, MarsRegion regionOne, MarsRegion regionTwo,
String parameterName)
{
MarsTable datatable = molecule.getTable();
double region1_mean = datatable.mean(yColumn, xColumn, regionOne.getStart(),
regionOne.getEnd());
double region2_mean = datatable.mean(yColumn, xColumn, regionTwo.getStart(),
regionTwo.getEnd());
double parameterValue = region1_mean - region2_mean;
molecule.setParameter(parameterName, parameterValue);
return parameterValue;
}
// Getters and Setters
public void setArchive(
MoleculeArchive<Molecule, MarsMetadata, MoleculeArchiveProperties<Molecule, MarsMetadata>, MoleculeArchiveIndex<Molecule, MarsMetadata>> archive)
{
this.archive = archive;
}
public
MoleculeArchive<Molecule, MarsMetadata, MoleculeArchiveProperties<Molecule, MarsMetadata>, MoleculeArchiveIndex<Molecule, MarsMetadata>>
getArchive()
{
return archive;
}
public void setXColumn(String xColumn) {
this.xColumn = xColumn;
}
public String getXColumn() {
return xColumn;
}
public void setYColumn(String yColumn) {
this.yColumn = yColumn;
}
public String getYColumn() {
return yColumn;
}
public void setRegionSource(String regionSource) {
this.regionSource = regionSource;
}
public String getRegionSource() {
return this.regionSource;
}
public void setRegionOne(String regionOneName) {
this.regionOneName = regionOneName;
}
public String getRegionOne() {
return this.regionOneName;
}
public void setRegionTwo(String regionTwoName) {
this.regionTwoName = regionTwoName;
}
public String getRegionTwo() {
return this.regionTwoName;
}
public void setParameterName(String ParameterName) {
this.ParameterName = ParameterName;
}
public String getParameterName() {
return ParameterName;
}
}
| 33.490683
| 154
| 0.753431
|
368f981278b4b59a421ca68c89bd7d74f0533842
| 3,013
|
package ru.dadata.api.entity;
import com.google.gson.annotations.SerializedName;
/**
* @author leon0399
*/
public class Phone extends AbstractEntity {
@SerializedName("type")
private String type;
@SerializedName("phone")
private String phone;
@SerializedName("country_code")
private String countryCode;
@SerializedName("city_code")
private String cityCode;
@SerializedName("number")
private String number;
@SerializedName("extension")
private String extension;
@SerializedName("provider")
private String provider;
@SerializedName("region")
private String region;
@SerializedName("timezone")
private String timezone;
@SerializedName("qc_conflict")
private int qcConflict;
/**
* @return Исходный телефон одной строкой
*/
@Override
public String getSource() {
return super.getSource();
}
/**
* @return Тип телефона
*/
public String getType() {
return type;
}
/**
* @return Стандартизованный телефон одной строкой
*/
public String getPhone() {
return phone;
}
/**
* @return Код страны
*/
public String getCountryCode() {
return countryCode;
}
/**
* @return Код города / DEF-код
*/
public String getCityCode() {
return cityCode;
}
/**
* @return Локальный номер телефона
*/
public String getNumber() {
return number;
}
/**
* @return Добавочный номер
*/
public String getExtension() {
return extension;
}
/**
* @return Оператор связи
*/
public String getProvider() {
return provider;
}
/**
* @return Регион
*/
public String getRegion() {
return region;
}
/**
* @return Часовой пояс
*/
public String getTimezone() {
return timezone;
}
/**
* @return Признак конфликта телефона с адресом
* @see <a href="https://dadata.ru/api/clean/#qc_conflict">Информация о возвращаемых кодах</a>
*/
public int getQcConflict() {
return qcConflict;
}
/**
* @return Код проверки
* @see <a href="https://dadata.ru/api/clean/#qc-phone">Информация о возвращаемых кодах</a>
*/
@Override
public int getQc() {
return super.getQc();
}
@Override
public String toString() {
return "Phone[source=" + getSource() +
", type=" + getType() +
", phone=" + getPhone() +
", countryCode=" + getCountryCode() +
", cityCode=" + getCityCode() +
", number=" + getNumber() +
", extension=" + getExtension() +
", provider=" + getProvider() +
", region=" + getRegion() +
", timezone=" + getTimezone() +
", qcConflict=" + getQcConflict() +
", qc=" + getQc() +
"]";
}
}
| 20.77931
| 98
| 0.543644
|
1e2188fc6d33fe00f568d6d363ac248eef3055cf
| 5,468
|
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.scim;
import org.cloudfoundry.identity.uaa.constants.OriginKeys;
import org.cloudfoundry.identity.uaa.provider.IdentityProvider;
import org.cloudfoundry.identity.uaa.provider.IdentityProviderProvisioning;
import org.cloudfoundry.identity.uaa.provider.UaaIdentityProviderDefinition;
import org.cloudfoundry.identity.uaa.util.ObjectUtils;
import org.cloudfoundry.identity.uaa.web.ExceptionReport;
import org.cloudfoundry.identity.uaa.web.ExceptionReportHttpMessageConverter;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.NestedServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class DisableUserManagementSecurityFilter extends OncePerRequestFilter {
public static final String INTERNAL_USER_CREATION_IS_CURRENTLY_DISABLED = "Internal User Creation is currently disabled. External User Store is in use.";
private final IdentityProviderProvisioning identityProviderProvisioning;
private static String regex1 = "";
static {
// scim user endpoints
// ui controllers
regex1 = "^/Users/.*/password";
regex1 += "|^/Users/.*/verify";
regex1 += "|^/create_account";
regex1 += "|^/create_account.do";
regex1 += "|^/accounts/email_sent";
regex1 += "|^/verify_user";
regex1 += "|^/change_email";
regex1 += "|^/change_email.do";
regex1 += "|^/verify_email";
regex1 += "|^/change_password";
regex1 += "|^/change_password.do";
regex1 += "|^/forgot_password";
regex1 += "|^/forgot_password.do";
regex1 += "|^/email_sent";
regex1 += "|^/reset_password";
regex1 += "|^/reset_password.do";
}
private Pattern pattern1 = Pattern.compile(regex1);
private List<String> methods1 = Arrays.asList("GET", "POST", "PUT", "DELETE");
public DisableUserManagementSecurityFilter(IdentityProviderProvisioning identityProviderProvisioning) {
this.identityProviderProvisioning = identityProviderProvisioning;
}
@Override
protected void doFilterInternal(HttpServletRequest request, final HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
if (matches(request)) {
IdentityProvider idp = identityProviderProvisioning.retrieveByOriginIgnoreActiveFlag(OriginKeys.UAA, IdentityZoneHolder.get().getId());
boolean isDisableInternalUserManagement = false;
UaaIdentityProviderDefinition config = ObjectUtils.castInstance(idp.getConfig(), UaaIdentityProviderDefinition.class);
if (config != null) {
isDisableInternalUserManagement = config.isDisableInternalUserManagement();
}
if (isDisableInternalUserManagement) {
throw new InternalUserManagementDisabledException(INTERNAL_USER_CREATION_IS_CURRENTLY_DISABLED);
}
}
filterChain.doFilter(request, response);
} catch (InternalUserManagementDisabledException x) {
handleInternalUserManagementDisabledException(response, x);
} catch (NestedServletException x) {
if (x.getRootCause() instanceof InternalUserManagementDisabledException) {
handleInternalUserManagementDisabledException(response, (InternalUserManagementDisabledException) x.getRootCause());
} else {
throw x;
}
}
}
private void handleInternalUserManagementDisabledException(HttpServletResponse response, InternalUserManagementDisabledException x) throws IOException {
ExceptionReportHttpMessageConverter converter = new ExceptionReportHttpMessageConverter();
response.setStatus(403);
converter.write(new ExceptionReport(x), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
}
private boolean matches(HttpServletRequest request) {
return pattern1.matcher(getUri(request)).matches() && methods1.contains(request.getMethod());
}
private String getUri(HttpServletRequest request) {
if (request.getContextPath() != null && request.getContextPath().length() > 0) {
return request.getServletPath();
}
return request.getRequestURI();
}
}
| 47.547826
| 163
| 0.695135
|
dc8b6d8ac3185a7921d10bbb93bcb5b1f1f88b9d
| 8,890
|
/*
* 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 com.alipay.remoting.rpc.userprocessor.multiinterestprocessor;
import com.alipay.remoting.BizContext;
import com.alipay.remoting.InvokeContext;
import com.alipay.remoting.NamedThreadFactory;
import com.alipay.remoting.rpc.common.RequestBody;
import com.alipay.remoting.rpc.protocol.SyncMutiInterestUserProcessor;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @antuor muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:20 AM
*/
public class SimpleClientMultiInterestUserProcessor
extends
SyncMutiInterestUserProcessor<MultiInterestBaseRequestBody> {
/**
* logger
*/
private static final Logger logger = LoggerFactory
.getLogger(SimpleClientMultiInterestUserProcessor.class);
/**
* delay milliseconds
*/
private long delayMs;
/**
* whether delay or not
*/
private boolean delaySwitch;
/**
* executor
*/
private ThreadPoolExecutor executor;
/**
* default is true
*/
private boolean timeoutDiscard = true;
private AtomicInteger c1invokeTimes = new AtomicInteger();
private AtomicInteger c1onewayTimes = new AtomicInteger();
private AtomicInteger c1syncTimes = new AtomicInteger();
private AtomicInteger c1futureTimes = new AtomicInteger();
private AtomicInteger c1callbackTimes = new AtomicInteger();
private AtomicInteger c2invokeTimes = new AtomicInteger();
private AtomicInteger c2onewayTimes = new AtomicInteger();
private AtomicInteger c2syncTimes = new AtomicInteger();
private AtomicInteger c2futureTimes = new AtomicInteger();
private AtomicInteger c2callbackTimes = new AtomicInteger();
public SimpleClientMultiInterestUserProcessor() {
this.delaySwitch = false;
this.delayMs = 0;
this.executor = new ThreadPoolExecutor(1, 3, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(4), new NamedThreadFactory("Request-process-pool"));
}
public SimpleClientMultiInterestUserProcessor(long delay) {
this();
if (delay < 0) {
throw new IllegalArgumentException("delay time illegal!");
}
this.delaySwitch = true;
this.delayMs = delay;
}
public SimpleClientMultiInterestUserProcessor(long delay, int core, int max,
int keepaliveSeconds, int workQueue) {
this(delay);
this.executor = new ThreadPoolExecutor(core, max, keepaliveSeconds, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(workQueue), new NamedThreadFactory(
"Request-process-pool"));
}
// ~~~ override methods
@Override
public Object handleRequest(BizContext bizCtx, MultiInterestBaseRequestBody request)
throws Exception {
logger.warn("Request received:" + request);
if (bizCtx.isRequestTimeout()) {
String errMsg = "Stop process in client biz thread, already timeout!";
logger.warn(errMsg);
throw new Exception(errMsg);
}
if (request instanceof RequestBodyC1) {
Assert.assertEquals(RequestBodyC1.class, request.getClass());
return handleRequest(bizCtx, (RequestBodyC1) request);
} else if (request instanceof RequestBodyC2) {
Assert.assertEquals(RequestBodyC2.class, request.getClass());
return handleRequest(bizCtx, (RequestBodyC2) request);
} else {
throw new Exception("RequestBody does not belong to defined interests !");
}
}
private Object handleRequest(BizContext bizCtx, RequestBodyC1 request) {
Long waittime = (Long) bizCtx.getInvokeContext().get(InvokeContext.BOLT_PROCESS_WAIT_TIME);
Assert.assertNotNull(waittime);
if (logger.isInfoEnabled()) {
logger.info("Client User processor process wait time {}", waittime);
}
processTimes(request);
if (!delaySwitch) {
return RequestBodyC1.DEFAULT_CLIENT_RETURN_STR;
}
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
return RequestBodyC1.DEFAULT_CLIENT_RETURN_STR;
}
private Object handleRequest(BizContext bizCtx, RequestBodyC2 request) {
Long waittime = (Long) bizCtx.getInvokeContext().get(InvokeContext.BOLT_PROCESS_WAIT_TIME);
Assert.assertNotNull(waittime);
if (logger.isInfoEnabled()) {
logger.info("Client User processor process wait time {}", waittime);
}
processTimes(request);
if (!delaySwitch) {
return RequestBodyC2.DEFAULT_CLIENT_RETURN_STR;
}
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
return RequestBodyC2.DEFAULT_CLIENT_RETURN_STR;
}
@Override
public Executor getExecutor() {
return executor;
}
@Override
public boolean timeoutDiscard() {
return this.timeoutDiscard;
}
// ~~~ public methods
public int getInvokeTimesC1() {
return this.c1invokeTimes.get();
}
public int getInvokeTimesC2() {
return this.c2invokeTimes.get();
}
public int getInvokeTimesEachCallTypeC1(RequestBody.InvokeType type) {
return new int[]{this.c1onewayTimes.get(), this.c1syncTimes.get(),
this.c1futureTimes.get(), this.c1callbackTimes.get()}[type.ordinal()];
}
public int getInvokeTimesEachCallTypeC2(RequestBody.InvokeType type) {
return new int[]{this.c2onewayTimes.get(), this.c2syncTimes.get(),
this.c2futureTimes.get(), this.c2callbackTimes.get()}[type.ordinal()];
}
// ~~~ private methods
private void processTimes(RequestBodyC1 req) {
this.c1invokeTimes.incrementAndGet();
if (req.getMsg().equals(RequestBodyC1.DEFAULT_ONEWAY_STR)) {
this.c1onewayTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC1.DEFAULT_SYNC_STR)) {
this.c1syncTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC1.DEFAULT_FUTURE_STR)) {
this.c1futureTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC1.DEFAULT_CALLBACK_STR)) {
this.c1callbackTimes.incrementAndGet();
}
}
private void processTimes(RequestBodyC2 req) {
this.c2invokeTimes.incrementAndGet();
if (req.getMsg().equals(RequestBodyC2.DEFAULT_ONEWAY_STR)) {
this.c2onewayTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC2.DEFAULT_SYNC_STR)) {
this.c2syncTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC2.DEFAULT_FUTURE_STR)) {
this.c2futureTimes.incrementAndGet();
} else if (req.getMsg().equals(RequestBodyC2.DEFAULT_CALLBACK_STR)) {
this.c2callbackTimes.incrementAndGet();
}
}
// ~~~ getters and setters
/**
* Getter method for property <tt>timeoutDiscard</tt>.
*
* @return property value of timeoutDiscard
*/
public boolean isTimeoutDiscard() {
return timeoutDiscard;
}
/**
* Setter method for property <tt>timeoutDiscard<tt>.
*
* @param timeoutDiscard value to be assigned to property timeoutDiscard
*/
public void setTimeoutDiscard(boolean timeoutDiscard) {
this.timeoutDiscard = timeoutDiscard;
}
@Override
public List<String> multiInterest() {
List<String> list = new ArrayList<String>();
list.add(RequestBodyC1.class.getName());
list.add(RequestBodyC2.class.getName());
return list;
}
}
| 35.56
| 101
| 0.670191
|
3cf6a0d08fc8721af04c620b429dd66a0a69fc4e
| 2,243
|
/*
* Copyright (c) 2011, Paul Merlin. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qipki.crypto;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class DefaultCryptoContext
implements CryptoContext
{
private final String providerName;
private final SecureRandom random;
public DefaultCryptoContext()
throws NoSuchAlgorithmException
{
this( BouncyCastleProvider.PROVIDER_NAME, "SHA1PRNG", 128 );
}
public DefaultCryptoContext( String randomAlgorithm )
throws NoSuchAlgorithmException
{
this( BouncyCastleProvider.PROVIDER_NAME, randomAlgorithm, 128 );
}
public DefaultCryptoContext( String randomAlgorithm, int seedSize )
throws NoSuchAlgorithmException
{
this( BouncyCastleProvider.PROVIDER_NAME, randomAlgorithm, seedSize );
}
public DefaultCryptoContext( String providerName, String randomAlgorithm, int seedSize )
throws NoSuchAlgorithmException
{
this.providerName = providerName;
this.random = SecureRandom.getInstance( "SHA1PRNG" );
this.random.setSeed( random.generateSeed( 128 ) );
}
public DefaultCryptoContext( SecureRandom random )
{
this( BouncyCastleProvider.PROVIDER_NAME, random );
}
public DefaultCryptoContext( String providerName, SecureRandom random )
{
this.providerName = providerName;
this.random = random;
}
@Override
public String providerName()
{
return providerName;
}
@Override
public SecureRandom random()
{
return random;
}
}
| 29.12987
| 92
| 0.71333
|
7b96f8a8ccec0b4c792b4b646cbce8527d7aae7a
| 1,633
|
package me.etki.tasks.revolving.di.database;
import com.google.inject.Inject;
import com.google.inject.Provider;
import me.etki.tasks.revolving.database.PersistenceUnit;
import me.etki.tasks.revolving.database.entity.AccountEntity;
import me.etki.tasks.revolving.database.entity.RateEntity;
import me.etki.tasks.revolving.database.entity.TransferEntity;
import org.h2.Driver;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.jpa.HibernatePersistenceProvider;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HibernateProvider implements Provider<EntityManagerFactory> {
private final DataSource source;
@Inject
public HibernateProvider(DataSource source) {
this.source = source;
}
@Override
public EntityManagerFactory get() {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", H2Dialect.class);
properties.put("hibernate.driver_class", Driver.class);
properties.put("hibernate.connection.isolation", Connection.TRANSACTION_REPEATABLE_READ);
properties.put("hibernate.connection.datasource", source);
List<Class> entities = Arrays.asList(AccountEntity.class, RateEntity.class, TransferEntity.class);
PersistenceUnitInfo unit = new PersistenceUnit(source, entities);
return new HibernatePersistenceProvider().createContainerEntityManagerFactory(unit, properties);
}
}
| 38.880952
| 106
| 0.778322
|
7e9763357726bf00ee8215d8961d6978498a2170
| 81,368
|
package com.zyh5games.controller;
import com.alibaba.fastjson.JSONObject;
import com.zyh5games.entity.Account;
import com.zyh5games.entity.GameNew;
import com.zyh5games.entity.UOrder;
import com.zyh5games.jedis.JedisRechargeCache;
import com.zyh5games.sdk.UOrderManager;
import com.zyh5games.sdk.channel.BaseChannel;
import com.zyh5games.sdk.channel.ChannelHandler;
import com.zyh5games.sdk.channel.HttpService;
import com.zyh5games.service.AccountService;
import com.zyh5games.service.GameNewService;
import com.zyh5games.util.DateUtil;
import com.zyh5games.util.FeeUtils;
import com.zyh5games.util.MD5Util;
import com.zyh5games.util.ResponseUtil;
import com.zyh5games.util.enums.OrderState;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* @author song minghua
* @date 2019/11/27
*/
@Controller
@RequestMapping("/sdkPay")
public class PayCallbackController {
private static final Logger log = Logger.getLogger(PayCallbackController.class);
public static String[] keys = {"createRole", "levelUp", "enterGame", "exitGame"};
@Autowired
JedisRechargeCache cache;
@Resource
ChannelHandler channelHandler;
@Resource
private UOrderManager orderManager;
@Resource
private AccountService accountService;
@Resource
private GameNewService gameNewService;
@Resource
private HttpService httpService;
/**
* 检查订单并发货 通用方法
*
* @param appId 指悦游戏id
* @param channelId 指悦渠道id
* @param channelOrderId 渠道订单id
* @param cpOrderId cp订单id
* @param channelOrder 给cp的参数-函数内赋值
* @param money 金额 元
*/
public boolean checkOrder(Integer appId, Integer channelId,
Map<String, String> parameterMap, JSONObject channelOrder,
String cpOrderId, String channelOrderId, String money) throws Exception {
boolean result = true;
do {
BaseChannel channelSerivce = channelHandler.getChannel(channelId);
boolean channelCheck = channelSerivce.channelPayCallback(appId, parameterMap, channelOrder);
if (!channelCheck) {
result = false;
break;
}
if (cpOrderId == null || cpOrderId.isEmpty()) {
cpOrderId = channelOrder.getString("cpOrderId");
}
if (channelOrderId == null || channelOrderId.isEmpty()) {
channelOrderId = channelOrder.getString("channelOrderId");
}
UOrder order = orderManager.getCpOrder(String.valueOf(appId), String.valueOf(channelId), cpOrderId);
if (order == null) {
log.info("订单为空");
result = false;
break;
}
//某些清况 检查金额 todo
if (!channelSerivce.checkOrderMoney(money, order)) {
return false;
}
//检查uid
Integer zhiyueUid = order.getUserID();
channelOrder.replace("zy_uid", zhiyueUid);
log.info("start OrderState = " + order.getState());
boolean first = false;
boolean isReturn = false;
switch (order.getState()) {
case OrderState.STATE_OPEN_PAY: {
// 首次回调 已完成支付 但未发货
order.setState(OrderState.STATE_PAY_SUCCESS);
order.setChannelOrderID(channelOrderId);
order.setRealMoney(Integer.parseInt(FeeUtils.yuanToFen(money)));
order.setSdkOrderTime(DateUtil.formatDate(System.currentTimeMillis(), DateUtil.FORMAT_YYYY_MMDD_HHmmSS));
orderManager.updateCpOrder(order);
first = true;
}
break;
case OrderState.STATE_PAY_SUCCESS: {
// 多次回调 已完成支付 申请发货未发货
log.info("checkOrder 支付成功待发货 order = " + order.getOrderID());
}
break;
case OrderState.STATE_PAY_FINISHED:
default:
isReturn = true;
break;
}
if (isReturn) {
return result;
}
// cp请求发货
GameNew gameNew = gameNewService.selectGame(appId, -1);
if (gameNew == null) {
result = false;
break;
}
//订单金额 非实际支付
String orderMoney = FeeUtils.fenToYuan(order.getMoney());
result = notifyToCp(first, gameNew, order, orderMoney, cpOrderId, channelId);
log.info(" end OrderState = " + order.getState());
} while (false);
log.info(" end result = " + result);
return result;
}
/**
* 渠道订单回调地址
* <p>
* 支付成功-核对订单 渠道->sdk回调->cp->通知sdk->渠道
* <p>
* 通知cp发货
* <p>
* 1.指悦支付 在 ijpay--master里面发货 这里不处理
* <p>
* 2.渠道在这里处理
*/
public boolean notifyToCp(boolean first, GameNew gameNew, UOrder order,
String price, String cpOrderId, Integer channelId) throws Exception {
log.info("notifyToCp");
boolean res = true;
do {
// cp验证订单并发货
String notifyUrl = gameNew.getPaybackUrl();
String md5Key = gameNew.getCallbacKey();
Integer appId = gameNew.getAppId();
Integer zhiyueUid = order.getUserID();
long orderId = order.getOrderID();
StringBuilder param = new StringBuilder();
param.append("amount").append("=").append(price);//金额 元
param.append("&").append("appId").append("=").append(appId);
param.append("&").append("cpOrderId").append("=").append(cpOrderId);
param.append("&").append("orderId").append("=").append(orderId);
param.append("&").append("productId").append("=").append(order.getProductID());
param.append("&").append("roleId").append("=").append(order.getRoleID());
String sdkSign = MD5Util.md5(param.toString() + md5Key);
param.append("&").append("sign").append("=").append(sdkSign);
String url = notifyUrl + param.toString();
JSONObject cpData = httpService.httpGetJson(url);
log.info("cp支付回调:" + cpData);
if (cpData.containsKey("code") && cpData.getInteger("code") == 1) {
order.setState(OrderState.STATE_PAY_FINISHED);
order.setCompleteTime(DateUtil.formatDate(System.currentTimeMillis(), DateUtil.FORMAT_YYYY_MMDD_HHmmSS));
orderManager.updateCpOrder(order);
} else {
res = false;
break;
}
log.info("first:" + first);
//支付成功 更新订单 redis-mysql
if (first) {
Account account = accountService.findAccountById(zhiyueUid);
log.info("account:" + (account != null));
if (account != null) {
cache.reqPay(String.valueOf(appId), order.getServerID(), String.valueOf(channelId), zhiyueUid, order.getRoleID(), order.getRealMoney(), account.getCreateTime());
}
}
} while (false);
return res;
}
/**
* 支付服通知
*
* @param orderId 指悦订单
* @param channelOrderId 渠道(敏付)订单
* @param amount 实际支付金额 元
* @param secretKey 32位随机秘钥
*/
@RequestMapping(value = "/minPay", method = RequestMethod.POST)
@ResponseBody
public void payServer(@RequestParam("orderId") String orderId,
@RequestParam("channelOrderId") String channelOrderId,
@RequestParam("amount") String amount,
@RequestParam("secretKey") String secretKey,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("payServer start ");
boolean result = false;
do {
String key = "CNnhJ0fjfLFZ7f70tsVbWYjESiPZ4Pgj";
if (!secretKey.equals(key)) {
log.info("payServer key error " + secretKey);
break;
}
UOrder order = orderManager.getUOrderById(orderId);
if (order == null) {
log.info("payServer order 不存在 " + orderId);
break;
}
Integer appId = order.getAppID();
// cp请求发货
GameNew gameNew = gameNewService.selectGame(appId, -1);
if (gameNew == null) {
log.info("payServer GameNew 不存在 " + appId);
break;
}
boolean first = false;
String fen = FeeUtils.yuanToFen(amount);
if (OrderState.STATE_OPEN_PAY == order.getState()) {
// 首次回调 已完成支付 但未发货
order.setState(OrderState.STATE_PAY_SUCCESS);
order.setChannelOrderID(channelOrderId);
order.setRealMoney(Integer.parseInt(fen));
order.setSdkOrderTime(DateUtil.formatDate(System.currentTimeMillis(), DateUtil.FORMAT_YYYY_MMDD_HHmmSS));
orderManager.updateCpOrder(order);
first = true;
} else if (OrderState.STATE_PAY_SUCCESS == order.getState()) {
} else {
return;
}
//订单金额 非实际支付
String orderMoney = FeeUtils.fenToYuan(order.getMoney());
result = notifyToCp(first, gameNew, order, orderMoney, order.getCpOrderId(), order.getChannelID());
} while (false);
ResponseUtil.write(response, result ? "success" : "fail");
log.info("payServer end " + result);
}
/**
* 模板
*/
@RequestMapping(value = "/callbackPayInfo/h5_example/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_example(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("cpOrderId") String cpOrderId,
@RequestParam("channelOrderId") String channelOrderId,
@RequestBody Map<String, Object> param,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("cpOrderId", cpOrderId);
parameterMap.put("channelOrderId", channelOrderId);
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, channelOrderId, amount);
ResponseUtil.write(response, result ? "success" : "fail");
log.info("h5_ziwan end " + result);
}
/**
* 紫菀
*
* @param openid 渠道玩家唯一标示
* @param price 商品金额
* @param other 其他信息
* @param item_id 商品id
* @param orderid 订单id
* @param sign 签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_ziwan/{channelId}/{appId}")
@ResponseBody
public void h5_ziwan(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("openid") String openid,
@RequestParam("price") String price,
@RequestParam("other") String other,
@RequestParam("item_id") String item_id,
@RequestParam("orderid") String orderid,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("h5_ziwan start " + "channelId=" + channelId + " appId=" + appId);
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("openid", openid);
parameterMap.put("price", price);
parameterMap.put("other", other);
parameterMap.put("item_id", item_id);
parameterMap.put("orderid", orderid);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
String money = price;
String cpOrderId = orderid;
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, "", money);
ResponseUtil.write(response, result ? "success" : "fail");
log.info("h5_ziwan end " + result);
}
/**
* 百家
* status String 是 是 订单状态。“success”为支付成功
* cpOrderId String 是 是 游戏方(cp)游戏订单号
* orderId String 是 是 我方订单ID
* uid string 是 是 用户UID (唯一) 我方用户的UID
* userName string 是 是 用户名
* money 是 是 商品价格(元) 例:1.00
* gameId String 是 是 游戏的id
* goodsId string 是 是 商品ID 没有的话。可以写1
* goodsName string 是 是 商品名,如:游戏币
* server string 是 是 支付时的游戏服
* role string 是 是 支付时角色信息,支付完后回传
* time int 是 是 当前时间unix时间戳
* ext string 否 否 额外透传参数(原样返回)
* signType string 是 否 固定值 md5
* sign string 是 否 加密串
*/
@RequestMapping(value = "/callbackPayInfo/h5_baijia/{channelId}/{appId}")
@ResponseBody
public void h5_baijia(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("status") String status,
@RequestParam("cpOrderId") String cpOrderId,
@RequestParam("orderId") String orderId,
@RequestParam("uid") String uid,
@RequestParam("userName") String userName,
@RequestParam("money") String money,
@RequestParam("gameId") String gameId,
@RequestParam("goodsId") String goodsId,
@RequestParam("goodsName") String goodsName,
@RequestParam("server") String server,
@RequestParam("role") String role,
@RequestParam("time") String time,
@RequestParam("ext") String ext,
@RequestParam("signType") String signType,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("status", status);
parameterMap.put("cpOrderId", cpOrderId);
parameterMap.put("orderId", orderId);
parameterMap.put("uid", uid);
parameterMap.put("userName", userName);
parameterMap.put("money", money);
parameterMap.put("gameId", gameId);
parameterMap.put("goodsId", goodsId);
parameterMap.put("goodsName", goodsName);
parameterMap.put("server", server);
parameterMap.put("role", role);
parameterMap.put("time", time);
parameterMap.put("ext", ext);
parameterMap.put("signType", signType);
parameterMap.put("sign", sign);
log.info("h5_baijia parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, "", money);
ResponseUtil.write(response, result ? "success" : "fail");
}
/**
* 5144玩
* status String 是 是 订单状态。“success”为支付成功
* cpOrderId String 是 是 游戏方(cp)游戏订单号
* orderId String 是 是 我方订单ID
* uid string 是 是 用户UID (唯一) 我方用户的UID
* userName string 是 是 用户名
* money 是 是 商品价格(元) 例:1.00
* gameId String 是 是 游戏的id
* goodsId string 是 是 商品ID 没有的话。可以写1
* goodsName string 是 是 商品名,如:游戏币
* server string 是 是 支付时的游戏服
* role string 是 是 支付时角色信息,支付完后回传
* time int 是 是 当前时间unix时间戳
* ext string 否 否 额外透传参数(原样返回)
* signType string 是 否 固定值 md5
* sign string 是 否 加密串
*/
@RequestMapping(value = "/callbackPayInfo/h5_5144wan/{channelId}/{appId}")
@ResponseBody
public void h5_5144wan(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("status") String status,
@RequestParam("cpOrderId") String cpOrderId,
@RequestParam("orderId") String orderId,
@RequestParam("uid") String uid,
@RequestParam("userName") String userName,
@RequestParam("money") String money,
@RequestParam("gameId") String gameId,
@RequestParam("goodsId") String goodsId,
@RequestParam("goodsName") String goodsName,
@RequestParam("server") String server,
@RequestParam("role") String role,
@RequestParam("time") String time,
@RequestParam("ext") String ext,
@RequestParam("signType") String signType,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("status", status);
parameterMap.put("cpOrderId", cpOrderId);
parameterMap.put("orderId", orderId);
parameterMap.put("uid", uid);
parameterMap.put("userName", userName);
parameterMap.put("money", money);
parameterMap.put("gameId", gameId);
parameterMap.put("goodsId", goodsId);
parameterMap.put("goodsName", goodsName);
parameterMap.put("server", server);
parameterMap.put("role", role);
parameterMap.put("time", time);
parameterMap.put("ext", ext);
parameterMap.put("signType", signType);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, "", money);
ResponseUtil.write(response, result ? "success" : "fail");
}
/**
* 顺网
* 参数名 类型 是否必传 说明
* order_no string 是 顺网平台订单号
* guid string 是 顺网平台游戏帐号
* server_code string 否 分区服的游戏必传,游戏方的区服编号,如s1,s2
* money string 是 充值金额,人民币(单位元)
* coin string 否 游戏币数量,页游必传
* role_id string 否 角色ID(充值到角色的游戏必传)
* out_order_no string 否 游戏方订单号(H5,端游游戏必传)
* other_data string 否 其他数据(透传,原样返回)
* platform string 是 固定值:swjoy
* time int 是 unix时间戳
* sign string 是 签名规则
*/
@RequestMapping(value = "/callbackPayInfo/h5_shunwang/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_shunwang(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("order_no") String order_no,
@RequestParam("guid") String guid,
@RequestParam(value = "server_code", required = false) String server_code,//字符串
@RequestParam("money") String money,
@RequestParam(value = "coin", required = false) String coin,
@RequestParam(value = "role_id", required = false) String role_id,
@RequestParam(value = "out_order_no", required = false) String out_order_no,
@RequestParam(value = "other_data", required = false) String other_data,
@RequestParam("platform") String platform,
@RequestParam("time") String time,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("order_no", order_no);
parameterMap.put("guid", guid);
parameterMap.put("server_code", server_code);
parameterMap.put("money", money);
parameterMap.put("coin", coin);
parameterMap.put("role_id", role_id);
parameterMap.put("out_order_no", out_order_no);
parameterMap.put("other_data", other_data);
parameterMap.put("platform", platform);
parameterMap.put("time", time);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject rsp = new JSONObject();
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, out_order_no, order_no, money);
/*
{"code": 1,"msg": "ok"} json 其中 code 为 int 类型,msg 为 code 的说明类型,两个属性值都不 能少
code=1 订单充值成功
code=2 订单号重复,顺网当成充值成功来处理
code=3 充值异常,顺网会重复发起请求
code=4 明确充值失败,顺网发起退款流
还没返回或其它值 顺网会重复发起请求
*/
if (!result) {
rsp.put("code", 3);
rsp.put("msg", "发货失败");
} else {
rsp.put("code", 1);
rsp.put("msg", "订单充值成功");
}
ResponseUtil.write(response, rsp);
}
/**
* 鱼马
* 参数名 类型 是否必传 说明
* nt_data string 是 通知数据解码后为xml格式 ,具体见2.1.1
* sign string 是 签名串,具体见第三章
* md5Sign string 否 分区服的游戏必传,游戏方的区服编号,如s1,s2
*/
@RequestMapping(value = "/callbackPayInfo/h5_yuma/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_yuma(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("nt_data") String nt_data,
@RequestParam("sign") String sign,
@RequestParam("md5Sign") String md5Sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("nt_data", nt_data);
parameterMap.put("sign", sign);
parameterMap.put("md5Sign", md5Sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject rsp = new JSONObject();
JSONObject channelOrder = new JSONObject();
boolean result = false;
do {
result = checkOrder(appId, channelId, parameterMap, channelOrder, "", "", "");
if (!result) {
rsp.put("code", 3);
rsp.put("msg", "发货失败");
} else {
rsp.put("code", 1);
rsp.put("msg", "订单充值成功");
}
} while (false);
ResponseUtil.write(response, rsp);
}
/**
* 欢聚
* <p>
* 接收参数(CGI) 类型 必选 参于加密 说明
* status String 是 是 订单状态。“success”为支付成功
* cpOrderId String 是 是 cp游戏订单号。
* orderId String 是 是 欢聚游微游戏订单号
* uid string 是 是 欢聚游微游戏用户的uid
* userName string 是 是 欢聚游微游戏的用户名
* money decimal 是 是 支付钱数(元),保留2位小数
* gameId String 是 是 游戏的id
* goodsId String 是 是 商品ID
* goodsName String 是 是 商品名
* server String 是 是 支付的游戏服
* role String 是 是 支付时角色信息,
* time int 是 是 当前时间unix时间戳
* ext String(200) 否 否 额外透传参数(原样返回)
* sign string 是 否 加密串
* signType string 是 否 固定md5
*/
@RequestMapping(value = "/callbackPayInfo/h5_huanju/{channelId}/{appId}")
@ResponseBody
public String h5_huanju(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("status") String status,
@RequestParam("cpOrderId") String cpOrderId,
@RequestParam("orderId") String orderId,
@RequestParam("uid") String uid,
@RequestParam("userName") String userName,
@RequestParam("money") String money,
@RequestParam("gameId") String gameId,
@RequestParam("goodsId") String goodsId,
@RequestParam("goodsName") String goodsName,
@RequestParam("server") String server,
@RequestParam("role") String role,
@RequestParam("time") String time,
@RequestParam(value = "ext", required = false) String ext,
@RequestParam("signType") String signType,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("status", status);
parameterMap.put("cpOrderId", cpOrderId);
parameterMap.put("orderId", orderId);
parameterMap.put("uid", uid);
parameterMap.put("userName", userName);
parameterMap.put("money", money);
parameterMap.put("gameId", gameId);
parameterMap.put("goodsId", goodsId);
parameterMap.put("goodsName", goodsName);
parameterMap.put("server", server);
parameterMap.put("role", role);
parameterMap.put("time", time);
parameterMap.put("ext", ext);
parameterMap.put("signType", signType);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, orderId, money);
// ResponseUtil.write(response, result ? "success" : "fail");
return result ? "success" : "fail";
}
/**
* 引力
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
* uid KUKU平台用户ID
* orderNo KUKU平台订单唯一编号
* productId 游戏方支付时传入的商品ID
* gameOrderNo 游戏方支付时传入的游戏方订单编号
* gameKey KUKU平台分配给游戏方的游戏标识
* payCost 用户真实支付的金额,单位分
* ext1 游戏方支付时传入的扩展参数2,原样返回
* ext2 游戏方支付时传入的扩展参数1,原样返回
* sign 签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_yinli/{channelId}/{appId}")
@ResponseBody
public void h5_yinli(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
int length = request.getContentLength();
ServletInputStream input = request.getInputStream();
byte[] buffer = new byte[length];
input.read(buffer, 0, length);
String urlData = new String(buffer);
log.info("callbackPayInfo:" + urlData);
String jsonData = URLDecoder.decode(urlData, String.valueOf(StandardCharsets.UTF_8));
log.info("h5_yinli JsonData = " + jsonData);
JSONObject data = JSONObject.parseObject(jsonData);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("uid", data.getString("uid"));
parameterMap.put("orderNo", data.getString("orderNo"));
parameterMap.put("productId", data.getString("productId"));
parameterMap.put("gameOrderNo", data.getString("gameOrderNo"));
parameterMap.put("gameKey", data.getString("gameKey"));
parameterMap.put("payCost", data.getString("payCost"));
parameterMap.put("ext1", data.getString("ext1"));
parameterMap.put("ext2", data.getString("ext2"));
parameterMap.put("sign", data.getString("sign"));
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(data.getString("payCost"));
boolean result = checkOrder(appId, channelId, parameterMap, data, data.getString("gameOrderNo"), data.getString("orderNo"), money);
ResponseUtil.write(response, result ? "ok" : "fail");
}
/**
* 悦游
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_yueyou/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_yueyou(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 掌盟 soeasy
* 参数名 类型 是否必传 说明
*
* @param appid string Y 同APPID
* @param sdkindx string Y 平台定义
* @param uid string Y 用户的唯一标示
* @param feeid string N 计费点ID
* @param feemoney string Y 实际扣费金额(分)
* @param orderid string Y 支付在速易服务器上订单号
* @param extradata string N Cp自定义参数,响应时透传返回(如游戏服务的订单号)
* @param paytime string Y 下单时间
* @param prover string Y 协议版本号初始为1
* @param paystatus string Y 支付状态1为成功,2沙盒测试,其他均为失败
* @param sign string Y
*/
@RequestMapping(value = "/callbackPayInfo/h5_zhangmeng/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_zhangmeng(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("appid") String appid,
@RequestParam("sdkindx") String sdkindx,
@RequestParam("uid") String uid,
@RequestParam(value = "feeid", required = false) String feeid,
@RequestParam("feemoney") String feemoney,
@RequestParam("orderid") String orderid,
@RequestParam(value = "extradata", required = false) String extradata,
@RequestParam("paytime") String paytime,
@RequestParam("prover") String prover,
@RequestParam("paystatus") String paystatus,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("appid", appid);
parameterMap.put("sdkindx", sdkindx);
parameterMap.put("uid", uid);
parameterMap.put("feeid", feeid);
parameterMap.put("feemoney", feemoney);
parameterMap.put("orderid", orderid);
parameterMap.put("extradata", extradata);
parameterMap.put("paytime", paytime);
parameterMap.put("prover", prover);
parameterMap.put("paystatus", paystatus);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject rsp = new JSONObject();
JSONObject channelOrder = new JSONObject();
boolean result = false;
do {
String cpOrderId = channelOrder.getString("extradata");
String money = FeeUtils.fenToYuan(parameterMap.get("feemoney"));
result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, "", money);
} while (false);
rsp.put("status", result ? "ok" : "fail");
ResponseUtil.write(response, rsp);
log.info("callbackPayInfo rsp " + rsp.toString());
}
/**
* 一牛
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_yiniu/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_yiniu(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 1758
* 参数字段 类型 说明 是否可空 是否参与签名
*
* @param params appKey string 游戏的appKey 否 是
* gid string 用户的gid 否 是
* orderId string 1758订单号 否 是
* txId string cp订单号 否 是
* productDesc string 商品描述 否 是
* totalFee int 支付金额,单位分 否 是
* status int 订单状态 否 是
* state string cp自定义参数 是 是
* ext string 订单其他信息,json结构,预留参数,目前未启用 是 否
* sign string 参数签名 否 签名方法 , 签名工具
*/
@RequestMapping(value = "/callbackPayInfo/h5_1758/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_1758(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam Map<String, String> params,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
log.info("parameterMap =" + params.toString());
JSONObject data = new JSONObject();
String totalFee = params.get("totalFee");
String txId = params.get("txId");
String orderId = params.get("orderId");
String money = FeeUtils.fenToYuan(totalFee);
boolean result = checkOrder(appId, channelId, params, data, txId, orderId, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 小y
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_xiaoy/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_xiaoy(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 三唐
* <p>
* 参数名 备注 说明
* pf 平台名 固定值:3tang
* sid 游戏区服 根据玩家所在区服传值
* openid 玩家唯一标志三唐 openid
* billDate 玩家下单时间 Unixtime 格式标准时间
* st_trade_no 三唐平台订单号
* cp_trade_no CP 方订单号 跟调起充值接口传入的 CP 方,订单号是一致的
* cash 玩家充值金额 单位是元
* sign 签名(md5 加密 小写) md5(pf&sid&openid&billDate&st_trade_no&cp_trade_no&cash& APPKEY )注意:&是变量连接符,不要放到加密里APPKEY 由三唐平台分配或双方协定
*/
@RequestMapping(value = "/callbackPayInfo/h5_santang/{channelId}/{appId}")
@ResponseBody
public void h5_santang(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("pf") String pf,
@RequestParam("sid") String sid,
@RequestParam("openid") String openid,
@RequestParam("billDate") String billDate,
@RequestParam("st_trade_no") String st_trade_no,
@RequestParam("cp_trade_no") String cp_trade_no,
@RequestParam("cash") String cash,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("pf", pf);
parameterMap.put("sid", sid);
parameterMap.put("openid", openid);
parameterMap.put("billDate", billDate);
parameterMap.put("st_trade_no", st_trade_no);
parameterMap.put("cp_trade_no", cp_trade_no);
parameterMap.put("cash", cash);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, cp_trade_no, st_trade_no, cash);
JSONObject rsp = new JSONObject();
rsp.put("result", result ? 1 : 0);
ResponseUtil.write(response, rsp);
}
/**
* 羊羔
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_yanggao/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_yanggao(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 奇游
* <p>
*
* @param order_no 平台支付订单 是 201912181137114223
* @param cp_order 游戏订单号 是
* @param user_id 平台用户ID,和登录注册时返回的user_id一致 是
* @param product_id 游戏商品ID 是
* @param price 充值金额(元) 是
* @param role_id 角色ID 是
* @param server_id 服务器ID 是
* @param ext 扩展参数,透传下单时提供的extension 否 默认空字符串
* @param time Unix时间戳 是
* @param sign 加密串 是 详见下面sign生成算法
*/
@RequestMapping(value = "/callbackPayInfo/h5_qiyou/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_qiyou(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("order_no") String order_no,
@RequestParam("cp_order") String cp_order,
@RequestParam("user_id") String user_id,
@RequestParam("product_id") String product_id,
@RequestParam("price") String price,
@RequestParam("role_id") String role_id,
@RequestParam("server_id") String server_id,
@RequestParam("ext") String ext,
@RequestParam("time") String time,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("order_no", order_no);
parameterMap.put("cp_order", cp_order);
parameterMap.put("user_id", user_id);
parameterMap.put("product_id", product_id);
parameterMap.put("price", price);
parameterMap.put("role_id", role_id);
parameterMap.put("server_id", server_id);
parameterMap.put("ext", ext);
parameterMap.put("time", time);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, cp_order, order_no, price);
ResponseUtil.write(response, result ? "0" : "-1");
}
/**
* 77
*
* @param qqes_order String 是 SDK订单号
* @param cp_order String 是 cp订单号
* @param fee float 是 订单金额(元)
* @param cpgameid Integer 是 cp在我们平台的游戏id
* @param timestamp String 是 请求时间戳,Unix时间戳,10位
* @param sign String 否 签名字符串,算法: 除非字段标注为不需要参与签名,否则请求参数都参与签名,按参数值自然升序,然后拼接成字符串(比如a=1&b=2&c=3&签名秘钥),然后md5生成签名字符串
*/
@RequestMapping(value = "/callbackPayInfo/h5_77/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_77(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("qqes_order") String qqes_order,
@RequestParam("cp_order") String cp_order,
@RequestParam("fee") String fee,
@RequestParam("cpgameid") String cpgameid,
@RequestParam("timestamp") String timestamp,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("qqes_order", qqes_order);
parameterMap.put("cp_order", cp_order);
parameterMap.put("fee", fee);
parameterMap.put("cpgameid", cpgameid);
parameterMap.put("timestamp", timestamp);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, cp_order, qqes_order, fee);
ResponseUtil.write(response, result ? "success" : "fail");
}
/**
* so游记
* <p>
*
* @param uid 用户在汇米网络的用户ID # length <= 20
* @param nonce 随机字符串,可为空 # length <= 64
* @param time 操作发生时的UNIX时间戳,精确到秒 # length = 10
* @param money 订单金额,币种人民币,单位分,此值必须为正整数 # length <= 20
* @param propsname 游戏商品名 # length <= 128
* @param order 由游戏开发商产生的唯一订单号 # length <= 128
* @param token 校验token # length <= 128
* @param pay_code #
* 0 # 支付失败
* 1 # 支付成功
* @param sign #
* --- # 签名,用于请求合法性校验
*/
@RequestMapping(value = "/callbackPayInfo/h5_SOyouji/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_SOyouji(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("uid") String uid,
@RequestParam("nonce") String nonce,
@RequestParam("time") String time,
@RequestParam("money") String money,
@RequestParam("propsname") String propsname,
@RequestParam("order") String order,
@RequestParam("token") String token,
@RequestParam("pay_code") String pay_code,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("uid", uid);
parameterMap.put("nonce", nonce);
parameterMap.put("time", time);
parameterMap.put("money", money);
parameterMap.put("propsname", propsname);
parameterMap.put("order", order);
parameterMap.put("token", token);
parameterMap.put("pay_code", pay_code);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, order, "", FeeUtils.fenToYuan(money));
ResponseUtil.write(response, result ? "1" : "0");
}
/**
* 找手游
*
* @param user_id Int 是 付费用户id
* @param username String 是 付费用户名
* @param to_uid Int 是 充入用户id
* @param to_user String 是 充入用户名
* @param pay_id string 是 支付id
* @param money Smallint 是 充值金额
* @param game_id Int 是 游戏id
* @param server_id Int 是 区/服 id
* @param cp_order String 是 游戏充值(订单号)
* @param time Int 是 充值发起时间
* @param extra String 否 额外信息good_id
* @param sign string 是 签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_zhaoshouyou/{channelId}/{appId}")
@ResponseBody
public void h5_zhaoshouyou(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("user_id") String user_id,
@RequestParam("username") String username,
@RequestParam("to_uid") String to_uid,
@RequestParam("to_user") String to_user,
@RequestParam("pay_id") String pay_id,
@RequestParam("money") String money,
@RequestParam("game_id") String game_id,
@RequestParam("server_id") String server_id,
@RequestParam("cp_order") String cp_order,
@RequestParam("time") String time,
@RequestParam("extra") String extra,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("user_id", user_id);
parameterMap.put("username", username);
parameterMap.put("to_uid", to_uid);
parameterMap.put("to_user", to_user);
parameterMap.put("pay_id", pay_id);
parameterMap.put("money", money);
parameterMap.put("game_id", game_id);
parameterMap.put("server_id", server_id);
parameterMap.put("cp_order", cp_order);
parameterMap.put("time", time);
parameterMap.put("extra", extra);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, cp_order, "", money);
ResponseUtil.write(response, result ? "success" : "fail");
}
/**
* 果盘
* <p>
* 必选 类型及范围 说明
*
* @param trade_no true string 果盘唯一订单号
* @param serialNumber true string 游戏方订单序列号
* @param money true string 消费金额。单位是元,精确到分,如10.00。请务必校验金额与玩家下单的商品价值是否一致
* @param status true string 状态;0=失败;1=成功;2=失败,原因是余额不足。
* @param t true string 时间戳(果盘服务器发起通知的北京时间)
* @param sign true string 加密串 sign=md5(serialNumber+money+status+t+SERVER_KEY) 是五个变量值拼接后经 md5 后的值,其中SERVER_KEY 在果盘开放平台上获得。
* @param appid false string
* @param item_id false string
* @param item_price false string
* @param item_count false string
* @param reserved false string 扩展参数,SDK 发起支付时有传递,则这里会回传。
* @param game_uin true string 玩家游戏 uid;请务必校验该 game_uin 和下单时对应的角色 game_uin 是否一致,防止“任意充”
*/
@RequestMapping(value = "/callbackPayInfo/h5_guopan/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_guopan(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("trade_no") String trade_no,
@RequestParam("serialNumber") String serialNumber,
@RequestParam("money") String money,
@RequestParam("status") String status,
@RequestParam("t") String t,
@RequestParam("sign") String sign,
@RequestParam(value = "appid", required = false) String appid,
@RequestParam(value = "item_id", required = false) String item_id,
@RequestParam(value = "item_price", required = false) String item_price,
@RequestParam(value = "item_count", required = false) String item_count,
@RequestParam(value = "reserved", required = false) String reserved,
@RequestParam(value = "game_uin", required = false) String game_uin,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("trade_no", trade_no);
parameterMap.put("serialNumber", serialNumber);
parameterMap.put("money", money);
parameterMap.put("status", status);
parameterMap.put("t", t);
parameterMap.put("sign", sign);
parameterMap.put("appid", appid);
parameterMap.put("item_id", item_id);
parameterMap.put("item_price", item_price);
parameterMap.put("item_count", item_count);
parameterMap.put("reserved", reserved);
parameterMap.put("game_uin", game_uin);
log.info("parameterMap =" + parameterMap.toString());
boolean result = checkOrder(appId, channelId, parameterMap, data, serialNumber, trade_no, money);
ResponseUtil.write(response, result ? "success" : "fail");
}
/**
* 游戏fan
* <p>
*/
@RequestMapping(value = "/callbackPayInfo/h5_youxifun/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_youxifun(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestBody String datas,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
String[] body = URLDecoder.decode(datas, String.valueOf(StandardCharsets.UTF_8)).split("&");
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
Integer len = body.length;
StringBuilder param = new StringBuilder();
for (int index = 0; index < len; index++) {
String s = body[index];
String[] p = s.split("=");
String key = p[0];
String value = p.length == 2 ? p[1] : "";
System.out.println("key = " + key + "[" + value + "]");
parameterMap.put(key, value);
data.put(key, value);
if (key.equals("userId") || key.equals("sign")) {
} else {
if (index > 1) {
param.append("&");
}
param.append(s);
}
}
parameterMap.put("param", param.toString());
String cpOrderNo = data.getString("attach");
String channelOrder = data.getString("orderid");
String amount = data.getString("amount");
boolean result = checkOrder(appId, channelId, parameterMap, data, cpOrderNo, channelOrder, amount);
ResponseUtil.write(response, result ? "success" : "error");
}
/**
* 大秦
* <p>
* 接收参数(CGI) 类型 必选 参于加密 说明
* status String 是 是 订单状态。“success”为支付成功
* cpOrderId String 是 是 cp游戏订单号。
* orderId String 是 是 欢聚游微游戏订单号
* uid string 是 是 欢聚游微游戏用户的uid
* userName string 是 是 欢聚游微游戏的用户名
* money decimal 是 是 支付钱数(元),保留2位小数
* gameId String 是 是 游戏的id
* goodsId String 是 是 商品ID
* goodsName String 是 是 商品名
* server String 是 是 支付的游戏服
* role String 是 是 支付时角色信息,
* time int 是 是 当前时间unix时间戳
* ext String(200) 否 否 额外透传参数(原样返回)
* sign string 是 否 加密串
* signType string 是 否 固定md5
*/
@RequestMapping(value = "/callbackPayInfo/h5_daqin/{channelId}/{appId}")
@ResponseBody
public String h5_daqin(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("status") String status,
@RequestParam("cpOrderId") String cpOrderId,
@RequestParam("orderId") String orderId,
@RequestParam("uid") String uid,
@RequestParam("userName") String userName,
@RequestParam("money") String money,
@RequestParam("gameId") String gameId,
@RequestParam("goodsId") String goodsId,
@RequestParam("goodsName") String goodsName,
@RequestParam("server") String server,
@RequestParam("role") String role,
@RequestParam("time") String time,
@RequestParam(value = "ext", required = false) String ext,
@RequestParam("signType") String signType,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("status", status);
parameterMap.put("cpOrderId", cpOrderId);
parameterMap.put("orderId", orderId);
parameterMap.put("uid", uid);
parameterMap.put("userName", userName);
parameterMap.put("money", money);
parameterMap.put("gameId", gameId);
parameterMap.put("goodsId", goodsId);
parameterMap.put("goodsName", goodsName);
parameterMap.put("server", server);
parameterMap.put("role", role);
parameterMap.put("time", time);
parameterMap.put("ext", ext);
parameterMap.put("signType", signType);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, cpOrderId, orderId, money);
// ResponseUtil.write(response, result ? "success" : "fail");
return result ? "success" : "fail";
}
/**
* 盛娱
*
* @param datas datas.origin_order_no 原始订单号
* datas.order_id 平台订单号
* datas.type 充值类型(direct 平台直充 order 订单充值)
* datas.money 充值金额(单位分)
* datas.game_id 游戏ID
* datas.game_area 区服ID
* datas.pay_channel 支付渠道 wechat alipay coin
* datas.status 订单状态 1 表示成功,只有成功才会发通知
* datas.complete_at 成功时间戳
* datas.extra_data 透传参数
* datas.sign 签名字符串
*/
@RequestMapping(value = "/callbackPayInfo/h5_shengyu/{channelId}/{appId}")
@ResponseBody
public void h5_shengyu(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestBody String datas,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = JSONObject.parseObject(datas);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("origin_order_no", data.getString("origin_order_no"));
parameterMap.put("order_id", data.getString("order_id"));
parameterMap.put("type", data.getString("type"));
parameterMap.put("money", data.getString("money"));
parameterMap.put("game_id", data.getString("game_id"));
parameterMap.put("game_area", data.getString("game_area"));
parameterMap.put("pay_channel", data.getString("pay_channel"));
parameterMap.put("status", data.getString("status"));
parameterMap.put("complete_at", data.getString("complete_at"));
parameterMap.put("extra_data", data.getString("extra_data"));
parameterMap.put("sign", data.getString("sign"));
log.info("parameterMap =" + parameterMap.toString());
String yuan = FeeUtils.fenToYuan(data.getString("money"));
boolean result = checkOrder(appId, channelId, parameterMap, data, data.getString("origin_order_no"), data.getString("order_id"), yuan);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "ok" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 游心
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_youxin/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_youxin(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 天天玩
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param actor_id
* @param app_id 分配给游戏里的gameId
* @param app_user_id 游戏内的userid,允许自定义。不做校验,下单值原样返回
* @param real_amount 充值金额
* @param app_order_id 传入的订单号,允许自定义。不做校验,下单值原样返回
* @param order_id 平台的订单号,在充值未返回success时,会在后续进行补单,游戏需防止重复发放奖励
* @param payment_time 充值时间
* @param ext 玩家所在区服,用于区分统计
* @param sign 平台计算的签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_tiantianwan/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public String h5_tiantianwan(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("actor_id") String actor_id,
@RequestParam("app_id") String app_id,
@RequestParam("app_user_id") String app_user_id,
@RequestParam("real_amount") String real_amount,
@RequestParam("app_order_id") String app_order_id,
@RequestParam("order_id") String order_id,
@RequestParam("payment_time") String payment_time,
@RequestParam("ext") String ext,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("actor_id", actor_id);
parameterMap.put("app_id", app_id);
parameterMap.put("app_user_id", app_user_id);
parameterMap.put("real_amount", real_amount);
parameterMap.put("app_order_id", app_order_id);
parameterMap.put("order_id", order_id);
parameterMap.put("payment_time", payment_time);
parameterMap.put("ext", ext);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
// String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, app_order_id, order_id, real_amount);
return result ? "success" : "fail";
}
/**
* 5144玩_2
* 名称 参数名 类型 提供方 必填 说明
* 商户ID pid string 我 是 贵方在我方唯一标识
* 游戏ID gid string 贵 是 贵方游戏唯一标识
* 游戏服ID sid string 贵 是 贵方游戏服唯一标识
* 玩家id uid string 我 是 我方玩家唯一标识
* 时间戳 time string - 是 Unix time
* 订单号 orderid string 我 是 我方订单唯一标识
* 充值金额 money string 我 是 人民币,单位元
* 请求类型 type string 我 是 固定值:pay
* 自定义参数 other string 贵 是 贵方自定义参数值,如贵方订单号,我方会在充值回调里,传回给贵方,可为空
* Sign sign string 我 是 MD5(pid#gid#sid#uid#time#orderid#money#pkey),Md5只加密参数值,32位小写,用英文#连接各参数值
* 充值密钥 pkey 我 我方提供不以明文显示在前端,只用于加密
*/
@RequestMapping(value = "/callbackPayInfo/h5_5144wan2/{channelId}/{appId}")
@ResponseBody
public void h5_5144wan2(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("pid") String pid,
@RequestParam("gid") String gid,
@RequestParam("sid") String sid,
@RequestParam("uid") String uid,
@RequestParam("time") String time,
@RequestParam("orderid") String orderid,
@RequestParam("money") String money,
@RequestParam("type") String type,
@RequestParam("other") String other,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("pid", pid);
parameterMap.put("gid", gid);
parameterMap.put("sid", sid);
parameterMap.put("uid", uid);
parameterMap.put("time", time);
parameterMap.put("orderid", orderid);
parameterMap.put("money", money);
parameterMap.put("type", type);
parameterMap.put("other", other);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, "", "", money);
JSONObject rsp = new JSONObject();
if (result) {
rsp.put("code", "1");
// 充值成功 Unicode
rsp.put("msg", "\u5145\u503c\u6210\u529f");
} else {
// 其他错误 Unicode
rsp.put("code", "18");
rsp.put("msg", "\u5176\u4ed6\u9519\u8bef");
}
ResponseUtil.write(response, rsp.toString());
}
/**
* 暴雨quick
* 参数名 类型 是否必传 说明
* nt_data string 是 通知数据解码后为xml格式 ,具体见2.1.1
* sign string 是 签名串,具体见第三章
* md5Sign string 否 分区服的游戏必传,游戏方的区服编号,如s1,s2
*/
@RequestMapping(value = "/callbackPayInfo/h5_baoyu/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_baoyu(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("nt_data") String nt_data,
@RequestParam("sign") String sign,
@RequestParam("md5Sign") String md5Sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("nt_data", nt_data);
parameterMap.put("sign", sign);
parameterMap.put("md5Sign", md5Sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject rsp = new JSONObject();
JSONObject channelOrder = new JSONObject();
boolean result = false;
do {
result = checkOrder(appId, channelId, parameterMap, channelOrder, "", "", "");
if (!result) {
rsp.put("code", 3);
rsp.put("msg", "发货失败");
} else {
rsp.put("code", 1);
rsp.put("msg", "订单充值成功");
}
} while (false);
ResponseUtil.write(response, rsp);
}
/**
* 手游大侠
* 回调body已经过url encode,使用时要使用url decode进行解密等到json
* <p>
*
* @param amount 金额,单位为分
* @param channel_source 数据来源
* @param game_appid 游戏编号----运营方为游戏分配的唯一编号
* @param out_trade_no 渠道方订单号
* @param payplatform2cp 用于 CP 要求平台特别传输其他参数,默认是访问 ip
* @param trade_no 游戏透传参数(默认为游戏订单号,回调时候原样返回)
* @param sign 按照上方签名机制进行签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_shouyoudaxia/{channelId}/{appId}", method = RequestMethod.GET)
@ResponseBody
public void h5_shouyoudaxia(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("amount") String amount,
@RequestParam("channel_source") String channel_source,
@RequestParam("game_appid") String game_appid,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("payplatform2cp") String payplatform2cp,
@RequestParam("trade_no") String trade_no,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
JSONObject data = new JSONObject();
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("amount", amount);
parameterMap.put("channel_source", channel_source);
parameterMap.put("game_appid", game_appid);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("payplatform2cp", payplatform2cp);
parameterMap.put("trade_no", trade_no);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
String money = FeeUtils.fenToYuan(amount);
boolean result = checkOrder(appId, channelId, parameterMap, data, trade_no, out_trade_no, money);
JSONObject rsp = new JSONObject();
rsp.put("status", result ? "success" : "fail");
ResponseUtil.write(response, rsp);
}
/**
* 紫霞
*
* @param uid 用户登录ID
* @param gkey 游戏名字(拼音字母缩写)
* @param skey 传用户角色所在的游戏区服id
* @param order_id 订单号(游戏方自己的订单号)
* @param money 人民币数量(单位:元) 只能为正整数(需要厂家与原始订单进行校验比对)
* @param time 时间戳
* @param sign 双方协定的密钥(生成规则为:md5($uid.$gkey.$skey.$time.$order_id.$money.'#'.$pkey) (pkey为充值密钥)
*/
@RequestMapping(value = "/callbackPayInfo/h5_zixia/{channelId}/{appId}")
@ResponseBody
public void h5_zixia(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("uid") String uid,
@RequestParam("gkey") String gkey,
@RequestParam("skey") String skey,
@RequestParam("order_id") String order_id,
@RequestParam("money") String money,
@RequestParam("time") String time,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("uid", uid);
parameterMap.put("gkey", gkey);
parameterMap.put("skey", skey);
parameterMap.put("order_id", order_id);
parameterMap.put("money", money);
parameterMap.put("time", time);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject rsp = new JSONObject();
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, "", "", money);
//订单充值成功/发货失败
rsp.put("code", result ? 1 : 0);
ResponseUtil.write(response, rsp);
}
/**
* 天宇-41
* <p>
*
* @param out_order_no cp订单编号
* @param order_no 订单编号
* @param amount 支付金额,单位元
* @param role_id 玩家角色id
* @param pay_time 支付时间(YY-mm-dd HH:ii:ss) 2017-12-31 12:22:22
* @param cp_game_id 游戏id(对接群获取)
* @param sign 签名
*/
@RequestMapping(value = "/callbackPayInfo/h5_tianyu/{channelId}/{appId}", method = RequestMethod.POST)
@ResponseBody
public void h5_tianyu(@PathVariable("channelId") Integer channelId, @PathVariable("appId") Integer appId,
@RequestParam("out_order_no") String out_order_no,
@RequestParam("order_no") String order_no,
@RequestParam("amount") String amount,
@RequestParam("role_id") String role_id,
@RequestParam("pay_time") String pay_time,
@RequestParam("cp_game_id") String cp_game_id,
@RequestParam("sign") String sign,
HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("callbackPayInfo:" + channelId);
log.info("callbackPayInfo:" + appId);
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("out_order_no", out_order_no);
parameterMap.put("order_no", order_no);
parameterMap.put("amount", amount);
parameterMap.put("role_id", role_id);
parameterMap.put("pay_time", pay_time);
parameterMap.put("cp_game_id", cp_game_id);
parameterMap.put("sign", sign);
log.info("parameterMap =" + parameterMap.toString());
JSONObject channelOrder = new JSONObject();
boolean result = checkOrder(appId, channelId, parameterMap, channelOrder, out_order_no, order_no, amount);
//订单充值成功/发货失败
ResponseUtil.write(response, result ? "SUCCESS" : "FAIL");
}
}
| 44.221739
| 181
| 0.567582
|
6e1ac5bf66c96db4ac58064a14e104f97390e3f2
| 35,161
|
/*
* Tencent is pleased to support the open source community by making TubeMQ available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.tubemq.server.master.nodemanage.nodebroker;
import com.tencent.tubemq.corebase.TokenConstants;
import com.tencent.tubemq.corebase.utils.CheckSum;
import com.tencent.tubemq.corebase.utils.TStringUtils;
import com.tencent.tubemq.server.common.TServerConstants;
import com.tencent.tubemq.server.common.TStatusConstants;
import com.tencent.tubemq.server.master.bdbstore.bdbentitys.BdbBrokerConfEntity;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BrokerSyncStatusInfo {
private static final Logger logger =
LoggerFactory.getLogger(BrokerSyncStatusInfo.class);
private boolean isFirstInit = true;
private int brokerId = -2;
private String brokerIp; //broker ip
private int brokerPort; //broker port
private int brokerTLSPort; //broker tls port
/* Broker manager stratus :-2:undefine,1:pending for approval,5:online,7:offline */
private int brokerManageStatus = -2;
/* Broker run status, -2:undefine, 31: online(wait-server), 32:online(readonly), 33:online(read&write)
* 51: offline(unreadable¬ writeable), 52: offline(wait load balance) */
private int brokerRunStatus = -2;
private long subStepOpTimeInMills = 0;
private boolean isBrokerRegister = false; //broker register flag
private boolean isBrokerOnline = false; //broker online flag
private boolean isOverTLS = false; //enable tls
private boolean isBrokerConfChaned = false; //config change flag
private boolean isBrokerLoaded = false; //broker load status
private boolean isFastStart = false; //enable fast start
private long lastPushBrokerConfId = -2;
private int lastPushBrokerCheckSumId = -2;
private long lastDataPushInMills = 0;
private String lastPushBrokerDefaultConfInfo;
private List<String> lastPushBrokerTopicSetConfInfo =
new ArrayList<String>();
private long reportedBrokerConfId = -2;
private int reportedBrokerCheckSumId = -2;
private long lastDataReportInMills = 0;
private String reportedBrokerDefaultConfInfo;
private List<String> reportedBrokerTopicSetConfInfo =
new ArrayList<String>();
private AtomicLong currBrokerConfId = new AtomicLong(0);
private int currBrokerCheckSumId = 0;
private String curBrokerDefaultConfInfo;
private List<String> curBrokerTopicSetConfInfo =
new ArrayList<String>();
private int numPartitions = 1; //partition number
private int numTopicStores = 1; //store number
private int unFlushDataHold = TServerConstants.CFG_DEFAULT_DATA_UNFLUSH_HOLD;
private int unflushThreshold = 1000; //flush threshold
private int unflushInterval = 10000; //flush interval
private int memCacheMsgSizeInMB = 2; //memory cache size
private int memCacheMsgCntInK = 10; //memory cache message count
private int memCacheFlushIntvl = 20000; //memory cache flush interval
private String deletePolicy = "delete,168h"; //data delete policy
private String deleteWhen = "0 0 6,18 * * ?"; //date delete policy execute time
private boolean acceptPublish = true; //accept publish
private boolean acceptSubscribe = true; //accept subscribe
//Constructor
public BrokerSyncStatusInfo(final BdbBrokerConfEntity bdbEntity,
List<String> brokerTopicSetConfInfo) {
updateBrokerConfigureInfo(bdbEntity.getBrokerDefaultConfInfo(),
brokerTopicSetConfInfo);
this.brokerManageStatus = bdbEntity.getManageStatus();
this.isBrokerConfChaned = bdbEntity.isConfDataUpdated();
this.isBrokerLoaded = bdbEntity.isBrokerLoaded();
this.brokerId = bdbEntity.getBrokerId();
this.brokerIp = bdbEntity.getBrokerIp();
this.brokerPort = bdbEntity.getBrokerPort();
this.brokerTLSPort = bdbEntity.getBrokerTLSPort();
this.isFastStart = false;
if (this.brokerManageStatus > TStatusConstants.STATUS_MANAGE_APPLY) {
currBrokerConfId.incrementAndGet();
}
}
/**
* Update current broker config info
*
* @param brokerManageStatus broker status
* @param isBrokerConfChaned
* @param isBrokerLoaded
* @param brokerDefaultConfInfo broker default config
* @param brokerTopicSetConfInfo topic config
* @param isOnlineUpdate
*/
public void updateCurrBrokerConfInfo(int brokerManageStatus, boolean isBrokerConfChaned,
boolean isBrokerLoaded, String brokerDefaultConfInfo,
List<String> brokerTopicSetConfInfo,
boolean isOnlineUpdate) {
this.brokerManageStatus = brokerManageStatus;
this.currBrokerConfId.incrementAndGet();
this.isBrokerConfChaned = isBrokerConfChaned;
this.isBrokerLoaded = isBrokerLoaded;
updateBrokerConfigureInfo(brokerDefaultConfInfo, brokerTopicSetConfInfo);
this.lastPushBrokerConfId = this.currBrokerConfId.get();
this.lastPushBrokerCheckSumId = this.currBrokerCheckSumId;
this.lastDataPushInMills = System.currentTimeMillis();
this.lastPushBrokerDefaultConfInfo = this.curBrokerDefaultConfInfo;
this.lastPushBrokerTopicSetConfInfo = this.curBrokerTopicSetConfInfo;
switch (this.brokerManageStatus) {
case TStatusConstants.STATUS_MANAGE_ONLINE: {
this.brokerRunStatus = isOnlineUpdate
? TStatusConstants.STATUS_SERVICE_TOONLINE_PART_WAIT_REGISTER
: TStatusConstants.STATUS_SERVICE_TOONLINE_WAIT_REGISTER;
break;
}
case TStatusConstants.STATUS_MANAGE_ONLINE_NOT_WRITE: {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_READ;
break;
}
case TStatusConstants.STATUS_MANAGE_ONLINE_NOT_READ: {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_WRITE;
break;
}
default: {
if (this.isBrokerRegister) {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOOFFLINE_NOT_WRITE;
}
}
}
this.subStepOpTimeInMills = System.currentTimeMillis();
}
/**
* Reset broker report info
*/
public void resetBrokerReportInfo() {
this.reportedBrokerConfId = -2;
this.reportedBrokerCheckSumId = -2;
this.reportedBrokerDefaultConfInfo = "";
this.reportedBrokerTopicSetConfInfo =
new ArrayList<String>();
this.isBrokerRegister = false;
this.isBrokerOnline = false;
this.isFastStart = false;
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_UNDEFINED;
this.subStepOpTimeInMills = System.currentTimeMillis();
}
/**
* Set broker report info
*
* @param isRegister
* @param reportConfigId
* @param reportCheckSumId
* @param isTackData
* @param reportDefaultConfInfo
* @param reportTopicSetConfInfo
* @param isBrokerRegister
* @param isBrokerOnline
* @param isOverTLS
*/
public void setBrokerReportInfo(boolean isRegister, long reportConfigId,
int reportCheckSumId, boolean isTackData,
String reportDefaultConfInfo,
List<String> reportTopicSetConfInfo,
boolean isBrokerRegister, boolean isBrokerOnline, boolean isOverTLS) {
this.reportedBrokerConfId = reportConfigId;
this.reportedBrokerCheckSumId = reportCheckSumId;
if (isTackData) {
this.reportedBrokerDefaultConfInfo = reportDefaultConfInfo;
if (reportTopicSetConfInfo == null) {
this.reportedBrokerTopicSetConfInfo = new ArrayList<String>();
} else {
this.reportedBrokerTopicSetConfInfo = reportTopicSetConfInfo;
}
this.lastDataReportInMills = System.currentTimeMillis();
}
this.isBrokerRegister = isBrokerRegister;
this.isBrokerOnline = isBrokerOnline;
this.isOverTLS = isOverTLS;
if (isRegister) {
if (this.isBrokerOnline) {
if (this.reportedBrokerConfId <= 0) {
if (this.isBrokerConfChaned
|| !this.isBrokerLoaded
|| this.reportedBrokerCheckSumId != this.lastPushBrokerCheckSumId
|| !isFirstInit) {
return;
}
this.lastPushBrokerConfId = this.reportedBrokerConfId;
this.currBrokerConfId.set(this.lastPushBrokerConfId);
this.lastPushBrokerCheckSumId = this.currBrokerCheckSumId;
this.lastDataPushInMills = System.currentTimeMillis();
this.brokerRunStatus =
TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_READ;
this.subStepOpTimeInMills = System.currentTimeMillis();
this.isFirstInit = false;
} else {
this.isFirstInit = false;
this.isFastStart = true;
switch (this.brokerManageStatus) {
case TStatusConstants.STATUS_MANAGE_ONLINE: {
this.brokerRunStatus =
TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_READ;
break;
}
case TStatusConstants.STATUS_MANAGE_ONLINE_NOT_WRITE: {
this.brokerRunStatus =
TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_READ;
break;
}
case TStatusConstants.STATUS_MANAGE_ONLINE_NOT_READ: {
this.brokerRunStatus =
TStatusConstants.STATUS_SERVICE_TOONLINE_ONLY_WRITE;
break;
}
default: {
this.brokerRunStatus =
TStatusConstants.STATUS_SERVICE_TOOFFLINE_NOT_WRITE;
}
}
this.subStepOpTimeInMills = 0;
}
}
}
}
/**
* Set broker status to offline
*/
public void setBrokerOffline() {
if (this.brokerManageStatus != TStatusConstants.STATUS_MANAGE_OFFLINE) {
this.brokerManageStatus = TStatusConstants.STATUS_MANAGE_OFFLINE;
}
if (this.isBrokerOnline) {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOOFFLINE_NOT_WRITE;
} else if (this.isBrokerRegister) {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOOFFLINE_NOT_READ_WRITE;
} else {
this.brokerRunStatus = TStatusConstants.STATUS_SERVICE_TOOFFLINE_WAIT_REBALANCE;
}
this.subStepOpTimeInMills = System.currentTimeMillis();
}
/**
* Check if need sync config data to broker
*
* @return true if need otherwise false
*/
public boolean needSyncConfDataToBroker() {
if (this.lastPushBrokerConfId != this.reportedBrokerConfId
|| this.lastPushBrokerCheckSumId != this.reportedBrokerCheckSumId) {
return true;
}
return false;
}
/**
* According to last report time and current time to decide if need to report data
*
* @return true if need report data otherwise false
*/
public boolean needReportData() {
if (System.currentTimeMillis() - this.lastDataPushInMills
> TServerConstants.CFG_REPORT_DEFAULT_SYNC_DURATITON) {
this.lastDataPushInMills = System.currentTimeMillis();
return true;
}
return false;
}
public void forceSyncConfDataToBroker() {
this.isFastStart = true;
this.lastPushBrokerConfId = this.currBrokerConfId.incrementAndGet();
this.lastPushBrokerCheckSumId = this.currBrokerCheckSumId;
this.lastPushBrokerDefaultConfInfo = this.curBrokerDefaultConfInfo;
this.lastPushBrokerTopicSetConfInfo = this.curBrokerTopicSetConfInfo;
this.lastDataPushInMills = System.currentTimeMillis();
}
public Long getCurrBrokerConfId() {
return currBrokerConfId.get();
}
public int getCurrBrokerCheckSumId() {
return currBrokerCheckSumId;
}
public String getCurBrokerDefaultConfInfo() {
return curBrokerDefaultConfInfo;
}
public List<String> getCurBrokerTopicSetConfInfo() {
return curBrokerTopicSetConfInfo;
}
public long getLastDataReportInMills() {
return lastDataReportInMills;
}
public void setLastDataReportInMills(long lastDataReportInMills) {
this.lastDataReportInMills = lastDataReportInMills;
}
public boolean isFastStart() {
return isFastStart;
}
public void setFastStart(boolean isFastStart) {
this.isFastStart = isFastStart;
}
public boolean isBrokerOnline() {
return this.isBrokerOnline;
}
public void setBrokerOnline(boolean isBrokerOnline) {
this.isBrokerOnline = isBrokerOnline;
}
public boolean isBrokerRegister() {
return this.isBrokerRegister;
}
public void setBrokerRunStatus(boolean isBrokerRegister,
boolean isBrokerOnline) {
this.isBrokerRegister = isBrokerRegister;
this.isBrokerOnline = isBrokerOnline;
}
public long getReportedBrokerConfId() {
return reportedBrokerConfId;
}
public int getNumPartitions() {
return numPartitions;
}
public int getUnflushThreshold() {
return unflushThreshold;
}
public int getUnflushInterval() {
return unflushInterval;
}
public String getDeletePolicy() {
return deletePolicy;
}
public String getDeleteWhen() {
return deleteWhen;
}
public boolean isAcceptPublish() {
return acceptPublish;
}
public boolean isAcceptSubscribe() {
return acceptSubscribe;
}
public int getBrokerRunStatus() {
return brokerRunStatus;
}
public void setBrokerRunStatus(int brokerRunStatus) {
this.brokerRunStatus = brokerRunStatus;
this.subStepOpTimeInMills = System.currentTimeMillis();
}
public boolean isOverTLS() {
return isOverTLS;
}
public void setOverTLS(boolean overTLS) {
isOverTLS = overTLS;
}
public int getBrokerTLSPort() {
return brokerTLSPort;
}
public void setBrokerTLSPort(int brokerTLSPort) {
this.brokerTLSPort = brokerTLSPort;
}
public long getSubStepOpTimeInMills() {
return subStepOpTimeInMills;
}
public int getBrokerId() {
return brokerId;
}
public String getBrokerIp() {
return brokerIp;
}
public int getBrokerPort() {
return brokerPort;
}
public int getBrokerManageStatus() {
return brokerManageStatus;
}
private int calculateConfigCrc32Value(final String brokerDefaultConfInfo,
final List<String> brokerTopicSetConfInfo) {
int result = -1;
int capacity = 0;
Collections.sort(brokerTopicSetConfInfo);
capacity += brokerDefaultConfInfo.length();
for (String itemStr : brokerTopicSetConfInfo) {
capacity += itemStr.length();
}
capacity *= 2;
for (int i = 1; i < 3; i++) {
result = inCalcBufferResult(capacity, brokerDefaultConfInfo, brokerTopicSetConfInfo);
if (result >= 0) {
return result;
}
capacity *= i + 1;
}
logger.error("Calc BrokerConfigure Crc error!");
return 0;
}
private int inCalcBufferResult(int capacity, final String brokerDefaultConfInfo,
final List<String> brokerTopicSetConfInfo) {
final ByteBuffer buffer = ByteBuffer.allocate(capacity);
buffer.put(StringUtils.getBytesUtf8(brokerDefaultConfInfo));
for (String itemStr : brokerTopicSetConfInfo) {
byte[] itemData = StringUtils.getBytesUtf8(itemStr);
if (itemData.length > buffer.remaining()) {
return -1;
}
buffer.put(itemData);
}
return CheckSum.crc32(buffer.array());
}
/**
* Update broker config, field will set to default value if brokerDefaultConfInfo is empty,
* else will parse the string value and then set broker config
*
* @param brokerDefaultConfInfo a string, field join with ":",
* @param brokerTopicSetConfInfo
*/
private void updateBrokerConfigureInfo(String brokerDefaultConfInfo,
List<String> brokerTopicSetConfInfo) {
int crc32CheckSum =
calculateConfigCrc32Value(brokerDefaultConfInfo, brokerTopicSetConfInfo);
if (crc32CheckSum != this.currBrokerCheckSumId) {
this.currBrokerCheckSumId = crc32CheckSum;
this.curBrokerTopicSetConfInfo = brokerTopicSetConfInfo;
this.curBrokerDefaultConfInfo = brokerDefaultConfInfo;
if (TStringUtils.isBlank(brokerDefaultConfInfo)) {
this.numPartitions = 1;
this.numTopicStores = 1;
this.unflushThreshold = 1000;
this.unflushInterval = 10000;
this.unFlushDataHold = TServerConstants.CFG_DEFAULT_DATA_UNFLUSH_HOLD;
this.deletePolicy = "delete,168h";
this.deleteWhen = "0 0 6,18 * * ?";
this.acceptPublish = true;
this.acceptSubscribe = true;
this.memCacheFlushIntvl = 20000;
this.memCacheMsgCntInK = 10;
this.memCacheMsgSizeInMB = 2;
} else {
String[] brokerDefaultConfInfoArr =
brokerDefaultConfInfo.split(TokenConstants.ATTR_SEP);
this.numPartitions = Integer.parseInt(brokerDefaultConfInfoArr[0]);
this.acceptPublish = Boolean.parseBoolean(brokerDefaultConfInfoArr[1]);
this.acceptSubscribe = Boolean.parseBoolean(brokerDefaultConfInfoArr[2]);
this.unflushThreshold = Integer.parseInt(brokerDefaultConfInfoArr[3]);
this.unflushInterval = Integer.parseInt(brokerDefaultConfInfoArr[4]);
this.deleteWhen = brokerDefaultConfInfoArr[5];
this.deletePolicy = brokerDefaultConfInfoArr[6];
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[7])) {
this.numTopicStores = Integer.parseInt(brokerDefaultConfInfoArr[7]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[8])) {
this.unFlushDataHold = Integer.parseInt(brokerDefaultConfInfoArr[8]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[9])) {
this.memCacheMsgSizeInMB = Integer.parseInt(brokerDefaultConfInfoArr[9]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[10])) {
this.memCacheMsgCntInK = Integer.parseInt(brokerDefaultConfInfoArr[10]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[11])) {
this.memCacheFlushIntvl = Integer.parseInt(brokerDefaultConfInfoArr[11]);
}
}
}
}
public long getLastPushBrokerConfId() {
return lastPushBrokerConfId;
}
public void setLastPushBrokerConfId(long lastPushBrokerConfId) {
this.lastPushBrokerConfId = lastPushBrokerConfId;
}
public int getLastPushBrokerCheckSumId() {
return lastPushBrokerCheckSumId;
}
public void setLastPushBrokerCheckSumId(int lastPushBrokerCheckSumId) {
this.lastPushBrokerCheckSumId = lastPushBrokerCheckSumId;
}
public long getLastDataPushInMills() {
return lastDataPushInMills;
}
public void setLastDataPushInMills(long lastDataPushInMills) {
this.lastDataPushInMills = lastDataPushInMills;
}
public String getLastPushBrokerDefaultConfInfo() {
return lastPushBrokerDefaultConfInfo;
}
public void setLastPushBrokerDefaultConfInfo(String lastPushBrokerDefaultConfInfo) {
this.lastPushBrokerDefaultConfInfo = lastPushBrokerDefaultConfInfo;
}
public List<String> getLastPushBrokerTopicSetConfInfo() {
return lastPushBrokerTopicSetConfInfo;
}
public void setLastPushBrokerTopicSetConfInfo(List<String> lastPushBrokerTopicSetConfInfo) {
this.lastPushBrokerTopicSetConfInfo = lastPushBrokerTopicSetConfInfo;
}
public String getReportedBrokerDefaultConfInfo() {
return reportedBrokerDefaultConfInfo;
}
public void setReportedBrokerDefaultConfInfo(String reportedBrokerDefaultConfInfo) {
this.reportedBrokerDefaultConfInfo = reportedBrokerDefaultConfInfo;
}
public List<String> getReportedBrokerTopicSetConfInfo() {
return reportedBrokerTopicSetConfInfo;
}
public void setReportedBrokerTopicSetConfInfo(List<String> reportedBrokerTopicSetConfInfo) {
this.reportedBrokerTopicSetConfInfo = reportedBrokerTopicSetConfInfo;
}
public boolean isBrokerConfChaned() {
return isBrokerConfChaned;
}
public void setBrokerConfChaned() {
this.isBrokerConfChaned = true;
this.isBrokerLoaded = false;
}
public boolean isBrokerLoaded() {
return isBrokerLoaded;
}
public void setBrokerLoaded() {
this.isBrokerLoaded = true;
this.isBrokerConfChaned = false;
}
// #lizard forgives
private StringBuilder getBrokerAndTopicConfJsonInfo(String brokerConfInfo,
String brokerJsonKey,
List<String> topicConfInfoList,
String topicListJsonKey,
final StringBuilder strBuffer) {
// format config to json
strBuffer.append(",\"").append(brokerJsonKey).append("\":");
if (TStringUtils.isBlank(brokerConfInfo)) {
strBuffer.append("{},\"").append(topicListJsonKey).append("\":[]");
return strBuffer;
}
// broker default metadata
String[] brokerDefaultConfInfoArr =
brokerConfInfo.split(TokenConstants.ATTR_SEP);
final int numPartitions = Integer.parseInt(brokerDefaultConfInfoArr[0]);
final boolean acceptPublish = Boolean.parseBoolean(brokerDefaultConfInfoArr[1]);
final boolean acceptSubscribe = Boolean.parseBoolean(brokerDefaultConfInfoArr[2]);
final int unflushThreshold = Integer.parseInt(brokerDefaultConfInfoArr[3]);
final int unflushInterval = Integer.parseInt(brokerDefaultConfInfoArr[4]);
final String deleteWhen = brokerDefaultConfInfoArr[5];
final String deletePolicy = brokerDefaultConfInfoArr[6];
int numTopicStores = 1;
int unFlushDataHold = TServerConstants.CFG_DEFAULT_DATA_UNFLUSH_HOLD;
int memCacheMsgSizeInMB = 2;
int memCacheMsgCntInK = 10;
int memCacheFlushIntvl = 20000;
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[7])) {
numTopicStores =
Integer.parseInt(brokerDefaultConfInfoArr[7]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[8])) {
unFlushDataHold =
Integer.parseInt(brokerDefaultConfInfoArr[8]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[9])) {
memCacheMsgSizeInMB =
Integer.parseInt(brokerDefaultConfInfoArr[9]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[10])) {
memCacheMsgCntInK =
Integer.parseInt(brokerDefaultConfInfoArr[10]);
}
if (!TStringUtils.isBlank(brokerDefaultConfInfoArr[11])) {
memCacheFlushIntvl =
Integer.parseInt(brokerDefaultConfInfoArr[11]);
}
//format broker config to json
strBuffer.append("{\"numPartitions\":").append(numPartitions)
.append(",\"acceptPublish\":").append(acceptPublish)
.append(",\"acceptSubscribe\":").append(acceptSubscribe)
.append(",\"unflushThreshold\":").append(unflushThreshold)
.append(",\"unflushInterval\":").append(unflushInterval)
.append(",\"deleteWhen\":\"").append(deleteWhen)
.append("\",\"deletePolicy\":\"").append(deletePolicy)
.append("\",\"numTopicStores\":").append(numTopicStores)
.append(",\"unFlushDataHold\":").append(unFlushDataHold)
.append(",\"memCacheMsgSizeInMB\":").append(memCacheMsgSizeInMB)
.append(",\"memCacheMsgCntInK\":").append(memCacheMsgCntInK)
.append(",\"memCacheFlushIntvl\":").append(memCacheFlushIntvl)
.append("}");
strBuffer.append(",\"").append(topicListJsonKey).append("\":[");
if (topicConfInfoList == null
|| topicConfInfoList.isEmpty()) {
strBuffer.append("]");
return strBuffer;
}
// topic config metadata in the broker
// format topic metadata
int count = 0;
for (String strTopicConfInfo : topicConfInfoList) {
if (TStringUtils.isBlank(strTopicConfInfo)) {
continue;
}
String[] topicConfInfoArr =
strTopicConfInfo.split(TokenConstants.ATTR_SEP);
if (count++ > 0) {
strBuffer.append(",");
}
strBuffer.append("{\"topicName\":\"").append(topicConfInfoArr[0]).append("\"");
int tmpPartNum = numPartitions;
if (!TStringUtils.isBlank(topicConfInfoArr[1])) {
tmpPartNum = Integer.parseInt(topicConfInfoArr[1]);
}
strBuffer.append(",\"numPartitions\":").append(tmpPartNum);
boolean tmpAcceptPublish = acceptPublish;
if (!TStringUtils.isBlank(topicConfInfoArr[2])) {
tmpAcceptPublish = Boolean.parseBoolean(topicConfInfoArr[2]);
}
strBuffer.append(",\"acceptPublish\":").append(tmpAcceptPublish);
boolean tmpAcceptSubscribe = acceptSubscribe;
if (!TStringUtils.isBlank(topicConfInfoArr[3])) {
tmpAcceptSubscribe = Boolean.parseBoolean(topicConfInfoArr[3]);
}
strBuffer.append(",\"acceptSubscribe\":").append(tmpAcceptSubscribe);
int tmpUnflushThreshold = unflushThreshold;
if (!TStringUtils.isBlank(topicConfInfoArr[4])) {
tmpUnflushThreshold = Integer.parseInt(topicConfInfoArr[4]);
}
strBuffer.append(",\"unflushThreshold\":").append(tmpUnflushThreshold);
int tmpUnflushInterval = unflushInterval;
if (!TStringUtils.isBlank(topicConfInfoArr[5])) {
tmpUnflushInterval = Integer.parseInt(topicConfInfoArr[5]);
}
strBuffer.append(",\"unflushInterval\":").append(tmpUnflushInterval);
String tmpDeleteWhen = deleteWhen;
if (!TStringUtils.isBlank(topicConfInfoArr[6])) {
tmpDeleteWhen = topicConfInfoArr[6];
}
strBuffer.append(",\"deleteWhen\":\"").append(tmpDeleteWhen).append("\"");
String tmpDeletePolicy = deletePolicy;
if (!TStringUtils.isBlank(topicConfInfoArr[7])) {
tmpDeletePolicy = topicConfInfoArr[7];
}
int tmpNumTopicStores = numTopicStores;
if (!TStringUtils.isBlank(topicConfInfoArr[8])) {
tmpNumTopicStores = Integer.parseInt(topicConfInfoArr[8]);
}
strBuffer.append(",\"numTopicStores\":").append(tmpNumTopicStores);
strBuffer.append(",\"deletePolicy\":\"").append(tmpDeletePolicy).append("\"");
int topicStatusId = TStatusConstants.STATUS_TOPIC_OK;
if (!TStringUtils.isBlank(topicConfInfoArr[9])) {
topicStatusId = Integer.parseInt(topicConfInfoArr[9]);
}
int tmpunFlushDataHold = unFlushDataHold;
if (!TStringUtils.isBlank(topicConfInfoArr[10])) {
tmpunFlushDataHold = Integer.parseInt(topicConfInfoArr[10]);
}
strBuffer.append(",\"unFlushDataHold\":").append(tmpunFlushDataHold);
int tmpmemCacheMsgSizeInMB = memCacheMsgSizeInMB;
int tmpmemCacheMsgCntInK = memCacheMsgCntInK;
int tmpmemCacheFlushIntvl = memCacheFlushIntvl;
if (!TStringUtils.isBlank(topicConfInfoArr[11])) {
tmpmemCacheMsgSizeInMB = Integer.parseInt(topicConfInfoArr[11]);
}
if (!TStringUtils.isBlank(topicConfInfoArr[12])) {
tmpmemCacheMsgCntInK = Integer.parseInt(topicConfInfoArr[12]);
}
if (!TStringUtils.isBlank(topicConfInfoArr[13])) {
tmpmemCacheFlushIntvl = Integer.parseInt(topicConfInfoArr[13]);
}
strBuffer.append(",\"memCacheMsgSizeInMB\":").append(tmpmemCacheMsgSizeInMB);
strBuffer.append(",\"memCacheMsgCntInK\":").append(tmpmemCacheMsgCntInK);
strBuffer.append(",\"memCacheFlushIntvl\":").append(tmpmemCacheFlushIntvl);
strBuffer.append(",\"topicStatusId\":").append(topicStatusId);
strBuffer.append("}");
}
strBuffer.append("]");
return strBuffer;
}
/* Format to json */
public StringBuilder toJsonString(StringBuilder strBuffer, boolean isOrig) {
strBuffer.append("\"BrokerSyncStatusInfo\":{\"type\":\"BrokerSyncStatusInfo\",\"brokerId\":").append(brokerId)
.append(",\"brokerAddress\":\"").append(brokerIp).append(":").append(brokerPort)
.append("\",\"brokerManageStatus\":").append(brokerManageStatus)
.append(",\"brokerRunStatus\":").append(brokerRunStatus)
.append(",\"subStepOpTimeInMills\":").append(subStepOpTimeInMills)
.append(",\"lastDataReportInMills\":").append(lastDataReportInMills)
.append(",\"isBrokerRegister\":").append(isBrokerRegister)
.append(",\"isBrokerOnline\":").append(isBrokerOnline)
.append(",\"isFirstInit\":").append(isFirstInit)
.append(",\"isBrokerConfChaned\":").append(isBrokerConfChaned)
.append(",\"isBrokerLoaded\":").append(isBrokerLoaded)
.append(",\"isFastStart\":").append(isFastStart);
if (isOrig) {
strBuffer.append(",\"currBrokerConfId\":").append(currBrokerConfId.get())
.append(",\"currBrokerCheckSumId\":").append(currBrokerCheckSumId)
.append(",\"curBrokerDefaultConfInfo\":\"").append(curBrokerDefaultConfInfo)
.append("\",\"curBrokerTopicSetConfInfo\":\"").append(curBrokerTopicSetConfInfo.toString())
.append("\",\"lastPushBrokerConfId\":").append(lastPushBrokerConfId)
.append(",\"lastPushBrokerCheckSumId\":").append(lastPushBrokerCheckSumId)
.append(",\"lastPushBrokerDefaultConfInfo\":\"").append(lastPushBrokerDefaultConfInfo)
.append("\",\"lastPushBrokerTopicSetConfInfo\":\"")
.append(lastPushBrokerTopicSetConfInfo.toString())
.append(",\"reportedBrokerConfId\":").append(reportedBrokerConfId)
.append(",\"reportedBrokerCheckSumId\":").append(reportedBrokerCheckSumId)
.append(",\"reportedBrokerDefaultConfInfo\":\"").append(reportedBrokerDefaultConfInfo)
.append("\",\"reportedBrokerTopicSetConfInfo\":\"")
.append(reportedBrokerTopicSetConfInfo.toString())
.append("}");
} else {
strBuffer.append(",\"currBrokerConfId\":").append(currBrokerConfId.get())
.append(",\"currBrokerCheckSumId\":").append(currBrokerCheckSumId);
strBuffer = getBrokerAndTopicConfJsonInfo(curBrokerDefaultConfInfo,
"curBrokerDefaultConfInfo",
curBrokerTopicSetConfInfo,
"curBrokerTopicSetConfInfo",
strBuffer);
strBuffer.append(",\"lastPushBrokerConfId\":").append(lastPushBrokerConfId)
.append(",\"lastPushBrokerCheckSumId\":").append(lastPushBrokerCheckSumId);
strBuffer = getBrokerAndTopicConfJsonInfo(lastPushBrokerDefaultConfInfo,
"lastPushBrokerDefaultConfInfo",
lastPushBrokerTopicSetConfInfo,
"lastPushBrokerTopicSetConfInfo",
strBuffer);
strBuffer.append(",\"reportedBrokerConfId\":").append(reportedBrokerConfId)
.append(",\"reportedBrokerCheckSumId\":").append(reportedBrokerCheckSumId);
strBuffer = getBrokerAndTopicConfJsonInfo(reportedBrokerDefaultConfInfo,
"reportedBrokerDefaultConfInfo",
reportedBrokerTopicSetConfInfo,
"reportedBrokerTopicSetConfInfo",
strBuffer);
strBuffer.append("}");
}
return strBuffer;
}
}
| 43.355117
| 118
| 0.625295
|
9ded4e6abf7b86ed534d5413cfc205f5de972b4f
| 962
|
package com.tencentcloudapi.cmq.v20190304;
public enum CmqErrorCode {
// 操作失败。
FAILEDOPERATION("FailedOperation"),
// 操作进行中,请稍后重试。
FAILEDOPERATION_TRYLATER("FailedOperation.TryLater"),
// 参数错误。
INVALIDPARAMETER("InvalidParameter"),
// 任务Id不存在。
INVALIDPARAMETERVALUE_NOTASKID("InvalidParameterValue.NoTaskId"),
// 超过配额限制。
LIMITEXCEEDED("LimitExceeded"),
// 资源被占用。
RESOURCEINUSE("ResourceInUse"),
// 资源不存在。
RESOURCENOTFOUND("ResourceNotFound"),
// 资源不可用。
RESOURCEUNAVAILABLE("ResourceUnavailable"),
// 资源售罄。
RESOURCESSOLDOUT("ResourcesSoldOut"),
// 未授权操作。
UNAUTHORIZEDOPERATION("UnauthorizedOperation");
private String value;
private CmqErrorCode (String value){
this.value = value;
}
/**
* @return errorcode value
*/
public String getValue() {
return value;
}
}
| 21.377778
| 70
| 0.614345
|
1a99f6cf6c7be981b5c31d1b888a91d50d19958e
| 772
|
package org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.connection;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.*;
import java.io.*;
public class ConnectionCloseServerMessage extends BaseServerMessage
{
public ConnectionCloseServerMessage() {
super();
}
public ConnectionCloseServerMessage(final DataInputStream dataInputStream) throws IOException {
super();
}
@Override
public short getFlag() {
return -32766;
}
@Override
protected void onAppendTransmissionDataForToString(final StringBuilder sb) {
}
@Override
protected void onWriteTransmissionData(final DataOutputStream dataOutputStream) throws IOException {
}
}
| 26.62069
| 104
| 0.729275
|
fc377abb66d66f2668e9a90d4ac342d8b7e3efdb
| 1,946
|
/**
* 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 com.alibaba.jstorm.daemon.worker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* UpdateListener is used to dynamic update configurations in worker
* triggered by update topology action
* @author Jark (wuchong.wc@alibaba-inc.com)
*/
public class UpdateListener {
private static final Logger LOG = LoggerFactory.getLogger(UpdateListener.class);
interface IUpdater {
void update(Map conf);
}
private List<IUpdater> updaters = new ArrayList<>();
/**
* register an updater which implement IUpdate
* @param updater used to update configurations in worker
*/
public void registerUpdater(IUpdater updater) {
updaters.add(updater);
}
/**
* trigger all updaters' update action
* @param conf the new worker conf
*/
public void update(Map conf) {
for (IUpdater updater : updaters) {
try {
updater.update(conf);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
}
}
| 29.484848
| 84
| 0.685509
|
44e921c235c8c0b837ad633bd57a5799b48c9fe9
| 4,906
|
/* This source code is released under the new BSD license, a copy of the
* license is in the distribution directory. */
package mazerob.nxt;
import java.lang.RuntimeException;
import lejos.nxt.Motor;
import lejos.nxt.SensorPort;
import lejos.nxt.UltrasonicSensor;
import lejos.robotics.RotatingRangeScanner;
import lejos.robotics.RangeReadings;
import lejos.robotics.navigation.DifferentialPilot;
import mazerob.conn.RemotelyControllable;
/**
* NXT Explorer abstraction
*
* @author Pedro I. López
*
* @see <a
* href="http://www.nxtprograms.com/NXT2/explorer/steps.html">NXT Explorer</a>
*
*/
class Robot implements RemotelyControllable {
/** Abstraction of the Explorer's ultrasonic sensor */
RotatingRangeScanner scanner;
/** Instance of the Pilot mechanism to control the Explorer movements */
DifferentialPilot pilot;
/** Magnitude of translation in mm of methods {@link
* mazerob.nxt.Robot#translateForward} and {@link
* mazerob.nxt.Robot#translateBackward} specified by the
* {@code translationMagnitude} argument in {@link
* mazerob.nxt.Robot#Robot}
*/
double translationMagnitude;
/** Magnitude of rotation in degrees of methods {@link
* mazerob.nxt.Robot#rotateRight} and {@link
* mazerob.nxt.Robot#rotateLeft} specified by the
* {@code rotationMagnitude} argument in {@link
* mazerob.nxt.Robot#Robot}
*/
double rotationMagnitude;
/**
* @param wheelDiameter Diameter of the tires in mm
* @param trackWidth Distance between center of right tire and
* center of left tire in mm
* @param reverse If true, the NXT robot moves forward when the
* motors are running backward
* @param rotationSpeed Rotation speed of the vehicle, in degrees
* per second
* @param translationMagnitude Magnitude of translation in mm of methods
* {@link mazerob.nxt.Robot#translateForward} and {@link
* mazerob.nxt.Robot#translateBackward}
* @param rotationMagnitude Magnitude of rotation in degrees of methods
* {@link mazerob.nxt.Robot#rotateRight} and {@link
* mazerob.nxt.Robot#rotateLeft}
*
*/
public Robot(double wheelDiameter,
double trackWidth,
boolean reverse,
double rotationSpeed,
double translationMagnitude,
double rotationMagnitude) {
final String CONFIGURED_MSG = "Configuration complete";
this.translationMagnitude = translationMagnitude;
this.rotationMagnitude = rotationMagnitude;
pilot = new DifferentialPilot(wheelDiameter, trackWidth,
Motor.B, Motor.C, reverse);
pilot.setRotateSpeed(rotationSpeed);
scanner = new RotatingRangeScanner(Motor.A,
new UltrasonicSensor(SensorPort.S1));
scanner.setAngles( SCANNING_ANGLES );
System.out.println(CONFIGURED_MSG);
}
/**
* Wait until translation is done
*
* @see mazerob.conn.RemotelyControllable#translate
*/
public void translate(double distance) {
pilot.travel(distance);
}
/**
* Translate forward {@link Robot#translationMagnitude} mm, wait until
* translation is done
*
* @see mazerob.conn.RemotelyControllable#translateForward
*/
public void translateForward() {
pilot.travel(translationMagnitude);
}
/**
* Translate backward {@link Robot#translationMagnitude} mm, wait until
* translation is done
*
* @see mazerob.conn.RemotelyControllable#translateBackward
*/
public void translateBackward() {
pilot.travel(-translationMagnitude);
}
/**
* Wait until rotation is done
*
* @see mazerob.conn.RemotelyControllable#rotate
*/
public void rotate(double angle) {
pilot.rotate(angle);
}
/**
* Rotate to the right {@link Robot#rotationMagnitude} mm, wait until
* rotation is done
*
* @see mazerob.conn.RemotelyControllable#rotateRight
*/
public void rotateRight() {
pilot.rotate(rotationMagnitude);
}
/**
* Rotate to the left {@link Robot#rotationMagnitude} mm, wait until
* rotation is done
*
* @see mazerob.conn.RemotelyControllable#rotateLeft
*/
public void rotateLeft() {
pilot.rotate(-rotationMagnitude);
}
/**
* End the connection and exit the {@link mazerob.nxt.RobotApp}
* program
*
* @see mazerob.conn.RemotelyControllable#end
*/
public void end() throws RuntimeException {
System.out.println(CLOSING_CONN_MSG);
throw new RuntimeException();
}
/**
* @see mazerob.conn.RemotelyControllable#scan
*/
public RangeReadings scan() {
RangeReadings rangeValues = scanner.getRangeValues();
return rangeValues;
}
}
| 30.283951
| 78
| 0.661435
|
bf69869422b3024e1922966464c61663925544a0
| 2,880
|
package de.renew.gui;
import de.renew.dbnets.shadow.node.ShadowDBNetTransition;
import de.renew.dbnets.shadow.node.ShadowRollbackArc;
import de.renew.shadow.ShadowNet;
import de.renew.shadow.ShadowNetElement;
import de.renew.shadow.ShadowPlace;
import java.awt.Color;
import java.util.Objects;
/**
* The db-net rollback arc connection UI figure.
*
* @author Anton Rigin, National Research University - Higher School of Economics, Faculty of Computer Science,
* Master Degree Program "System and Software Engineering", the 2nd year student.
* Master Thesis on the Topic
* "Method of Performance Analysis of Time-Critical Applications Using DB-Nets".
* HSE University, Moscow, Russia, 2019 - 2021.
*/
public class RollbackArcConnection extends ArcConnection {
/**
* The db-net rollback arc connection UI figure constant.
*/
public static final RollbackArcConnection ROLLBACK_ARC_CONNECTION = new RollbackArcConnection();
/**
* The shadow (non-compiled) level representation of the db-net rollback arc
* formed from the Renew UI db-net's drawing.
*/
private transient ShadowRollbackArc shadow;
/**
* The db-net rollback arc connection UI figure's constructor.
*/
public RollbackArcConnection() {
super(ShadowRollbackArc.ROLLBACK_ARC);
}
/**
* Releases the figure's resources.
*/
@Override
public void release() {
super.release();
if (Objects.nonNull(shadow)) {
shadow.discard();
}
}
/**
* Builds the shadow (non-compiled) level representation of the db-net rollback arc.
*
* @param net The shadow (non-compiled) level representation of the db-net.
* @return The shadow (non-compiled) level representation of the db-net rollback arc.
*/
@Override
public ShadowNetElement buildShadow(ShadowNet net) {
shadow = new ShadowRollbackArc(((ShadowDBNetTransition) startShadow()), ((ShadowPlace) endShadow()));
shadow.context = this;
shadow.setID(getID());
shadow.setTrace(getTraceMode());
return shadow;
}
/**
* Returns the previously built shadow (non-compiled) level representation of the db-net rollback arc.
*
* @return The previously built shadow (non-compiled) level representation of the db-net rollback arc.
*/
@Override
public ShadowRollbackArc getShadow() {
return shadow;
}
/**
* Returns the shadow rollback arc type number.
*
* @return The shadow rollback arc type number.
*/
@Override
public int getArcType() {
return ShadowRollbackArc.ROLLBACK_ARC;
}
/**
* Returns the red arc color.
*
* @return The red arc color.
*/
@Override
public Color getFrameColor() {
return Color.RED;
}
}
| 29.690722
| 111
| 0.661458
|
9853a98f1a2ce34ba680fd766d1e19ae83bdbf40
| 1,647
|
package jdbc0627;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test05_Update {
public static void main(String[] args) {
/*
* JDBC(Java Database Connection)
* 자바와 MySQL 데이터베이스를 연동
* mysql-connector-java-5.1.47.jar 라이브러리 필요
* DB명 -> java0514
*/
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
String url="jdbc:mysql://localhost:3306/java0514?useUnicode=true&characterEncoding=euckr";
String user="root";
String password="1234";
String driver="org.gjt.mm.mysql.Driver";
Class.forName(driver);
con=DriverManager.getConnection(url, user, password);
System.out.println("MySQL DB 서버 연결 성공!!");
//----------MySQL DB연결-------------------------------------------------------------------------------------------
StringBuilder sql=new StringBuilder();
sql.append(" UPDATE sungjuk ");
sql.append(" SET tot=(kor+eng+mat) ");
sql.append(" ,aver=(kor+eng+mat)/3 ");
pstmt=con.prepareStatement(sql.toString());
int result=pstmt.executeUpdate();
if(result==0){
System.out.println("행수정 실패");
}else{
System.out.println("행수정 성공");
}
}catch(Exception e){
System.out.println("MySQL DB 연결 실패!"+e);
}finally{
//자원반납(순서주의!!!!!!)
//맨 처음에 열었던걸 나중에 닫기 > 역순
try{
if(rs!=null){rs.close();}
}catch(Exception e){}
try{
if(pstmt!=null){pstmt.close();}
}catch(Exception e){}
try{
if(con!=null){con.close();}
}catch(Exception e){}
}//try
}//main
}//class
| 19.843373
| 113
| 0.585914
|
c374706c059f1d7b3c317285ee662a277bf7444e
| 742
|
package yuku.alkitabconverter;
import java.io.FileInputStream;
public class Cek7BitFileTeks {
public static void main(String[] args) throws Exception {
new Cek7BitFileTeks().u(args);
}
public void u(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(args[0]);
int len = fis.available();
System.out.println("avail = " + len);
for (int i = 0; i < len; i++) {
int c = fis.read();
if (c >= 0x80) {
// terusin baca untuk kasih liat
byte[] buf = new byte[80];
fis.read(buf);
System.out.println(new String(buf, "utf-8"));
throw new RuntimeException("ada byte " + c + " di pos " + i);
} else if (c < 0) {
throw new RuntimeException("eof kecepetan");
}
}
}
}
| 23.935484
| 65
| 0.623989
|
6a1a7ad18778ade5abbba4bcbff215781d5aed89
| 124
|
package com.topicsbot.services.api.telegram.model;
/**
* Author: Artem Voronov
*/
public interface InlineQueryResult {
}
| 15.5
| 50
| 0.75
|
ddc2fa129f162d1e5df7d79db50c3ac0b363c037
| 2,650
|
/*
* Copyright 2019 The Context Mapper Project Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.hsr.servicecutter.api;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class ServiceCutterContextBuilderTest {
@Test
public void canCreateContextWithoutUserRepresentations() throws IOException {
// given
EntityRelationDiagramImporterJSON importerJSON = new EntityRelationDiagramImporterJSON();
ServiceCutterContextBuilder builder = new ServiceCutterContextBuilder(importerJSON.createERDFromJSONFile(new File("./src/test/resources/booking_1_model.json")));
// when
ServiceCutterContext context = builder.build();
// then
assertNotNull(context.getCriteriaCatalog());
assertNotNull(context.getSolverConfiguration());
assertEquals("Booking", context.getSystemName());
assertTrue(context.getNanoEntities().size() > 0);
assertTrue(context.getCouplingInstances().size() > 0);
}
@Test
public void canCreateContextWithUserRepresentations() throws IOException {
// given
EntityRelationDiagramImporterJSON erdImporterJSON = new EntityRelationDiagramImporterJSON();
UserRepresentationContainerImporterJSON urImporterJSON = new UserRepresentationContainerImporterJSON();
ServiceCutterContextBuilder builder = new ServiceCutterContextBuilder(erdImporterJSON.createERDFromJSONFile(new File("./src/test/resources/booking_1_model.json")))
.withUserRepresentations(urImporterJSON.createUserRepresentationContainerFromJSONFile(new File("./src/test/resources/booking_2_user_representations.json")));
// when
ServiceCutterContext context = builder.build();
// then
assertNotNull(context.getCriteriaCatalog());
assertNotNull(context.getSolverConfiguration());
assertEquals("Booking", context.getSystemName());
assertTrue(context.getNanoEntities().size() > 0);
assertTrue(context.getCouplingInstances().size() > 0);
}
}
| 41.40625
| 173
| 0.738113
|
2a65d5f47bb757950efe0e7339c43e5c123fbf3c
| 3,568
|
/*
* #%L
* Jetro Core
* %%
* Copyright (C) 2013 - 2016 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.
* #L%
*/
package net.sf.jetro.visitor.chained;
import net.sf.jetro.util.Stack;
import net.sf.jetro.visitor.JsonArrayVisitor;
import net.sf.jetro.visitor.JsonObjectVisitor;
import net.sf.jetro.visitor.JsonVisitor;
import java.util.ArrayList;
import java.util.List;
/**
* This class multiplexes all calls to all subsequent visitors.
*
* @param <R> the return type of {@link #getVisitingResult()}
* @author matthias.rothe
* @since 13.03.14.
*/
public final class MultiplexingJsonVisitor<R> extends UniformChainedJsonVisitor<R> {
private List<Stack<JsonVisitor<?>>> visitorStacks;
public MultiplexingJsonVisitor(JsonVisitor<R> masterVisitor, JsonVisitor<?>... slaveVisitors) {
super(masterVisitor);
if (slaveVisitors != null && slaveVisitors.length > 0) {
visitorStacks = new ArrayList<Stack<JsonVisitor<?>>>();
for (JsonVisitor<?> visitor : slaveVisitors) {
Stack<JsonVisitor<?>> stack = new Stack<JsonVisitor<?>>();
stack.push(visitor);
visitorStacks.add(stack);
}
}
}
@Override
protected JsonObjectVisitor<R> afterVisitObject(JsonObjectVisitor<R> visitor) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.push(stack.peek().visitObject());
}
return super.afterVisitObject(visitor);
}
@Override
protected void afterVisitObjectEnd() {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
JsonVisitor<?> topVisitor = stack.peek();
if (topVisitor instanceof JsonObjectVisitor) {
topVisitor.visitEnd();
stack.pop();
}
}
}
@Override
protected JsonArrayVisitor<R> afterVisitArray(JsonArrayVisitor<R> visitor) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.push(stack.peek().visitArray());
}
return super.afterVisitArray(visitor);
}
@Override
protected void afterVisitArrayEnd() {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
JsonVisitor<?> topVisitor = stack.peek();
if (topVisitor instanceof JsonArrayVisitor) {
topVisitor.visitEnd();
stack.pop();
}
}
}
@Override
protected void afterVisitProperty(String name) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.peek().visitProperty(name);
}
}
@Override
protected void afterVisitValue(Boolean value) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.peek().visitValue(value);
}
}
@Override
protected void afterVisitValue(Number value) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.peek().visitValue(value);
}
}
@Override
protected void afterVisitValue(String value) {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.peek().visitValue(value);
}
}
@Override
protected void afterVisitNullValue() {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.peek().visitNullValue();
}
}
@Override
protected void afterVisitEnd() {
for (Stack<JsonVisitor<?>> stack : visitorStacks) {
stack.pop().visitEnd();
}
}
}
| 25.855072
| 96
| 0.705437
|
27379071d79c92855a734daf76dea1cec13ee07f
| 356
|
package io.be.naut;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class UserService {
UserRepository userRepository;
public UserService() {
}
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> list() {
return userRepository.findAll();
}
}
| 15.478261
| 52
| 0.758427
|
f82d98af0c2fc47cd5b0c93b8bbe167f13f668c2
| 2,802
|
package es.upm.miw.apaw_ep_jesus_garceran.team_resource;
import es.upm.miw.apaw_ep_jesus_garceran.ApiTestConfig;
import es.upm.miw.apaw_ep_jesus_garceran.team_data.TeamDto;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ApiTestConfig
class TeamResourceIT {
@Autowired
private WebTestClient webTestClient;
@Test
void testCreate() {
TeamDto teamDto = this.webTestClient
.post().uri(TeamResource.TEAMS)
.body(BodyInserters.fromObject(new TeamCreationDto("Test", "Ciudad anónima", "Escudo")))
.exchange()
.expectStatus().isOk()
.expectBody(TeamDto.class).returnResult().getResponseBody();
assertNotNull(teamDto);
assertEquals("Test", teamDto.getName());
assertEquals("Ciudad anónima", teamDto.getCity());
assertEquals("Escudo", teamDto.getBadge());
}
@Test
void testCreateWithoutName() {
TeamCreationDto teamCreationDto = new TeamCreationDto("", "Ciudad anónima", "Escudo");
this.webTestClient
.post().uri(TeamResource.TEAMS)
.body(BodyInserters.fromObject(teamCreationDto))
.exchange()
.expectStatus().isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void testCreateWithoutCity() {
TeamCreationDto teamCreationDto = new TeamCreationDto("Name", "", "Escudo");
this.webTestClient
.post().uri(TeamResource.TEAMS)
.body(BodyInserters.fromObject(teamCreationDto))
.exchange()
.expectStatus().isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void testCreateWithoutBadge() {
TeamCreationDto teamCreationDto = new TeamCreationDto("Name", "Ciudad anónima", "");
this.webTestClient
.post().uri(TeamResource.TEAMS)
.body(BodyInserters.fromObject(teamCreationDto))
.exchange()
.expectStatus().isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void testGetAllTeams() {
List<TeamDto> teamDtoList =
this.webTestClient
.get().uri(TeamResource.TEAMS)
.exchange()
.expectStatus().isEqualTo(HttpStatus.OK)
.expectBodyList(TeamDto.class).returnResult().getResponseBody();
assertNotNull(teamDtoList);
}
}
| 35.923077
| 104
| 0.642041
|
61f48756ff13734fcff33a478dc098ef42925ce3
| 5,040
|
package ganymedes01.etfuturum.blocks.ores;
import java.util.Random;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import ganymedes01.etfuturum.IConfigurable;
import ganymedes01.etfuturum.ModBlocks;
import ganymedes01.etfuturum.configuration.ConfigurationHandler;
import ganymedes01.etfuturum.core.utils.Utils;
import net.minecraft.block.BlockRedstoneOre;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockDeepslateRedstoneOre extends BlockDeepslateOre implements IConfigurable {
private boolean isLit;
public BlockDeepslateRedstoneOre(boolean lit) {
super(lit ? Blocks.lit_redstone_ore : Blocks.redstone_ore);
if(lit) {
setCreativeTab(null);
setBlockName(Utils.getUnlocalisedName("deepslate_lit_redstone_ore"));
this.isLit = lit;
}
}
/**
* Called when a player hits the block. Args: world, x, y, z, player
*/
public void onBlockClicked(World p_149699_1_, int p_149699_2_, int p_149699_3_, int p_149699_4_, EntityPlayer p_149699_5_)
{
this.func_150185_e(p_149699_1_, p_149699_2_, p_149699_3_, p_149699_4_);
}
/**
* Called whenever an entity is walking on top of this block. Args: world, x, y, z, entity
*/
public void onEntityWalking(World p_149724_1_, int p_149724_2_, int p_149724_3_, int p_149724_4_, Entity p_149724_5_)
{
this.func_150185_e(p_149724_1_, p_149724_2_, p_149724_3_, p_149724_4_);
}
/**
* Called upon block activation (right click on the block.)
*/
public boolean onBlockActivated(World p_149727_1_, int p_149727_2_, int p_149727_3_, int p_149727_4_, EntityPlayer p_149727_5_, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_)
{
this.func_150185_e(p_149727_1_, p_149727_2_, p_149727_3_, p_149727_4_);
return false;
}
private void func_150185_e(World p_150185_1_, int p_150185_2_, int p_150185_3_, int p_150185_4_)
{
this.func_150186_m(p_150185_1_, p_150185_2_, p_150185_3_, p_150185_4_);
if (this == ModBlocks.deepslate_redstone_ore)
{
p_150185_1_.setBlock(p_150185_2_, p_150185_3_, p_150185_4_, ModBlocks.deepslate_lit_redstone_ore);
}
}
/**
* Ticks the block if it's been scheduled
*/
public void updateTick(World p_149674_1_, int p_149674_2_, int p_149674_3_, int p_149674_4_, Random p_149674_5_)
{
if (this == ModBlocks.deepslate_lit_redstone_ore)
{
p_149674_1_.setBlock(p_149674_2_, p_149674_3_, p_149674_4_, ModBlocks.deepslate_redstone_ore);
}
}
private void func_150186_m(World p_150186_1_, int p_150186_2_, int p_150186_3_, int p_150186_4_)
{
Random random = p_150186_1_.rand;
double d0 = 0.0625D;
for (int l = 0; l < 6; ++l)
{
double d1 = (double)((float)p_150186_2_ + random.nextFloat());
double d2 = (double)((float)p_150186_3_ + random.nextFloat());
double d3 = (double)((float)p_150186_4_ + random.nextFloat());
if (l == 0 && !p_150186_1_.getBlock(p_150186_2_, p_150186_3_ + 1, p_150186_4_).isOpaqueCube())
{
d2 = (double)(p_150186_3_ + 1) + d0;
}
if (l == 1 && !p_150186_1_.getBlock(p_150186_2_, p_150186_3_ - 1, p_150186_4_).isOpaqueCube())
{
d2 = (double)(p_150186_3_ + 0) - d0;
}
if (l == 2 && !p_150186_1_.getBlock(p_150186_2_, p_150186_3_, p_150186_4_ + 1).isOpaqueCube())
{
d3 = (double)(p_150186_4_ + 1) + d0;
}
if (l == 3 && !p_150186_1_.getBlock(p_150186_2_, p_150186_3_, p_150186_4_ - 1).isOpaqueCube())
{
d3 = (double)(p_150186_4_ + 0) - d0;
}
if (l == 4 && !p_150186_1_.getBlock(p_150186_2_ + 1, p_150186_3_, p_150186_4_).isOpaqueCube())
{
d1 = (double)(p_150186_2_ + 1) + d0;
}
if (l == 5 && !p_150186_1_.getBlock(p_150186_2_ - 1, p_150186_3_, p_150186_4_).isOpaqueCube())
{
d1 = (double)(p_150186_2_ + 0) - d0;
}
if (d1 < (double)p_150186_2_ || d1 > (double)(p_150186_2_ + 1) || d2 < 0.0D || d2 > (double)(p_150186_3_ + 1) || d3 < (double)p_150186_4_ || d3 > (double)(p_150186_4_ + 1))
{
p_150186_1_.spawnParticle("reddust", d1, d2, d3, 0.0D, 0.0D, 0.0D);
}
}
}
protected ItemStack createStackedBlock(int p_149644_1_)
{
return new ItemStack(ModBlocks.deepslate_redstone_ore);
}
@Override
public boolean isEnabled() {
return ConfigurationHandler.enableDeepslate && ConfigurationHandler.enableDeepslateOres;
}
}
| 36.521739
| 205
| 0.652183
|
122b9ee51585463d1ba6505323ff7a119867858d
| 1,370
|
package uk.co.ribot.assertjrx.api.observable;
import rx.observables.BlockingObservable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* This class takes a {@link BlockingObservable}. It uses {@link BlockingObservable#getIterator()} to triggers the
* subscription. Then it saves the emitted items in a List as well as a Throwable if an error happens.
*/
class BlockingObservableExecutor<T> {
private BlockingObservable<T> blockingObservable;
private Throwable error;
private List<T> itemsEmitted;
BlockingObservableExecutor(BlockingObservable<T> blockingObservable) {
this.blockingObservable = blockingObservable;
this.itemsEmitted = new ArrayList<>();
iterateResults();
}
public Throwable getError() {
return error;
}
public List<T> getValuesEmitted() {
return itemsEmitted;
}
public boolean hasFailed() {
return error != null;
}
public boolean hasCompletedSuccessfully() {
return error == null;
}
private void iterateResults() {
try {
Iterator<T> iterator = blockingObservable.getIterator();
while (iterator.hasNext()) {
itemsEmitted.add(iterator.next());
}
} catch (Throwable throwable) {
error = throwable;
}
}
}
| 25.849057
| 114
| 0.655474
|
dad4d1a20ce13a3fb0fa289d5564819e2ba5a919
| 1,823
|
package io.github.krasnoludkolo.eifer;
import io.vavr.control.Either;
import org.junit.jupiter.api.Test;
import static io.github.krasnoludkolo.eifer.Eifer.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ComplexEiferTest {
private final static Action<Integer> RETURN_ONE = () -> 1;
private final static Condition<Error> TRUE = () -> Either.right(new Success());
private final static Condition<Error> FALSE = () -> Either.left(new Error());
@Test
void shouldDoActionWithTrueConditions() {
int result = when(
or(
TRUE,
FALSE
)
).perform(RETURN_ONE).get();
assertEquals(1, result);
}
@Test
void shouldDoActionWithTrueConditions2() {
int result = when(
and(
or(
TRUE,
FALSE
),
and(
TRUE,
TRUE
)
)
).perform(RETURN_ONE).get();
assertEquals(1, result);
}
@Test
void shouldDoActionWithTrueConditions3() {
int result = when(
TRUE,
TRUE
).orAll(
TRUE
).perform(RETURN_ONE).get();
assertEquals(1, result);
}
@Test
void shouldNotDoActionWithFalseConditions() {
Either<Error, Integer> result = when(
and(
TRUE,
FALSE
)
).perform(RETURN_ONE);
assertTrue(result.isLeft());
}
private static class Error {
}
}
| 24.972603
| 83
| 0.484366
|
b14dc40fbceae17f3df8ec5f1e5d3a52348366e7
| 4,424
|
package kth.se.id2208.top_down.generated.client;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.FaultAction;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.7-b01
* Generated source version: 2.2
*
*/
@WebService(name = "FlightTicketReservationPortType", targetNamespace = "http://flight_reservation")
@XmlSeeAlso({
ObjectFactory.class
})
public interface FlightTicketReservationPortType {
/**
*
* @param arg1
* @param arg0
* @return
* returns java.lang.String
* @throws AuthorizationExceptionException
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "login", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.Login")
@ResponseWrapper(localName = "loginResponse", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.LoginResponse")
@Action(input = "http://flight_reservation/FlightTicketReservationPortType/loginRequest", output = "http://flight_reservation/FlightTicketReservationPortType/loginResponse", fault = {
@FaultAction(className = AuthorizationExceptionException.class, value = "http://flight_reservation/FlightTicketReservationPortType/login/Fault/AuthorizationException_Exception")
})
public String login(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1)
throws AuthorizationExceptionException
;
/**
*
* @param arg2
* @param arg1
* @param arg0
* @return
* returns java.util.List<kth.se.id2208.top_down.generated.client.ItineraryType>
* @throws AuthorizationExceptionException
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getItineraries", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.GetItineraries")
@ResponseWrapper(localName = "getItinerariesResponse", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.GetItinerariesResponse")
@Action(input = "http://flight_reservation/FlightTicketReservationPortType/getItinerariesRequest", output = "http://flight_reservation/FlightTicketReservationPortType/getItinerariesResponse", fault = {
@FaultAction(className = AuthorizationExceptionException.class, value = "http://flight_reservation/FlightTicketReservationPortType/getItineraries/Fault/AuthorizationException_Exception")
})
public List<ItineraryType> getItineraries(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2)
throws AuthorizationExceptionException
;
/**
*
* @param arg0
* @return
* returns java.util.List<kth.se.id2208.top_down.generated.client.GetPriceListResponse.Return>
* @throws AuthorizationExceptionException
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getPriceList", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.GetPriceList")
@ResponseWrapper(localName = "getPriceListResponse", targetNamespace = "http://flight_reservation", className = "kth.se.id2208.top_down.generated.client.GetPriceListResponse")
@Action(input = "http://flight_reservation/FlightTicketReservationPortType/getPriceListRequest", output = "http://flight_reservation/FlightTicketReservationPortType/getPriceListResponse", fault = {
@FaultAction(className = AuthorizationExceptionException.class, value = "http://flight_reservation/FlightTicketReservationPortType/getPriceList/Fault/AuthorizationException_Exception")
})
public List<kth.se.id2208.top_down.generated.client.GetPriceListResponse.Return> getPriceList(
@WebParam(name = "arg0", targetNamespace = "")
String arg0)
throws AuthorizationExceptionException
;
}
| 44.686869
| 205
| 0.731013
|
0a4d8aada7de5d456556ff43d3b2c206b3bf483d
| 1,195
|
package com.dev;
import android.app.Application;
import android.content.Context;
import com.dev.data.DataManager;
import com.dev.di.component.ApplicationComponent;
import com.dev.di.component.DaggerApplicationComponent;
import com.dev.di.module.ApplicationModule;
import com.dev.utils.AppLogger;
import javax.inject.Inject;
public class DevApplication extends Application {
@Inject
DataManager mDataManager;
private ApplicationComponent mApplicationComponent;
static Context context;
@Override
public void onCreate() {
super.onCreate();
this.context = this;
mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this)).build();
mApplicationComponent.inject(this);
AppLogger.init();
}
public ApplicationComponent getComponent() {
return mApplicationComponent;
}
// Needed to replace the component with a test specific one
public void setComponent(ApplicationComponent applicationComponent) {
mApplicationComponent = applicationComponent;
}
public static Context getContext(){
return context;
}
}
| 23.431373
| 73
| 0.725523
|
48dd168312a1d6219511946a313f1a6aa2cc8174
| 2,660
|
/*
* Copyright (c) 2015 Christian Chevalley
* This file is part of Project Ethercis
*
* 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.ethercis.servicemanager.dummy;
import com.ethercis.servicemanager.cluster.RunTimeSingleton;
import com.ethercis.servicemanager.cluster.ClusterInfo;
import com.ethercis.servicemanager.cluster.I_Info;
import com.ethercis.servicemanager.exceptions.ServiceManagerException;
import com.ethercis.servicemanager.service.ServiceInfo;
/**
* This class is JMX instrumentalized<p>
* @author Christian Chevalley
*
*/
public class DummyService2 extends ClusterInfo implements DummyService2MBean{
public static final String __REVISION_ID="$Revision$ $Date$";
//private static Logger log = Logger.getLogger(Constants.LOGGER_SYSTEM);
//private ContextNode contextNode;
private RunTimeSingleton glob;
// private int errors = 0;
private String lasterror;
private String ME="DUMMY2";
private boolean initiated = false;
public void doInit(RunTimeSingleton global, ServiceInfo serviceInfo) throws ServiceManagerException {
this.glob = global;
this.initiated = true;
//add JMX details...
putObject(I_Info.JMX_PREFIX+"DummyService2", this);
}
public boolean initiate() {
return initiated;
}
/**
* JMX - manual publish
*/
public String publish(String URL, String action, String message, int priority){
return "Done\n";
}
public String usage(){
StringBuffer sb = new StringBuffer();
sb.append("publish(String URL, String action, String message, int priority) - publish an arbitrary message\n");
sb.append("where:\n");
sb.append("action: ADD or CANCEL\n");
sb.append("message: text to display\n");
sb.append("priority: 0..9\n");
return sb.toString();
}
public String status(){
StringBuffer sb = new StringBuffer();
sb.append(ME+" version:"+__REVISION_ID+"\n");
sb.append("Last error:"+((lasterror==null)?"*none*":lasterror)+"\n");
return sb.toString();
}
public void shutdown() {
// TODO Auto-generated method stub
}
public String getType() {
return ME;
}
public String getVersion() {
return "1.0";
}
}
| 27.708333
| 113
| 0.725564
|
626816de8b41224903907aa102bda3a6a8ad16c2
| 6,232
|
/**
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.modules;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import com.github.anba.es6draft.compiler.CompilationException;
import com.github.anba.es6draft.parser.ParserException;
import com.github.anba.es6draft.runtime.Realm;
/**
*
*/
public interface ModuleLoader {
/**
* Returns the normalized module identifier.
*
* @param unnormalizedName
* the unnormalized module name
* @param referrerId
* the identifier of the including module or {@code null}
* @return the normalized module identifier
* @throws MalformedNameException
* if the name cannot be normalized
*/
SourceIdentifier normalizeName(String unnormalizedName, SourceIdentifier referrerId) throws MalformedNameException;
/**
* Retrieves the requested module record.
* <p>
* If the module record is not linked, it will be linked against <var>realm</var>.
*
* @param identifier
* the module source identifier
* @param realm
* the realm instance
* @return the module record or {@code null} if not found
*/
ModuleRecord get(SourceIdentifier identifier, Realm realm);
/**
* Defines a new module record in this module loader.
* <p>
* If the module record is not linked, it will be linked against <var>realm</var>.
*
* @param identifier
* the module source identifier
* @param source
* the module source code
* @param realm
* the realm record
* @return the new module record
* @throws IOException
* if there was any I/O error
* @throws IllegalArgumentException
* if the source identifier cannot be processed by this loader
* @throws ParserException
* if the module source contains any syntax errors
* @throws CompilationException
* if the parsed module source cannot be compiled
*/
ModuleRecord define(SourceIdentifier identifier, ModuleSource source, Realm realm)
throws IOException, IllegalArgumentException, ParserException, CompilationException;
/**
* Defines a new module record in this module loader.
* <p>
* If the module record is not linked, it will be linked against <var>realm</var>.
*
* @param identifier
* the module source identifier
* @param source
* the module source code
* @param realm
* the realm record
* @return the new module record
*/
default CompletionStage<ModuleRecord> defineAsync(SourceIdentifier identifier, ModuleSource source, Realm realm) {
try {
return CompletableFuture.completedFuture(define(identifier, source, realm));
} catch (IOException | IllegalArgumentException | ParserException | CompilationException e) {
CompletableFuture<ModuleRecord> c = new CompletableFuture<>();
c.completeExceptionally(e);
return c;
}
}
/**
* Resolves and links the requested module record.
* <p>
* If the module record is not linked, it will be linked against <var>realm</var>.
*
* @param identifier
* the module source identifier
* @param realm
* the realm instance
* @return the module record
* @throws IOException
* if there was any I/O error
* @throws IllegalArgumentException
* if the source identifier cannot be processed by this loader
* @throws ParserException
* if the module source contains any syntax errors
* @throws CompilationException
* if the parsed module source cannot be compiled
*/
ModuleRecord resolve(SourceIdentifier identifier, Realm realm)
throws IOException, IllegalArgumentException, ParserException, CompilationException;
/**
* Resolves and links the requested module record.
* <p>
* If the module record is not linked, it will be linked against <var>realm</var>.
*
* @param identifier
* the module source identifier
* @param realm
* the realm instance
* @return the module record
*/
default CompletionStage<ModuleRecord> resolveAsync(SourceIdentifier identifier, Realm realm) {
try {
return CompletableFuture.completedFuture(resolve(identifier, realm));
} catch (IOException | IllegalArgumentException | ParserException | CompilationException e) {
CompletableFuture<ModuleRecord> c = new CompletableFuture<>();
c.completeExceptionally(e);
return c;
}
}
/**
* Loads a module and all of its dependencies.
*
* @param identifier
* the module source identifier
* @return the loaded module record
* @throws IOException
* if there was any I/O error
* @throws IllegalArgumentException
* if the source identifier cannot be processed by this loader
* @throws MalformedNameException
* if the module specifier cannot be normalized
*/
ModuleRecord load(SourceIdentifier identifier) throws IOException, IllegalArgumentException, MalformedNameException;
/**
* Loads a module and all of its dependencies.
*
* @param identifier
* the module source identifier
* @return the loaded module record
*/
default CompletionStage<ModuleRecord> loadAsync(SourceIdentifier identifier) {
try {
return CompletableFuture.completedFuture(load(identifier));
} catch (IOException | IllegalArgumentException | MalformedNameException e) {
CompletableFuture<ModuleRecord> c = new CompletableFuture<>();
c.completeExceptionally(e);
return c;
}
}
}
| 36.87574
| 120
| 0.638158
|
99a820d30294763189d9b5c8f9888a3fc88c481b
| 3,854
|
package com.github.dadiyang.wechat.client;
import com.github.dadiyang.wechat.ApiTestBase;
import com.github.dadiyang.wechat.result.ClientResult;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ThreadLocalRandom;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ClientApiTest extends ApiTestBase {
private ClientApi clientApi;
private String client;
@Before
public void setup() {
clientApi = factory.getProxy(ClientApi.class);
client = String.valueOf(ThreadLocalRandom.current().nextInt());
}
@Test
public void getClientInfo() {
System.out.println("测试获取客户端信息");
String resultExample = "{\n" +
" \"code\":0,\n" +
" \"account\":\"default\",\n" +
" \"log_encoding\":null,\n" +
" \"log_level\":\"debug\",\n" +
" \"log_path\":null,\n" +
" \"os\":\"linux\",\n" +
" \"pid\":15497,\n" +
" \"runtime\":3096,\n" +
" \"starttime\":1475135588,\n" +
" \"status\":\"success\",\n" +
" \"http_debug\":\"0\",\n" +
" \"version\":\"1.2.0\"\n" +
" }";
String uri = "/openwx/get_client_info";
wireMockRule.stubFor(get(urlPathEqualTo(uri)).withQueryParam("client", equalTo(client)).willReturn(okJson(resultExample)));
ClientInfo clientInfo = clientApi.getClientInfo(client);
System.out.println("测试获取客户端信息结果: " + clientInfo);
assertNotNull(clientInfo);
assertEquals(0, clientInfo.getCode());
assertEquals("default", clientInfo.getAccount());
assertEquals("debug", clientInfo.getLogLevel());
assertEquals(15497, clientInfo.getPid());
}
@Test
public void stopClient() {
System.out.println("测试停止客户端");
String resultExample = "{\"client\":\"weixin_client_01\",\"code\":0,\"pid\":32294,\"port\":3000,\"status\":\"success\"}";
String uri = "/openwx/stop_client";
wireMockRule.stubFor(get(urlPathEqualTo(uri)).withQueryParam("client", equalTo(client)).willReturn(okJson(resultExample)));
ClientResult result = clientApi.stopClient(client);
System.out.println("测试停止客户端结果: " + result);
assertNotNull(result);
assertEquals(result.getCode(), 0);
assertEquals(result.getPid(), 32294);
assertEquals(result.getPort(), 3000);
}
@Test
public void startClient() {
System.out.println("测试启动客户端");
String resultExample = "{\"client\":\"weixin_client_01\",\"code\":0,\"pid\":32294,\"port\":3000,\"status\":\"success\"}";
String uri = "/openwx/start_client";
wireMockRule.stubFor(get(urlPathEqualTo(uri)).withQueryParam("client", equalTo(client)).willReturn(okJson(resultExample)));
ClientResult result = clientApi.startClient(client);
System.out.println("测试启动客户端结果: " + result);
assertNotNull(result);
assertEquals(result.getCode(), 0);
assertEquals(result.getPid(), 32294);
assertEquals(result.getPort(), 3000);
}
@Test
public void getQrcode() throws IOException {
System.out.println("测试获取登录二维码文件");
String uri = "/openwx/get_qrcode";
wireMockRule.stubFor(get(urlPathEqualTo(uri)).withQueryParam("client", equalTo(client)).willReturn(ok("OK")));
InputStream result = clientApi.getQrcode(client);
System.out.println("测试获取登录二维码文件客户端结果: " + result);
assertNotNull(result);
assertTrue(result.available() > 0);
}
}
| 41
| 131
| 0.614946
|
ac588c4e2264a5485aa876580e4ad35f035b9bb1
| 2,245
|
/*
* 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.inlong.manager.common.pojo.workflow.form;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.inlong.manager.common.exceptions.FormValidateException;
import org.apache.inlong.manager.common.pojo.group.InlongGroupRequest;
import java.util.Map;
/**
* Form of create inlong group resource
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class GroupResourceProcessForm extends BaseProcessForm {
public static final String FORM_NAME = "GroupResourceProcessForm";
private InlongGroupRequest groupInfo;
private String streamId;
public InlongGroupRequest getGroupInfo() {
return groupInfo;
}
public void setGroupInfo(InlongGroupRequest groupInfo) {
this.groupInfo = groupInfo;
}
@Override
public void validate() throws FormValidateException {
}
@Override
public String getFormName() {
return FORM_NAME;
}
@Override
public String getInlongGroupId() {
return groupInfo.getInlongGroupId();
}
public String getInlongStreamId() {
return streamId;
}
public void setInlongStreamId(String streamId) {
this.streamId = streamId;
}
@Override
public Map<String, Object> showInList() {
Map<String, Object> show = Maps.newHashMap();
show.put("inlongGroupId", groupInfo.getInlongGroupId());
return show;
}
}
| 28.782051
| 75
| 0.726503
|
8631d342d51436e253db2ba9cbbec299fe9c0631
| 9,539
|
/*
Copyright (c) 2016 Robert Atkinson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode.Teleop;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.Range;
import org.firstinspires.ftc.teamcode.DriversAndHardware.Hardware3415;
/**
* This OpMode uses the common HardwareK9bot class to define the devices on the Balin.
* All device access is managed through the HardwareK9bot class. (See this class for device names)
* The code is structured as a LinearOpMode
*
* This particular OpMode executes a basic Tank Drive Teleop for the K9 bot
* It raises and lowers the arm using the Gampad Y and A buttons respectively.
* It also opens and closes the claw slowly using the X and B buttons.
*
* Note: the configuration of the servos is such that
* as the arm servo approaches 0, the arm position moves up (away from the floor).
* Also, as the claw servo approaches 0, the claw opens up (drops the game element).
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@TeleOp(name="Teleop Without Perspective Drive", group="Competition")
public class TeleopWithHardwareFromRobWithoutPerspectiveDrive extends LinearOpMode {
/* Declare OpMode members. */
Hardware3415 Balin = new Hardware3415();
public static double x, y, z, trueX, trueY;
public static double frPower, flPower, brPower, blPower;
@Override
public void runOpMode() {
/* Initialize the hardware variables.
* The init() method of the hardware class does all the work here
*/
Balin.init(hardwareMap, false);
Balin.limitState = Balin.limit.getState();
// Send telemetry message to signify Balin waiting;
telemetry.addData("Ready?", "Yes");
telemetry.update();
// Wait for the game to start (driver presses PLAY)
waitForStart();
Balin.rollerRelease.setPosition(Balin.ROLLER_RELEASE_OUT);
// run until the end of the match (driver presses STOP)
while (opModeIsActive() && !isStopRequested()) {
//Sets controls for linear slides on forklift
if (gamepad2.right_stick_y < -.15) {
Balin.liftLeft.setPower(Range.clip(gamepad2.right_stick_y, -1, 1));
Balin.liftRight.setPower(Range.clip(gamepad2.right_stick_y, -1, 1));
} else if(gamepad2.right_stick_y > .15 && Balin.limitState) {
Balin.liftLeft.setPower(0);
Balin.liftRight.setPower(0);
} else if(gamepad2.right_stick_y > .15 && !Balin.limitState){
Balin.liftLeft.setPower(Range.clip(gamepad2.right_stick_y, -1, 1));
Balin.liftRight.setPower(Range.clip(gamepad2.right_stick_y, -1, 1));
} else {
Balin.liftLeft.setPower(0);
Balin.liftRight.setPower(0);
}
//Sets controls for shooter
if (gamepad1.left_trigger > .15) {
Balin.shoot(1);
} else if (gamepad1.left_bumper) {
Balin.shoot(0);
}
//Sets controls for collector
if (gamepad1.right_trigger > 0.15) {
Balin.collector.setPower(0.99);
} else if (gamepad1.right_bumper) {
Balin.collector.setPower(-0.99);
} else {
Balin.collector.setPower(0);
}
//Sets the gamepad values to x, y, and z
z = gamepad1.right_stick_x; //sideways
y = gamepad1.left_stick_y; //forward and backward
x = gamepad1.left_stick_x; //rotation
//Sets the motor powers of the wheels to the correct power based on all three of the above gyro values and
//scales them accordingly
flPower = Range.scale((-x + y - z), -1, 1, -Balin.MAX_MOTOR_SPEED, Balin.MAX_MOTOR_SPEED);
frPower = Range.scale((-x - y - z), -1, 1, -Balin.MAX_MOTOR_SPEED, Balin.MAX_MOTOR_SPEED);
blPower = Range.scale((x + y - z), -1, 1, -Balin.MAX_MOTOR_SPEED, Balin.MAX_MOTOR_SPEED);
brPower = Range.scale((x - y - z), -1, 1, -Balin.MAX_MOTOR_SPEED, Balin.MAX_MOTOR_SPEED);
//Sets each motor power to the correct power
Balin.fl.setPower(flPower);
Balin.fr.setPower(frPower);
Balin.bl.setPower(blPower);
Balin.br.setPower(brPower);
//Backup movement if the above method fails
/*
if (x == 0 && y == 0 && z == 0) {
if (gamepad1.dpad_right) {
Balin.bl.setPower(Balin.MAX_MOTOR_SPEED);
Balin.fl.setPower(Balin.MAX_MOTOR_SPEED);
} else if (gamepad1.dpad_up) {
Balin.bl.setPower(-Balin.MAX_MOTOR_SPEED);
Balin.fl.setPower(-Balin.MAX_MOTOR_SPEED);
} else if (gamepad1.dpad_down) {
Balin.br.setPower(Balin.MAX_MOTOR_SPEED);
Balin.fr.setPower(Balin.MAX_MOTOR_SPEED);
} else if (gamepad1.dpad_left) {
Balin.br.setPower(-Balin.MAX_MOTOR_SPEED);
Balin.fr.setPower(-Balin.MAX_MOTOR_SPEED);
}
}
*/
//Control servo toggling for beacon pushers and clamps
Balin.beaconPushLeftToggleReturnArray = Balin.servoToggle(gamepad2.left_trigger > .15, Balin.beaconPushLeft, Balin.beaconPushLeftPositions, Balin.beaconPushLeftPos, Balin.beaconPushLeftButtonPressed, this);
Balin.beaconPushLeftPos = Balin.beaconPushLeftToggleReturnArray[0];
Balin.beaconPushLeftButtonPressed = Balin.beaconPushLeftToggleReturnArray[1] == 1;
Balin.beaconPushRightToggleReturnArray = Balin.servoToggle(gamepad2.right_trigger > .15, Balin.beaconPushRight, Balin.beaconPushRightPositions, Balin.beaconPushRightPos, Balin.beaconPushRightButtonPressed, this);
Balin.beaconPushRightPos = Balin.beaconPushRightToggleReturnArray[0];
Balin.beaconPushRightButtonPressed = Balin.beaconPushRightToggleReturnArray[1] == 1;
Balin.doorToggleReturnArray = Balin.servoToggle(gamepad1.a, Balin.door, Balin.doorPositions, Balin.doorPos, Balin.doorButtonPressed, this);
Balin.doorPos = Balin.doorToggleReturnArray[0];
Balin.doorButtonPressed = Balin.doorToggleReturnArray[1] == 1;
if(gamepad2.a) {
Balin.clampLeft.setPosition(Balin.LEFT_CLAMP_CLAMP);
Balin.clampRight.setPosition(Balin.RIGHT_CLAMP_CLAMP);
}
else if (gamepad2.y) {
Balin.clampLeft.setPosition(Balin.LEFT_CLAMP_UP);
Balin.clampRight.setPosition(Balin.RIGHT_CLAMP_UP);
}
if(gamepad2.b) {
Balin.clampLeft.setPosition(Balin.LEFT_CLAMP_INITIAL_STATE);
Balin.clampRight.setPosition(Balin.RIGHT_CLAMP_INITIAL_STATE);
}
//Returns important data to the driver.
telemetry.addData("GamePad 1 Right Stick X Actual", gamepad1.right_stick_x);
telemetry.addData("GamePad 1 Left Stick Y Actual", gamepad1.left_stick_y);
telemetry.addData("GamePad 1 Left Stick X Actual", gamepad1.left_stick_x);
telemetry.addData("GamePad 1 X", gamepad1.x);
telemetry.addData("FR Power", Balin.fr.getPower());
telemetry.addData("FL Power", Balin.fl.getPower());
telemetry.addData("BR Power", Balin.br.getPower());
telemetry.addData("BL Power", Balin.bl.getPower());
telemetry.update();
// Pause for metronome tick. 40 mS each cycle = update 25 times a second.
Balin.waitForTick(40);
}
}
}
| 48.668367
| 224
| 0.662753
|
da2b244943cdd64c4a945bc630e97dc4df6cc713
| 665
|
package cn.meetdevelop.lesson_1;
/**
* @author zgy
* @DATE 2019/12/4 - 20:39
*/
public class LambdaDemo {
public static void main(String[] args) {
Action action = () -> {
System.out.println("Execute");
};
//System.out.println(Action.doExecute());
Action action1 = LambdaDemo::sayHello;
action1.execute();
}
public interface Action {
void execute();
static String doExecute() {
return "hello World";
}
boolean equals(Object o);
}
static void sayHello() {
System.out.println("Hello World");
}
}
| 19.558824
| 50
| 0.521805
|
a5d281a72b8513fdbb7089b11ffb5863cb5ee0c4
| 913
|
/**
* ADOBE SYSTEMS INCORPORATED
* Copyright 2009-2013 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute
* this file in accordance with the terms of the MIT license,
* a copy of which can be found in the LICENSE.txt file or at
* http://opensource.org/licenses/MIT.
*/
package runtime.sys;
import runtime.rep.list.ListValue;
import runtime.rep.list.PersistentList;
/**
* Manages runtime command-line arguments
*
* @author Keith McGuigan
*/
public final class Arguments
{
private static ListValue arguments = PersistentList.EMPTY;
/**
* Add a new string argument (copy on write)
*/
public static synchronized void add(final String value)
{
arguments = arguments.append(value);
}
/**
* Retrieve the arguments
*/
public static ListValue get()
{
return arguments;
}
}
| 22.268293
| 62
| 0.681271
|
260c11ea6342c1be5b714d9260f9ff389a99b129
| 1,608
|
/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-
*
* Copyright © 2018 microBean.
*
* 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.microbean.kubernetes.controller.cdi.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.enterprise.context.NormalScope;
/**
* A {@link NormalScope}-annotated annotation denoting a scope that is
* active during the lifespan of a CDI event fired by the {@link
* org.microbean.kubernetes.controller.cdi.KubernetesControllerExtension}
* and only on the same thread as that on which the relevant observer
* method is notified, or one of its descendant threads.
*
* @author <a href="https://about.me/lairdnelson"
* target="_parent">Laird Nelson</a>
*/
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@NormalScope
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE })
public @interface KubernetesEventScoped {
}
| 36.545455
| 83
| 0.75995
|
837107332702f39eda52661dd44bf641b087a313
| 506
|
package se.l4.dust.api.template;
/**
* Exception related to components, thrown when components are missing or
* misbehaving.
*
* @author Andreas Holstenson
*
*/
public class ComponentException
extends TemplateException
{
public ComponentException()
{
super();
}
public ComponentException(String message, Throwable cause)
{
super(message, cause);
}
public ComponentException(String message)
{
super(message);
}
public ComponentException(Throwable cause)
{
super(cause);
}
}
| 14.457143
| 73
| 0.725296
|
83b614904a3d5668e08c2de7c9b4e9226132e7a7
| 6,173
|
package org.contentmine.svg2xml.text;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.contentmine.eucl.euclid.IntArray;
import org.contentmine.graphics.svg.text.line.TextLine;
import org.contentmine.graphics.svg.text.structure.TextStructurer;
public class TextContainerTest {
private final static Logger LOG = Logger.getLogger(TextContainerTest.class);
@Test
public void testTextContainerRead() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
List<TextLine> textLineList = textContainer.getTextLineList();
Assert.assertEquals("textLineCount", 16, textLineList.size());
}
@Test
public void testTextContainerFonts() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
List<TextLine> textLineList = textContainer.getTextLineList();
Assert.assertEquals("header", "Helvetica", textLineList.get(0).getFontFamily());
Assert.assertEquals("header", "TimesNewRoman", textLineList.get(1).getFontFamily());
Assert.assertEquals("header", "TimesNewRoman", textLineList.get(15).getFontFamily());
}
@Test
public void testTextContainerSizes() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
List<TextLine> textLineList = textContainer.getTextLineList();
Assert.assertEquals("header", 10.261, textLineList.get(0).getFontSize(), 0.001);
Assert.assertEquals("header", 9.76, textLineList.get(1).getFontSize(), 0.01);
Assert.assertEquals("header", 9.76, textLineList.get(15).getFontSize(), 0.01);
for (TextLine textLine: textLineList) {
LOG.trace(textLine);
}
}
@Test
public void testTextContainerWeight() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
List<TextLine> textLineList = textContainer.getTextLineList();
Assert.assertTrue("header", textLineList.get(0).isBold());
Assert.assertFalse("header", textLineList.get(1).isBold());
Assert.assertFalse("header", textLineList.get(15).isBold());
for (TextLine textLine: textLineList) {
LOG.trace(textLine);
}
}
@Test
public void testTextContainerLineIsCommonestFontSize() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
Assert.assertEquals("commonest size", 9.76, textContainer.getCommonestFontSize().getDouble(), 0.001);
TextLine textLine0 = textContainer.getTextLineList().get(0);
Assert.assertFalse("not commonest size", textContainer.isCommonestFontSize(textLine0));
TextLine textLine1 = textContainer.getTextLineList().get(1);
LOG.trace("textLine1 "+textLine1);
Assert.assertTrue("commonest Font Size", textContainer.isCommonestFontSize(textLine1));;
}
@Test
public void testTextContainerLineIsDifferentSize() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
Assert.assertEquals("commonest size", 9.76, textContainer.getCommonestFontSize().getDouble(), 0.001);
TextLine textLine0 = textContainer.getTextLineList().get(0);
Assert.assertFalse("not commonestFontSize", textContainer.isCommonestFontSize(textLine0));
Assert.assertTrue("line 0 different size", textContainer.lineIsLargerThanCommonestFontSize(textLine0));
TextLine textLine1 = textContainer.getTextLineList().get(1);
Assert.assertTrue("isCommonestFontSize", textContainer.isCommonestFontSize(textLine1));
Assert.assertFalse("line 1 not different size", textContainer.lineIsLargerThanCommonestFontSize(textLine1));
}
@Test
public void testTextContainerLineIsBold() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
TextLine textLine0 = textContainer.getTextLineList().get(0);
Assert.assertTrue("line 0 bold", textLine0.isBold());
TextLine textLine1 = textContainer.getTextLineList().get(1);
Assert.assertFalse("line 1 bold", textLine1.isBold());
// this should be bold but didn't trigger threshold in PDF2SVG
textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_4_3_SVG);
textLine0 = textContainer.getTextLineList().get(0);
Assert.assertFalse("line 0 bold", textLine0.isBold());
textLine1 = textContainer.getTextLineList().get(1);
Assert.assertFalse("line 1 bold", textLine1.isBold());
}
@Test
public void testTextContainerLineGetFontFamily() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
TextLine textLine0 = textContainer.getTextLineList().get(0);
Assert.assertEquals("line 0", "Helvetica", textLine0.getFontFamily());
TextLine textLine1 = textContainer.getTextLineList().get(1);
Assert.assertEquals("line 1", "TimesNewRoman", textLine1.getFontFamily());
}
@Test //this is
public void testTextContainerSplitLineSizesNone() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_8_SVG);
IntArray intArray = textContainer.splitGroupBiggerThanCommonest();
LOG.trace(intArray);
int[] ref = {};
Assert.assertTrue("split", new IntArray(ref).equals(intArray));
}
@Test
public void testTextContainerSplitLineSizesOne() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_1_6_SVG);
IntArray intArray = textContainer.splitGroupBiggerThanCommonest();
LOG.trace(intArray);
int[] ref = {0};
Assert.assertTrue("split", new IntArray(ref).equals(intArray));
}
@Test
public void testTextContainerSplitLineSizesNoneButFont() {
TextStructurer textContainer = TextStructurer.createTextStructurerWithSortedLines(TextFixtures.BMC_174_4_3_SVG);
IntArray intArray = textContainer.splitGroupBiggerThanCommonest();
LOG.trace(intArray);
int[] ref = {};
Assert.assertTrue("split", new IntArray(ref).equals(intArray));
}
}
| 45.725926
| 115
| 0.774178
|
9bca6e5cdbb57fa021876d88ad464676bb3ad227
| 14,721
|
/*
* 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.servicecomb.foundation.protobuf.internal.model;
import java.util.List;
import java.util.Map;
import org.apache.servicecomb.foundation.test.scaffolding.model.Color;
import io.protostuff.Tag;
/**
* Tag annotation is only for protoStuff, not necessary for ServiceComb codec
*/
public class Root {
@Tag(1)
private int int32;
@Tag(2)
private long int64;
@Tag(3)
private int uint32;
@Tag(4)
private long uint64;
@Tag(5)
private int sint32;
@Tag(6)
private long sint64;
@Tag(7)
private int fixed32;
@Tag(8)
private long fixed64;
@Tag(9)
private int sfixed32;
@Tag(10)
private long sfixed64;
@Tag(11)
private float floatValue;
@Tag(12)
private double doubleValue;
@Tag(13)
private boolean bool;
@Tag(20)
private Integer objInt32;
@Tag(21)
private Long objInt64;
@Tag(22)
private Integer objUint32;
@Tag(23)
private Long objUint64;
@Tag(24)
private Integer objSint32;
@Tag(25)
private Long objSint64;
@Tag(26)
private Integer objFixed32;
@Tag(27)
private Long objFixed64;
@Tag(28)
private Integer objSfixed32;
@Tag(29)
private Long objSfixed64;
@Tag(30)
private Float objFloatValue;
@Tag(31)
private Double objDoubleValue;
@Tag(32)
private Boolean objBool;
@Tag(40)
private String string;
@Tag(41)
private byte[] bytes;
@Tag(42)
private Color color;
@Tag(43)
private User user;
@Tag(44)
private Root typeRecursive;
@Tag(50)
private Object any;
@Tag(51)
private List<Object> anys;
@Tag(60)
private Map<String, String> ssMap;
@Tag(61)
private Map<String, Integer> sint32Map;
@Tag(62)
private Map<String, User> spMap;
// repeated packed
@Tag(70)
private List<Integer> int32sPacked;
@Tag(71)
private List<Long> int64sPacked;
@Tag(72)
private List<Integer> uint32sPacked;
@Tag(73)
private List<Long> uint64sPacked;
@Tag(74)
private List<Integer> sint32sPacked;
@Tag(75)
private List<Long> sint64sPacked;
@Tag(76)
private List<Integer> fixed32sPacked;
@Tag(77)
private List<Long> fixed64sPacked;
@Tag(78)
private List<Integer> sfixed32sPacked;
@Tag(79)
private List<Long> sfixed64sPacked;
@Tag(80)
private List<Float> floatsPacked;
@Tag(81)
private List<Double> doublesPacked;
@Tag(82)
private List<Boolean> boolsPacked;
@Tag(83)
private List<Color> colorsPacked;
// repeated not packed
@Tag(90)
private List<Integer> int32sNotPacked;
@Tag(91)
private List<Long> int64sNotPacked;
@Tag(92)
private List<Integer> uint32sNotPacked;
@Tag(93)
private List<Long> uint64sNotPacked;
@Tag(94)
private List<Integer> sint32sNotPacked;
@Tag(95)
private List<Long> sint64sNotPacked;
@Tag(96)
private List<Integer> fixed32sNotPacked;
@Tag(97)
private List<Long> fixed64sNotPacked;
@Tag(98)
private List<Integer> sfixed32sNotPacked;
@Tag(99)
private List<Long> sfixed64sNotPacked;
@Tag(100)
private List<Float> floatsNotPacked;
@Tag(101)
private List<Double> doublesNotPacked;
@Tag(102)
private List<Boolean> boolsNotPacked;
@Tag(103)
private List<Color> colorsNotPacked;
@Tag(110)
private List<String> strings;
@Tag(111)
private List<byte[]> bytess;
@Tag(112)
private List<User> users;
public int getInt32() {
return int32;
}
public void setInt32(int int32) {
this.int32 = int32;
}
public long getInt64() {
return int64;
}
public void setInt64(long int64) {
this.int64 = int64;
}
public int getUint32() {
return uint32;
}
public void setUint32(int uint32) {
this.uint32 = uint32;
}
public long getUint64() {
return uint64;
}
public void setUint64(long uint64) {
this.uint64 = uint64;
}
public int getSint32() {
return sint32;
}
public void setSint32(int sint32) {
this.sint32 = sint32;
}
public long getSint64() {
return sint64;
}
public void setSint64(long sint64) {
this.sint64 = sint64;
}
public int getFixed32() {
return fixed32;
}
public void setFixed32(int fixed32) {
this.fixed32 = fixed32;
}
public long getFixed64() {
return fixed64;
}
public void setFixed64(long fixed64) {
this.fixed64 = fixed64;
}
public int getSfixed32() {
return sfixed32;
}
public void setSfixed32(int sfixed32) {
this.sfixed32 = sfixed32;
}
public long getSfixed64() {
return sfixed64;
}
public void setSfixed64(long sfixed64) {
this.sfixed64 = sfixed64;
}
public float getFloatValue() {
return floatValue;
}
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Map<String, String> getSsMap() {
return ssMap;
}
public void setSsMap(Map<String, String> ssMap) {
this.ssMap = ssMap;
}
public Map<String, User> getSpMap() {
return spMap;
}
public void setSpMap(Map<String, User> spMap) {
this.spMap = spMap;
}
public Object getAny() {
return any;
}
public void setAny(Object any) {
this.any = any;
}
public List<Object> getAnys() {
return anys;
}
public void setAnys(List<Object> anys) {
this.anys = anys;
}
public Root getTypeRecursive() {
return typeRecursive;
}
public void setTypeRecursive(Root typeRecursive) {
this.typeRecursive = typeRecursive;
}
public List<Integer> getInt32sPacked() {
return int32sPacked;
}
public void setInt32sPacked(List<Integer> int32sPacked) {
this.int32sPacked = int32sPacked;
}
public List<Long> getInt64sPacked() {
return int64sPacked;
}
public void setInt64sPacked(List<Long> int64sPacked) {
this.int64sPacked = int64sPacked;
}
public List<Integer> getUint32sPacked() {
return uint32sPacked;
}
public void setUint32sPacked(List<Integer> uint32sPacked) {
this.uint32sPacked = uint32sPacked;
}
public List<Long> getUint64sPacked() {
return uint64sPacked;
}
public void setUint64sPacked(List<Long> uint64sPacked) {
this.uint64sPacked = uint64sPacked;
}
public List<Integer> getSint32sPacked() {
return sint32sPacked;
}
public void setSint32sPacked(List<Integer> sint32sPacked) {
this.sint32sPacked = sint32sPacked;
}
public List<Long> getSint64sPacked() {
return sint64sPacked;
}
public void setSint64sPacked(List<Long> sint64sPacked) {
this.sint64sPacked = sint64sPacked;
}
public List<Integer> getFixed32sPacked() {
return fixed32sPacked;
}
public void setFixed32sPacked(List<Integer> fixed32sPacked) {
this.fixed32sPacked = fixed32sPacked;
}
public List<Long> getFixed64sPacked() {
return fixed64sPacked;
}
public void setFixed64sPacked(List<Long> fixed64sPacked) {
this.fixed64sPacked = fixed64sPacked;
}
public List<Integer> getSfixed32sPacked() {
return sfixed32sPacked;
}
public void setSfixed32sPacked(List<Integer> sfixed32sPacked) {
this.sfixed32sPacked = sfixed32sPacked;
}
public List<Long> getSfixed64sPacked() {
return sfixed64sPacked;
}
public void setSfixed64sPacked(List<Long> sfixed64sPacked) {
this.sfixed64sPacked = sfixed64sPacked;
}
public List<Float> getFloatsPacked() {
return floatsPacked;
}
public void setFloatsPacked(List<Float> floatsPacked) {
this.floatsPacked = floatsPacked;
}
public List<Double> getDoublesPacked() {
return doublesPacked;
}
public void setDoublesPacked(List<Double> doublesPacked) {
this.doublesPacked = doublesPacked;
}
public List<Boolean> getBoolsPacked() {
return boolsPacked;
}
public void setBoolsPacked(List<Boolean> boolsPacked) {
this.boolsPacked = boolsPacked;
}
public List<Color> getColorsPacked() {
return colorsPacked;
}
public void setColorsPacked(List<Color> colorsPacked) {
this.colorsPacked = colorsPacked;
}
public List<Integer> getInt32sNotPacked() {
return int32sNotPacked;
}
public void setInt32sNotPacked(List<Integer> int32sNotPacked) {
this.int32sNotPacked = int32sNotPacked;
}
public List<Long> getInt64sNotPacked() {
return int64sNotPacked;
}
public void setInt64sNotPacked(List<Long> int64sNotPacked) {
this.int64sNotPacked = int64sNotPacked;
}
public List<Integer> getUint32sNotPacked() {
return uint32sNotPacked;
}
public void setUint32sNotPacked(List<Integer> uint32sNotPacked) {
this.uint32sNotPacked = uint32sNotPacked;
}
public List<Long> getUint64sNotPacked() {
return uint64sNotPacked;
}
public void setUint64sNotPacked(List<Long> uint64sNotPacked) {
this.uint64sNotPacked = uint64sNotPacked;
}
public List<Integer> getSint32sNotPacked() {
return sint32sNotPacked;
}
public void setSint32sNotPacked(List<Integer> sint32sNotPacked) {
this.sint32sNotPacked = sint32sNotPacked;
}
public List<Long> getSint64sNotPacked() {
return sint64sNotPacked;
}
public void setSint64sNotPacked(List<Long> sint64sNotPacked) {
this.sint64sNotPacked = sint64sNotPacked;
}
public List<Integer> getFixed32sNotPacked() {
return fixed32sNotPacked;
}
public void setFixed32sNotPacked(List<Integer> fixed32sNotPacked) {
this.fixed32sNotPacked = fixed32sNotPacked;
}
public List<Long> getFixed64sNotPacked() {
return fixed64sNotPacked;
}
public void setFixed64sNotPacked(List<Long> fixed64sNotPacked) {
this.fixed64sNotPacked = fixed64sNotPacked;
}
public List<Integer> getSfixed32sNotPacked() {
return sfixed32sNotPacked;
}
public void setSfixed32sNotPacked(List<Integer> sfixed32sNotPacked) {
this.sfixed32sNotPacked = sfixed32sNotPacked;
}
public List<Long> getSfixed64sNotPacked() {
return sfixed64sNotPacked;
}
public void setSfixed64sNotPacked(List<Long> sfixed64sNotPacked) {
this.sfixed64sNotPacked = sfixed64sNotPacked;
}
public List<Float> getFloatsNotPacked() {
return floatsNotPacked;
}
public void setFloatsNotPacked(List<Float> floatsNotPacked) {
this.floatsNotPacked = floatsNotPacked;
}
public List<Double> getDoublesNotPacked() {
return doublesNotPacked;
}
public void setDoublesNotPacked(List<Double> doublesNotPacked) {
this.doublesNotPacked = doublesNotPacked;
}
public List<Boolean> getBoolsNotPacked() {
return boolsNotPacked;
}
public void setBoolsNotPacked(List<Boolean> boolsNotPacked) {
this.boolsNotPacked = boolsNotPacked;
}
public List<Color> getColorsNotPacked() {
return colorsNotPacked;
}
public void setColorsNotPacked(
List<Color> colorsNotPacked) {
this.colorsNotPacked = colorsNotPacked;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
public List<byte[]> getBytess() {
return bytess;
}
public void setBytess(List<byte[]> bytess) {
this.bytess = bytess;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Integer getObjInt32() {
return objInt32;
}
public void setObjInt32(Integer objInt32) {
this.objInt32 = objInt32;
}
public Long getObjInt64() {
return objInt64;
}
public void setObjInt64(Long objInt64) {
this.objInt64 = objInt64;
}
public Integer getObjUint32() {
return objUint32;
}
public void setObjUint32(Integer objUint32) {
this.objUint32 = objUint32;
}
public Long getObjUint64() {
return objUint64;
}
public void setObjUint64(Long objUint64) {
this.objUint64 = objUint64;
}
public Integer getObjSint32() {
return objSint32;
}
public void setObjSint32(Integer objSint32) {
this.objSint32 = objSint32;
}
public Long getObjSint64() {
return objSint64;
}
public void setObjSint64(Long objSint64) {
this.objSint64 = objSint64;
}
public Integer getObjFixed32() {
return objFixed32;
}
public void setObjFixed32(Integer objFixed32) {
this.objFixed32 = objFixed32;
}
public Long getObjFixed64() {
return objFixed64;
}
public void setObjFixed64(Long objFixed64) {
this.objFixed64 = objFixed64;
}
public Integer getObjSfixed32() {
return objSfixed32;
}
public void setObjSfixed32(Integer objSfixed32) {
this.objSfixed32 = objSfixed32;
}
public Long getObjSfixed64() {
return objSfixed64;
}
public void setObjSfixed64(Long objSfixed64) {
this.objSfixed64 = objSfixed64;
}
public Float getObjFloatValue() {
return objFloatValue;
}
public void setObjFloatValue(Float objFloatValue) {
this.objFloatValue = objFloatValue;
}
public Double getObjDoubleValue() {
return objDoubleValue;
}
public void setObjDoubleValue(Double objDoubleValue) {
this.objDoubleValue = objDoubleValue;
}
public Boolean isObjBool() {
return objBool;
}
public void setObjBool(Boolean objBool) {
this.objBool = objBool;
}
public Map<String, Integer> getSint32Map() {
return sint32Map;
}
public void setSint32Map(Map<String, Integer> sint32Map) {
this.sint32Map = sint32Map;
}
}
| 19.118182
| 77
| 0.695877
|
f38daf201b45a45ac08bb3bfddbb8ee662b9d5c3
| 1,487
|
package com.buildfailure.yaig.services;
import com.buildfailure.yaig.entities.InvoiceContext;
import org.springframework.stereotype.Service;
@Service
public class ContextMerger {
public InvoiceContext merge(InvoiceContext base, InvoiceContext individual){
InvoiceContext invoiceContext = new InvoiceContext();
if(individual.getId() != null){
invoiceContext.setId(individual.getId());
} else {
invoiceContext.setId(base.getId());
}
if(individual.getVat() != null){
invoiceContext.setVat(individual.getVat());
} else {
invoiceContext.setVat(base.getVat());
}
if(individual.getLocale() != null){
invoiceContext.setLocale(individual.getLocale());
} else {
invoiceContext.setLocale(base.getLocale());
}
if(individual.getTemplate() != null){
invoiceContext.setTemplate(individual.getTemplate());
} else {
invoiceContext.setTemplate(base.getTemplate());
}
invoiceContext.getIssuer().putAll(base.getIssuer());
invoiceContext.getIssuer().putAll(individual.getIssuer());
invoiceContext.getReceiver().putAll(base.getReceiver());
invoiceContext.getReceiver().putAll(individual.getReceiver());
invoiceContext.getItems().addAll(base.getItems());
invoiceContext.getItems().addAll(individual.getItems());
return invoiceContext;
}
}
| 33.795455
| 80
| 0.64694
|
7c0ad7c217d1bf380e5cff6150f4d8ab552e9959
| 4,569
|
/*
* Copyright (C) 2014 singwhatiwanna(任玉刚) <singwhatiwanna@gmail.com>
*
* collaborator:田啸,宋思宇
*
* 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.ryg.dynamicload.internal;
import java.lang.reflect.Constructor;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import com.ryg.dynamicload.DLPlugin;
import com.ryg.utils.DLConstants;
public class DLProxyImpl {
private static final String TAG = "DLProxyImpl";
private String mClass;
private String mPackageName;
private DLPluginPackage mPluginPackage;
private DLPluginManager mPluginManager;
private AssetManager mAssetManager;
private Resources mResources;
private Theme mTheme;
private ActivityInfo mActivityInfo;
private Activity mActivity;
protected DLPlugin mRemoteActivity;
public DLProxyImpl(Activity activity) {
mActivity = activity;
}
private void initializeActivityInfo() {
PackageInfo packageInfo = mPluginPackage.packageInfo;
if ((packageInfo.activities != null) && (packageInfo.activities.length > 0)) {
if (mClass == null) {
mClass = packageInfo.activities[0].name;
}
for (ActivityInfo a : packageInfo.activities) {
if (a.name.equals(mClass)) {
mActivityInfo = a;
}
}
}
}
private void handleActivityInfo() {
Log.d(TAG, "handleActivityInfo, theme=" + mActivityInfo.theme);
if (mActivityInfo.theme > 0) {
mActivity.setTheme(mActivityInfo.theme);
}
Theme superTheme = mActivity.getTheme();
mTheme = mResources.newTheme();
mTheme.setTo(superTheme);
// TODO: handle mActivityInfo.launchMode here in the future.
}
public void onCreate(Intent intent) {
mPackageName = intent.getStringExtra(DLConstants.EXTRA_PACKAGE);
mClass = intent.getStringExtra(DLConstants.EXTRA_CLASS);
Log.d(TAG, "mClass=" + mClass + " mPackageName=" + mPackageName);
mPluginManager = DLPluginManager.getInstance(mActivity);
mPluginPackage = mPluginManager.getPackage(mPackageName);
mAssetManager = mPluginPackage.assetManager;
mResources = mPluginPackage.resources;
initializeActivityInfo();
handleActivityInfo();
launchTargetActivity();
}
// @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected void launchTargetActivity() {
try {
Class<?> localClass = getClassLoader().loadClass(mClass);
//构造一个类的实例
Constructor<?> localConstructor = localClass.getConstructor(new Class[] {});
Object instance = localConstructor.newInstance(new Object[] {});
mRemoteActivity = (DLPlugin) instance;
((DLProxy) mActivity).attach(mRemoteActivity, mPluginManager);
Log.d(TAG, "instance = " + instance);
mRemoteActivity.attach(mActivity, mPluginPackage);
Bundle bundle = new Bundle();
bundle.putInt(DLConstants.FROM, DLConstants.FROM_EXTERNAL);
mRemoteActivity.onCreate(bundle);
} catch (Exception e) {
e.printStackTrace();
}
}
public ClassLoader getClassLoader() {
return mPluginPackage.classLoader;
}
public AssetManager getAssets() {
return mAssetManager;
}
public Resources getResources() {
return mResources;
}
public Theme getTheme() {
return mTheme;
}
public DLPlugin getRemoteActivity() {
return mRemoteActivity;
}
public interface DLProxy {
public void attach(DLPlugin remoteActivity, DLPluginManager pluginManager);
}
}
| 31.510345
| 88
| 0.672576
|
1ee811224dbd5ab91555e66674f9f90024f8382f
| 2,456
|
package at.rseiler.spbee.demo.entity;
import at.rseiler.spbee.core.annotation.Entity;
import at.rseiler.spbee.core.annotation.MappingConstructor;
import at.rseiler.spbee.demo.McName;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
/**
* @author Reinhard Seiler {@literal <rseiler.developer@gmail.com>}
*/
@Entity
public class User {
private int id;
private String name;
private LocalDateTime created;
private List<Permission> permissions;
private User() {
}
@MappingConstructor
public User(int id, String name, Timestamp created) {
this(id, name, created, new ArrayList<>());
}
@MappingConstructor(McName.SIMPLE_USER)
public User(int id) {
this(id, "-", null, new ArrayList<>());
}
public User(int id, String name, Timestamp created, List<Permission> permissions) {
this.id = id;
this.name = name;
this.created = created != null ? created.toLocalDateTime().atZone(ZoneId.systemDefault()).toLocalDateTime() : null;
this.permissions = permissions;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public LocalDateTime getCreated() {
return created;
}
public List<Permission> getPermissions() {
return permissions;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", created=" + created +
", permissions=" + permissions +
'}';
}
public static class Builder {
private final User user;
public Builder() {
this.user = new User();
}
public Builder(User user) {
this.user = new User();
this.user.id = user.id;
this.user.name = user.name;
this.user.permissions = user.permissions;
}
public Builder id(int id) {
user.id = id;
return this;
}
public Builder name(String name) {
user.name = name;
return this;
}
public Builder permissions(List<Permission> permissions) {
user.permissions = permissions;
return this;
}
public User build() {
return user;
}
}
}
| 23.169811
| 123
| 0.569625
|
9d9a5f582df1da536f26a59dd36945b46bfefb2f
| 9,479
|
/**
*
* 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.yoko.rmi.impl;
import java.io.Externalizable;
import java.io.IOException;
import java.io.NotActiveException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.yoko.util.cmsf.CmsfThreadLocal;
import org.apache.yoko.util.yasf.Yasf;
import org.apache.yoko.util.yasf.YasfThreadLocal;
abstract class ObjectWriter extends ObjectOutputStream {
protected final Serializable object;
private ValueDescriptor _desc;
private PutFieldImpl _putFields;
private WriteObjectState state = WriteObjectState.NOT_IN_WRITE_OBJECT;
final byte cmsf;
final Set<Yasf> yasfSet;
private enum WriteObjectState {
NOT_IN_WRITE_OBJECT {
void beforeWriteObject(ObjectWriter writer) {
writer.state = IN_WRITE_OBJECT;
}
},
IN_WRITE_OBJECT {
void afterWriteObject(ObjectWriter writer) throws IOException {
writer.state = NOT_IN_WRITE_OBJECT;
// there is no custom (nor default) state written
writer.writeBoolean(false);
// If we're in stream format version 2, we must
// put the "null" marker to say that there isn't
// any optional data
if (writer.cmsf == 2) {
writer._nullValue();
}
}
void beforeDefaultWriteObject(ObjectWriter writer) throws IOException {
writer.state = IN_DEFAULT_WRITE_OBJECT;
writer.writeBoolean(true);
}
void beforeWriteData(ObjectWriter writer) throws IOException {
writer.state = WROTE_CUSTOM_DATA;
// writeDefaultObject was not invoked
writer.writeBoolean(false);
if (writer.cmsf == 2) {
writer._startValue(writer._desc.getCustomRepositoryID());
}
}
},
IN_DEFAULT_WRITE_OBJECT {
void afterDefaultWriteObject(ObjectWriter writer) {
writer.state = WROTE_DEFAULT_DATA;
}
},
WROTE_DEFAULT_DATA {
void afterWriteObject(ObjectWriter writer) throws IOException {
// the boolean identifying that default data was written has already
// been emitted in IN_WRITE_OBJECT.beforeWriteDefaultObject
writer.state = NOT_IN_WRITE_OBJECT;
// write a null-marker to identify that there is no custom
// state being marshalled...
if (writer.cmsf == 2) {
writer._nullValue();
}
}
void beforeWriteData(ObjectWriter writer) throws IOException {
// the boolean identifying that default data was written has already
// been emitted in IN_WRITE_OBJECT.beforeWriteDefaultObject
writer.state = WROTE_CUSTOM_DATA;
if (writer.cmsf == 2) {
writer._startValue(writer._desc.getCustomRepositoryID());
}
}
},
WROTE_CUSTOM_DATA {
void afterWriteObject(ObjectWriter writer) throws IOException {
if (writer.cmsf == 2) {
writer._endValue();
}
writer.state = NOT_IN_WRITE_OBJECT;
}
}
;
void beforeWriteObject(ObjectWriter writer) {
throw new IllegalStateException();
}
void afterWriteObject(ObjectWriter writer) throws IOException {
throw new IllegalStateException();
}
void beforeDefaultWriteObject(ObjectWriter writer) throws IOException {
throw new IllegalStateException();
}
void afterDefaultWriteObject(ObjectWriter writer) {
throw new IllegalStateException();
}
void beforeWriteData(ObjectWriter writer) throws IOException {
}
}
protected void beforeWriteData() throws IOException {
state.beforeWriteData(this);
}
ObjectWriter(Serializable obj) throws IOException {
object = obj;
cmsf = CmsfThreadLocal.get();
yasfSet = YasfThreadLocal.get();
}
abstract ObjectReader getObjectReader(Object newObject);
private void setCurrentValueDescriptor(ValueDescriptor desc) {
_desc = desc;
_putFields = null;
}
public final void defaultWriteObject() throws IOException {
if (_desc == null) {
throw new NotActiveException();
}
state.beforeDefaultWriteObject(this);
try {
_desc.defaultWriteValue(this, object);
} finally {
state.afterDefaultWriteObject(this);
}
}
public ObjectOutputStream.PutField putFields()
throws IOException {
if (_desc == null) {
throw new NotActiveException();
}
_putFields = new PutFieldImpl(_desc);
return _putFields;
}
public void writeFields() throws IOException {
if (_putFields == null) {
throw new NotActiveException("no current PutFields");
}
if (_putFields.slice != _desc) {
throw new NotActiveException(
"PutField cannot survive writeObject invocation");
}
state.beforeDefaultWriteObject(this);
try {
_putFields.write(this);
} finally {
state.afterDefaultWriteObject(this);
}
}
public void close() { /* skip */
}
public void flush() { /* skip */
}
public abstract void writeValueObject(Object obj) throws IOException;
public abstract void writeRemoteObject(Object obj) throws IOException;
public abstract void writeCorbaObject(Object obj) throws IOException;
public abstract void writeAny(Object obj) throws IOException;
static class PutFieldImpl extends PutField {
final ValueDescriptor slice;
final Map<String, Object> valueMap = new HashMap<>();
PutFieldImpl(ValueDescriptor slice) {
this.slice = slice;
}
@Override
public void put(String name, boolean val) {
valueMap.put(name, val);
}
@Override
public void put(String name, byte val) {
valueMap.put(name, val);
}
@Override
public void put(String name, char val) {
valueMap.put(name, val);
}
@Override
public void put(String name, double val) {
valueMap.put(name, val);
}
@Override
public void put(String name, float val) {
valueMap.put(name, val);
}
@Override
public void put(String name, int val) {
valueMap.put(name, val);
}
@Override
public void put(String name, long val) {
valueMap.put(name, val);
}
@Override
public void put(String name, Object val) {
valueMap.put(name, val);
}
@Override
public void put(String name, short val) {
valueMap.put(name, val);
}
@Override
public void write(ObjectOutput out) throws IOException {
slice.writeFields((ObjectWriter) out, valueMap);
}
}
void invokeWriteObject(ValueDescriptor descriptor, Serializable val,
Method _write_object_method) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, IOException {
final ValueDescriptor desc = _desc;
final WriteObjectState old_state = state;
state = WriteObjectState.NOT_IN_WRITE_OBJECT;
try {
setCurrentValueDescriptor(descriptor);
writeByte(cmsf);
state.beforeWriteObject(this);
_write_object_method.invoke(val, this);
state.afterWriteObject(this);
} finally {
state = old_state;
setCurrentValueDescriptor(desc);
}
}
protected abstract void _startValue(String rep_id) throws IOException;
protected abstract void _endValue() throws IOException;
protected abstract void _nullValue() throws IOException;
void invokeWriteExternal(Externalizable externalizable) throws IOException {
writeByte(cmsf);
externalizable.writeExternal(this);
}
}
| 30.876221
| 88
| 0.61114
|
1aa14d3da442a59d135f2ad9e96ef31deb92d8a4
| 1,432
|
package com.web.keywords.entity;
import com.app.base.entity.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 类别匹配关键字分类
*
*/
@Entity(name = "KeywordsCategory2")
@Table(name = KeywordsCategory2.TABLE_NAME)
@DynamicUpdate
@ApiModel
public class KeywordsCategory2 extends BaseEntity {
private static final long serialVersionUID = -3903342846561755250L;
public static final String TABLE_NAME = "t_keywords_category_2";
/**
* 分类名称
*/
@ApiModelProperty(name = "bsName", value = "分类名称")
@Column(length = 200)
public String bsName;
/**
* 备注
*/
@ApiModelProperty(name = "bsRemark", value = "备注")
@Column(length = 500)
public String bsRemark;
public String getBsName() {
return bsName;
}
public void setBsName(String bsName) {
this.bsName = bsName;
}
public String getBsRemark() {
return bsRemark;
}
public void setBsRemark(String bsRemark) {
this.bsRemark = bsRemark;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("分类名称:").append(this.bsName);
sb.append(",备注:").append(this.bsRemark);
return sb.toString();
}
}
| 23.096774
| 71
| 0.670391
|
8cb0ff9c00059ffc79e030bd6a1a421f1a6eacf7
| 7,243
|
package com.systematictesting.daolayer.beans;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.systematictesting.daolayer.entity.User;
public class License {
public static final String DELIMITER = ",";
public static final String EXPIRY_DATE_FORMAT = "dd/MM/yyyy";
public static final String NOT_APPLICABLE = "Not Applicable";
public static final String ENTERPRISE = "Enterprise";
public static final String STANDARD = "Standard";
public static final String FEATURE_KEY = "feature";
private static final Logger logger = LoggerFactory.getLogger(License.class);
private static final String SEPARATOR = "=";
private static final String HMAC_DELIMITER = "~";
private static final String CRYPTO_ALOG = "HmacMD5";
private static final byte[] key_bytes = new byte[] { -10,-95,-120,58,-54,34,98,-34,-42,-2,100,-87};
private String licenseKey;
private Long expiryDate;
private List<String> featureList = new ArrayList<String>();
private String expiryDateString;
public interface FIELDS {
String LICENSE_KEY = "licenseKey";
String EXPIRY_DATE_STRING = "expiryDateString";
String EXPIRY_DATE = "expiryDate";
String FEATURE_LIST = "featureList";
}
public String getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(String licenseKey) {
this.licenseKey = licenseKey;
}
public Long getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Long expiryDate) {
this.expiryDate = expiryDate;
}
public List<String> getFeatureList() {
return featureList;
}
public String getExpiryDateString() {
return expiryDateString;
}
public void setExpiryDateString(String expiryDateString) {
this.expiryDateString = expiryDateString;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((expiryDate == null) ? 0 : expiryDate.hashCode());
result = prime * result + ((expiryDateString == null) ? 0 : expiryDateString.hashCode());
result = prime * result + ((featureList == null) ? 0 : featureList.hashCode());
result = prime * result + ((licenseKey == null) ? 0 : licenseKey.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
License other = (License) obj;
if (expiryDate == null) {
if (other.expiryDate != null)
return false;
} else if (!expiryDate.equals(other.expiryDate))
return false;
if (expiryDateString == null) {
if (other.expiryDateString != null)
return false;
} else if (!expiryDateString.equals(other.expiryDateString))
return false;
if (featureList == null) {
if (other.featureList != null)
return false;
} else if (!featureList.equals(other.featureList))
return false;
if (licenseKey == null) {
if (other.licenseKey != null)
return false;
} else if (!licenseKey.equals(other.licenseKey))
return false;
return true;
}
@Override
public String toString() {
return "License [licenseKey=" + licenseKey + ", expiryDate=" + expiryDate + ", featureList=" + featureList
+ ", expiryDateString=" + expiryDateString + "]";
}
public boolean validateLicense(String email){
logger.debug("VALIDATING LICENSE KEY : "+this.licenseKey);
boolean result = false;
StringBuilder hash_source = new StringBuilder();
hash_source.append(FIELDS.EXPIRY_DATE).append(SEPARATOR).append(this.expiryDate).append(HMAC_DELIMITER);
hash_source.append(User.FIELDS.EMAIL).append(SEPARATOR).append(email.toLowerCase().trim()).append(HMAC_DELIMITER);
hash_source.append(FIELDS.FEATURE_LIST).append(SEPARATOR);
for (String feature : featureList){
hash_source.append(feature.trim()).append(DELIMITER);
}
hash_source.append(HMAC_DELIMITER);
try {
Mac hmac = Mac.getInstance(CRYPTO_ALOG);
SecretKeySpec secret_key = new SecretKeySpec(key_bytes, CRYPTO_ALOG);
hmac.init(secret_key);
byte[] hmac_bytes = hmac.doFinal(hash_source.substring(0, hash_source.length() - 1).toString().getBytes());
String token = String.format("%0" + (2 * hmac.getMacLength()) + "x", new BigInteger(1, hmac_bytes));
if (token.equals(licenseKey)){
logger.info("LICENSE KEY : "+this.licenseKey+" : is 100% valid.");
result=true;
} else {
logger.warn("LICENSE KEY : "+this.licenseKey+" : is not valid.");
logger.debug("LICENSE TOKEN : "+token);
logger.warn("Here are some more details : \nLICENSE KEY : "+this.licenseKey+"\nFEATURE LIST="+this.featureList+"\nEMAIL="+email.toLowerCase().trim()+"\nEXPIRY_DATE_STRING="+this.expiryDateString+"\nEXPIRY_DATE="+this.expiryDate);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new IllegalArgumentException("No such algorithm detected.");
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new IllegalArgumentException("Invalid Key Detected");
}
return result;
}
private static String generateLicense(String features, String email, String dateOfExpiry) {
try {
DateFormat format = new SimpleDateFormat(License.EXPIRY_DATE_FORMAT);
Date expiryDate = format.parse(dateOfExpiry);
StringBuilder hash_source = new StringBuilder();
hash_source.append(FIELDS.EXPIRY_DATE).append(SEPARATOR).append(expiryDate.getTime()).append(HMAC_DELIMITER);
hash_source.append(User.FIELDS.EMAIL).append(SEPARATOR).append(email).append(HMAC_DELIMITER);
hash_source.append(FIELDS.FEATURE_LIST).append(SEPARATOR);
String[] featureList = features.split(DELIMITER);
for (String feature : featureList) {
hash_source.append(feature.trim()).append(DELIMITER);
}
hash_source.append(HMAC_DELIMITER);
Mac hmac = Mac.getInstance(CRYPTO_ALOG);
SecretKeySpec secret_key = new SecretKeySpec(key_bytes, CRYPTO_ALOG);
hmac.init(secret_key);
byte[] hmac_bytes = hmac.doFinal(hash_source.substring(0, hash_source.length() - 1).toString().getBytes());
String token = String.format("%0" + (2 * hmac.getMacLength()) + "x", new BigInteger(1, hmac_bytes));
return token;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new IllegalArgumentException("No such algorithm detected.");
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new IllegalArgumentException("Invalid Key Detected");
} catch (ParseException e) {
e.printStackTrace();
throw new IllegalArgumentException("Expiry Date can't be parsed.");
}
}
public static void main(String[] args) {
Feature feature = new Feature();
String features = feature.getAutomationCoverage()+DELIMITER+feature.getMoreVersionHistory()+DELIMITER+feature.getSiteManager();
String email = "sharad.kumar@shell.com";
String dateOfExpiry = "01/01/2016";
System.out.println("FEATURE LIST = "+features);
System.out.println("LICENSE KEY = "+generateLicense(features, email, dateOfExpiry));
}
}
| 36.766497
| 233
| 0.727185
|
ded366d43b7f62a9b1866fec19a3f2c5ba9c2a58
| 748
|
package io.fabric8.kubernetes.api;
import io.fabric8.kubernetes.api.model.Pod;
import org.eclipse.jetty.websocket.client.WebSocketClient;
public class WatchPodsExample {
public static void main(String... args) throws Exception {
KubernetesClient kube = new KubernetesClient();
System.out.println("Connecting to kubernetes on: " + kube.getAddress());
WebSocketClient client = kube.watchPods("default", null, new ExampleWatcher());
Thread.sleep(10000l);
client.stop();
}
static class ExampleWatcher extends AbstractWatcher<Pod> {
@Override
public void eventReceived(Watcher.Action action, Pod object) {
System.out.println(action + ": " + object);
}
}
}
| 31.166667
| 87
| 0.677807
|
9cf17ba9929f4cf26ccc63b37726b75b19dc6f74
| 1,332
|
package com.couchbase.litecore;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class C4PathsQueryTest extends C4QueryBaseTest {
C4Query query = null;
//-------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------
@Override
public void setUp() throws Exception {
super.setUp();
importJSONLines("paths.json");
}
@Override
public void tearDown() throws Exception {
if (query != null) {
query.free();
query = null;
}
super.tearDown();
}
// - DB Query ANY w/paths
@Test
public void testDBQueryANYwPaths() throws LiteCoreException {
// For https://github.com/couchbase/couchbase-lite-core/issues/238
compile(json5("['ANY','path',['.paths'],['=',['?path','city'],'San Jose']]"));
assertEquals(Arrays.asList("0000001"), run());
compile(json5("['ANY','path',['.paths'],['=',['?path.city'],'San Jose']]"));
assertEquals(Arrays.asList("0000001"), run());
compile(json5("['ANY','path',['.paths'],['=',['?path','city'],'Palo Alto']]"));
assertEquals(Arrays.asList("0000001", "0000002"), run());
}
}
| 29.6
| 87
| 0.516517
|
4d4174cfd5a2a9e8d6209b85223e1f8e1b12de39
| 429
|
package TheoryDA;
import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); System.out.println("Enter your weight in kg: ");
float weight = s.nextFloat();
System.out.println("Enter your height in cm: "); float height = s.nextInt();
float heightInMeters = height/100;
float bmi = weight/(heightInMeters*heightInMeters); System.out.println("Your BMI is: " + bmi);
} }
| 42.9
| 94
| 0.731935
|
9cd0d001a9a99eeaae21b597ad3a44fd3d160f5e
| 4,475
|
package com.daniel366cobra.impenitent_illagers.world.gen.feature;
import com.daniel366cobra.impenitent_illagers.structure.PillagerFortGenerator;
import com.mojang.serialization.Codec;
import net.minecraft.block.BlockState;
import net.minecraft.structure.StructureGeneratorFactory;
import net.minecraft.structure.StructurePiecesCollector;
import net.minecraft.structure.StructurePiecesGenerator;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.Heightmap;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.StructureConfig;
import net.minecraft.world.gen.chunk.VerticalBlockSample;
import net.minecraft.world.gen.feature.DefaultFeatureConfig;
import net.minecraft.world.gen.feature.StructureFeature;
import net.minecraft.world.gen.random.AtomicSimpleRandom;
import net.minecraft.world.gen.random.ChunkRandom;
public class PillagerFortFeature extends StructureFeature<DefaultFeatureConfig> {
public PillagerFortFeature(Codec<DefaultFeatureConfig> configCodec) {
super(configCodec, StructureGeneratorFactory.simple(PillagerFortFeature::isFeatureChunk, PillagerFortFeature::addPieces));
}
private static void addPieces(StructurePiecesCollector collector, StructurePiecesGenerator.Context<DefaultFeatureConfig> context) {
BlockRotation blockRotation = BlockRotation.random(context.random());
BlockPos spawnXZPos = context.chunkPos().getCenterAtY(0);
BlockPos spawnPosHeightCorrected = new BlockPos(context.chunkPos().getStartX(),
context.chunkGenerator().getHeightInGround(spawnXZPos.getX(), spawnXZPos.getZ(), Heightmap.Type.WORLD_SURFACE_WG, context.world()),
context.chunkPos().getStartZ());
PillagerFortGenerator.addPieces(context.structureManager(), spawnPosHeightCorrected, blockRotation, collector, context.random(), context.config());
}
private static boolean isFeatureChunk(StructureGeneratorFactory.Context<DefaultFeatureConfig> context) {
int i = context.chunkPos().x >> 4;
int j = context.chunkPos().z >> 4;
ChunkRandom chunkRandom = new ChunkRandom(new AtomicSimpleRandom(0L));
chunkRandom.setSeed((long)(i ^ j << 4) ^ context.seed());
chunkRandom.nextInt();
if (chunkRandom.nextInt(5) != 0) {
return false;
}
BlockPos spawnXZPos = context.chunkPos().getCenterAtY(0);
int landHeight = context.chunkGenerator().getHeightInGround(spawnXZPos.getX(), spawnXZPos.getZ(), Heightmap.Type.WORLD_SURFACE_WG, context.world());
VerticalBlockSample chunkCenterBlockColumn = context.chunkGenerator().getColumnSample(spawnXZPos.getX(), spawnXZPos.getZ(), context.world());
BlockState topBlockState = chunkCenterBlockColumn.getState(landHeight);
return topBlockState.getFluidState().isEmpty() && !isVillageOrOutpostNearby(context.chunkGenerator(), context.seed(), context.chunkPos());
}
private static boolean isVillageOrOutpostNearby(ChunkGenerator chunkGenerator, long seed, ChunkPos chunkPos) {
StructureConfig villageStructureConfig = chunkGenerator.getStructuresConfig().getForType(StructureFeature.VILLAGE);
StructureConfig outpostStructureConfig = chunkGenerator.getStructuresConfig().getForType(StructureFeature.PILLAGER_OUTPOST);
if (villageStructureConfig == null) {
return false;
} else if (outpostStructureConfig == null) {
return false;
} else {
int currentX = chunkPos.x;
int currentZ = chunkPos.z;
for (int iterX = currentX - 10; iterX < currentX + 10; iterX++) {
for (int iterZ = currentZ - 10; iterZ < currentZ + 10; iterZ++) {
ChunkPos villageStartChunk = StructureFeature.VILLAGE.getStartChunk(villageStructureConfig, seed, iterX, iterZ);
ChunkPos outpostStartChunk = StructureFeature.PILLAGER_OUTPOST.getStartChunk(outpostStructureConfig, seed, iterX, iterZ);
boolean isVillageStartChunk = (iterX == villageStartChunk.x && iterZ == villageStartChunk.z);
boolean isOutpostStartChunk = (iterX == outpostStartChunk.x && iterZ == outpostStartChunk.z);
if (isVillageStartChunk || isOutpostStartChunk) return true;
}
}
}
return false;
}
}
| 52.034884
| 156
| 0.730503
|
a537d683c3be52996cb153da8214e7368d17dbb5
| 2,666
|
import java.util.Date;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* Connection class
* @descrip Connection class to be used as a pipe between router threads.
* @author Benjamin Russell (brr1922)
*/
public class Connection extends LinkedList<RoutingTable> {
// MEMBER VARIABLES ////////////////////////////////////////////////////
/**
* The link speed for the link (aka the metric)
*/
private final int linkCost;
/**
* Whether or not the link is down
*/
private boolean down = false;
private int downProbability;
private int check = 0;
// CONSTRUCTORS ////////////////////////////////////////////////////////
public Connection(int linkCost, boolean canGoDown) {
// Set the link speed
this.linkCost = linkCost;
downProbability = (canGoDown) ? 2 : -1;
}
// METHODS /////////////////////////////////////////////////////////////
/**
* Receives whatever is at the head of the pipe
* @return A routing table, if there is one, null otherwise
* @throws NullPointerException Thrown if the link is down
*/
public RoutingTable receive() throws NullPointerException {
// Verify that the link is up before returning something
if(down) {
throw new NullPointerException("Link is down!");
}
// Will we go down?
Random r = new Random();
if(check >= 100) {
if(r.nextInt(100) <= downProbability) {
// OH NO! we're going down!
down = true;
check = 0;
throw new NullPointerException("Link is down!");
} else {
// Link is back up
down = false;
check = 0;
}
}
// Update when we next check
check++;
// Return whatever is at the head of the list, or nothing
try {
return (super.size() > 0) ? super.removeFirst() : null;
} catch(NoSuchElementException e) {
return null;
}
}
/**
* Adds the given routing table to the list pipe
* @param r The routing table to send
* @throws NullPointerException Thrown if the link is down
*/
public void send(RoutingTable r) throws NullPointerException {
if(down) {
throw new NullPointerException("Link is Down!");
}
super.add(r);
}
// GETTERS/SETTERS /////////////////////////////////////////////////////
/**
* @return The link speed
*/
public int getLinkCost() { return linkCost; }
}
| 28.063158
| 76
| 0.522881
|
e1472f9c6f0b48095e231e090daa0d1c130cfa27
| 10,767
|
package xyz.dowenliu.study.algo._07_linked_list;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Objects;
/**
* {@code int} 循环单链表
* <p>create at 2019/11/27</p>
*
* @author liufl
* @since version 1.0
*/
public class IntCircularSinglyLinkedList implements IntLinkedList {
/**
* 链表节点
*/
public static class Node implements IntLinkedList.Node {
private int value;
@NotNull
private Node next; // 在循环链表中,next始终不为null
/**
* 构建头节点
*
* @param value 节点存储的值
*/
private Node(int value) {
this.value = value;
this.next = this;
}
/**
* 构建节点
*
* @param value 节点存储的值
* @param next 后续节点。不允许为 {@code null}
* @throws NullPointerException 后续节点为空
*/
private Node(int value, @NotNull Node next) {
this.value = value;
this.next = Objects.requireNonNull(next);
}
@Override
public int getValue() {
return this.value;
}
@Override
@NotNull
public Node getNext() {
return this.next;
}
}
/**
* 内部使用的游标
*/
private static class Cursor {
@Nullable
final Node previous;
@Nullable
final Node node;
@Nullable
final Node next;
final int position;
public Cursor(@Nullable Node previous, @Nullable Node node,
@Nullable Node next, int position) {
this.previous = previous;
this.node = node;
this.next = next;
this.position = position;
}
@Nullable
public Cursor next() {
if (this.node == null) {
return null;
}
return new Cursor(this.node, this.node.next,
this.next == null ? null : this.next.next,
this.position + 1);
}
}
@Nullable
private Node head;
@Nullable
private Node tail;
private int size;
@Override
public int size() {
return this.size;
}
@Override
public @Nullable Node getFirstNode() {
return this.head;
}
private void checkAccessIndex(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
}
private void checkInsertIndex(int index) {
if (index < 0 || index > this.size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
}
private String outOfBoundsMsg(int index) {
return "Index: " + index + ", Size: " + this.size;
}
/**
* 获取索引位置的游标
*
* @param index 索引
* @return 如果 {@code index} 小于 {@code 0} 或者
* {@code index} 大于等于 {@link #size()} ,返回 {@code null} ;
* 否则,返回索引位置的游标
*/
@SuppressWarnings("DuplicatedCode")
@Nullable
private Cursor cursorAt(int index) {
if (index < 0 || index > this.size) {
return null;
}
if (index == this.size) {
return new Cursor(
this.tail,
this.head,
this.head == null ? null : this.head.next,
this.size
);
}
Cursor cursor = new Cursor(
this.tail,
this.head,
this.head == null ? null : this.head.next,
0
);
while (cursor != null && cursor.position != index) {
cursor = cursor.next();
}
return cursor;
}
@SuppressWarnings("DuplicatedCode")
@Override
@NotNull
public Node getNode(int index) throws IndexOutOfBoundsException {
this.checkAccessIndex(index);
assert this.size != 0 && this.head != null && this.tail != null :
"index 已通过检查,则 size 至少为 1 ,头尾节点不为空";
Cursor cursor = this.cursorAt(index);
assert cursor != null : "index 已通过检查,游标不可能是 null";
Node node = cursor.node;
assert node != null : "index 已通过检查,节点不可能是 null";
return node;
}
@Nullable
private Cursor find(@Nullable Cursor cursor, int value) {
while (cursor != null && cursor.node != null &&
cursor.position < this.size) {
if (cursor.node.value == value) {
return cursor;
}
cursor = cursor.next();
}
return null;
}
@Override
@Nullable
public Node nodeOfValue(int value) {
Cursor cursor = this.find(this.cursorAt(0), value);
return cursor == null ? null : cursor.node;
}
@Override
public int set(int index, int value) throws IndexOutOfBoundsException {
Node node = this.getNode(index);
int origin = node.value;
node.value = value;
return origin;
}
@SuppressWarnings("DuplicatedCode")
@Override
public void addBefore(int index, int value)
throws IndexOutOfBoundsException {
this.checkInsertIndex(index);
if (this.isEmpty()) {
this.tail = this.head = new Node(value);
this.size++;
return;
}
Cursor cursor = this.cursorAt(index);
assert cursor != null : "链表非空,index 合法,游标必定不是 null";
Node next = cursor.node;
Node previous = cursor.previous;
assert previous != null && next != null :
"循环链表非空,各节点不可能是 null";
Node node = new Node(value, next);
previous.next = node;
if (index == 0) {
this.head = node;
}
if (index == this.size) {
this.tail = node;
}
this.size++;
}
@SuppressWarnings("DuplicatedCode")
@Override
public void addAfter(int index, int value)
throws IndexOutOfBoundsException {
this.checkAccessIndex(index);
if (index == this.size - 1) {
assert this.head != null : "index检查已通过,链表非空," +
"头节点不可能为 null";
Node node = new Node(value, this.head);
assert this.tail != null : "索引指向尾节点,尾节点不应为 null";
this.tail.next = node;
this.tail = node;
this.size++;
return;
}
Cursor cursor = this.cursorAt(index);
assert cursor != null : "index检查已通过,链表必定不为空,游标不可能为 null";
Node previous = cursor.node;
assert previous != null : "index检查已通过,节点不可能为 null";
previous.next = new Node(value, previous.next);
this.size++;
}
@SuppressWarnings("DuplicatedCode")
@Nullable
private Node removeByCursor(@NotNull Cursor cursor) {
Node node = cursor.node;
if (node == null) {
return null; // nothing to remove here
}
Node previous = cursor.previous;
Node next = cursor.next;
assert previous != null && next != null :
"当前节点不是 null,那么前后节点也不会是 null";
if (this.size == 1 && cursor.position == 0) {
// 只有一个节点
this.tail = this.head = null;
} else {
previous.next = next;
if (cursor.position == 0) {
this.head = next;
}
if (cursor.position == this.size - 1) {
this.tail = previous;
}
}
//noinspection ConstantConditions
node.next = null; // help GC
this.size--;
return node;
}
@SuppressWarnings("DuplicatedCode")
@Override
public int remove(int index) throws IndexOutOfBoundsException {
this.checkAccessIndex(index);
Cursor cursor = this.cursorAt(index);
assert cursor != null : "index检查已通过,游标不可能是 null";
Node removed = this.removeByCursor(cursor);
assert removed != null : "index检查已通过,要删除的节点不可能是 null";
return removed.value;
}
@Override
public boolean removeBy(int value) {
Cursor cursor = this.find(this.cursorAt(0), value);
if (cursor == null) {
return false;
}
Node removed = this.removeByCursor(cursor);
return removed != null;
}
@Override
public int indexOf(int value) {
Cursor cursor = this.find(this.cursorAt(0), value);
if (cursor == null) {
return -1;
}
return cursor.position;
}
@SuppressWarnings("DuplicatedCode")
@Override
public int lastIndexOf(int value) {
Cursor cursor = this.cursorAt(0);
int lastPosition = -1;
while (cursor != null) {
cursor = this.find(cursor, value);
if (cursor != null) {
lastPosition = cursor.position;
cursor = cursor.next();
}
}
return lastPosition;
}
@SuppressWarnings("DuplicatedCode")
@Override
public void reverse() {
if (this.isEmpty()) {
return;
}
Node previous = this.tail;
Node node = this.head;
assert node != null && previous != null :
"链表不为空,头尾节点不可能是 null";
Node next = node.next;
int position = 0;
while (position < this.size) {
node.next = previous;
previous = node;
node = next;
if (next != this.head) {
next = next.next;
}
position++;
}
Node temp = this.head;
this.head = previous;
this.tail = temp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IntList)) return false;
IntList that = (IntList) o;
return Arrays.equals(this.toArray(), that.toArray());
}
@Override
public int hashCode() {
return Arrays.hashCode(this.toArray());
}
@SuppressWarnings("DuplicatedCode")
@Override
public IntList clone() {
IntCircularSinglyLinkedList clone;
try {
clone = (IntCircularSinglyLinkedList) super.clone();
clone.head = null;
clone.tail = null;
clone.size = 0;
} catch (CloneNotSupportedException e) {
throw new InternalError(); // should not happen
}
Node cursor = this.head;
int position = 0;
while (cursor != null && position < this.size) {
clone.addTail(cursor.value);
cursor = cursor.next;
position++;
}
return clone;
}
@Override
public String toString() {
return "IntCircularSinglyLinkedList" + Arrays.toString(this.toArray());
}
}
| 27.821705
| 79
| 0.526516
|
3d6298ce194afc2fc81c4ee81102778d29e05488
| 3,436
|
package gnu.kawa.functions;
import gnu.expr.Language;
import gnu.lists.FVector;
import gnu.lists.LList;
import gnu.lists.Pair;
import gnu.mapping.Procedure2;
public class IsEqual extends Procedure2 {
Language language;
public IsEqual(Language language2, String name) {
this.language = language2;
setName(name);
}
public static boolean numberEquals(Number num1, Number num2) {
boolean exact1 = Arithmetic.isExact(num1);
boolean exact2 = Arithmetic.isExact(num2);
if (!exact1 || !exact2) {
return exact1 == exact2 && num1.equals(num2);
}
return NumberCompare.$Eq(num1, num2);
}
/* JADX WARNING: Code restructure failed: missing block: B:92:?, code lost:
return apply(r14, r15);
*/
public static boolean apply(Object arg1, Object arg2) {
if (arg1 == arg2) {
return true;
}
if (arg1 == null || arg2 == null) {
return false;
}
if ((arg1 instanceof Number) && (arg2 instanceof Number)) {
return numberEquals((Number) arg1, (Number) arg2);
}
if (arg1 instanceof CharSequence) {
if (!(arg2 instanceof CharSequence)) {
return false;
}
CharSequence seq1 = (CharSequence) arg1;
CharSequence seq2 = (CharSequence) arg2;
int len1 = seq1.length();
if (len1 != seq2.length()) {
return false;
}
int i = len1;
do {
i--;
if (i < 0) {
return true;
}
} while (seq1.charAt(i) == seq2.charAt(i));
return false;
} else if (arg1 instanceof FVector) {
if (!(arg2 instanceof FVector)) {
return false;
}
FVector vec1 = (FVector) arg1;
FVector vec2 = (FVector) arg2;
int n = vec1.size;
if (vec2.data == null || vec2.size != n) {
return false;
}
Object[] data1 = vec1.data;
Object[] data2 = vec2.data;
int i2 = n;
do {
i2--;
if (i2 < 0) {
return true;
}
} while (apply(data1[i2], data2[i2]));
return false;
} else if (!(arg1 instanceof LList)) {
return arg1.equals(arg2);
} else {
if (!(arg1 instanceof Pair) || !(arg2 instanceof Pair)) {
return false;
}
Pair pair1 = (Pair) arg1;
Object obj = arg2;
while (true) {
Pair pair2 = (Pair) obj;
if (!apply(pair1.getCar(), pair2.getCar())) {
return false;
}
Object x1 = pair1.getCdr();
Object x2 = pair2.getCdr();
if (x1 == x2) {
return true;
}
if (x1 != null && x2 != null) {
if ((x1 instanceof Pair) && (x2 instanceof Pair)) {
pair1 = (Pair) x1;
obj = x2;
}
}
}
return false;
}
}
public Object apply2(Object arg1, Object arg2) {
return this.language.booleanObject(apply(arg1, arg2));
}
}
| 31.236364
| 79
| 0.460128
|
b1a247546342fdc362c8f9b5e9d424dd1a314089
| 1,108
|
/*
* Created on Apr 11, 2005
*
* Copyright (c) 2005, the JUNG Project and the Regents of the University
* of California
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* http://jung.sourceforge.net/license.txt for a description.
*/
package edu.uci.ics.jung.visualization.picking;
import edu.uci.ics.jung.algorithms.layout.GraphElementAccessor;
/**
* <code>PickSupport</code> implementation that emulates the picking behavior
* of versions of <code>VisualizationViewer</code> prior to version 1.6.
* (<code>VisualizationViewer</code> still has this behavior by default, but
* the picking behavior can now be changed.)
*
* @see ShapePickSupport
*
* @author Tom Nelson
* @author Joshua O'Madadhain
*/
public class ClassicPickSupport<V,E> extends RadiusPickSupport<V,E> implements GraphElementAccessor<V,E> {
public ClassicPickSupport()
{
super();
}
/**
* @return null ClassicPickSupport does not do edges
*/
public E getEdge(double x, double y) {
return null;
}
}
| 27.02439
| 106
| 0.696751
|
7ac23aa0d6a0e091b6b9ac6f3dde493e6a412c00
| 3,679
|
/*
*
* * Copyright (c) [2019-2021] [NorthLan](lan6995@gmail.com)
* *
* * 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.lan.iti.cloud.autoconfigure.gateway;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lan.iti.common.core.api.ApiResult;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import springfox.documentation.spring.web.OnReactiveWebApplication;
/**
* 网关全局异常处理器,仅作用于webflux下
* <p>
* 优先级低于{@link org.springframework.web.server.handler.ResponseStatusExceptionHandler}
*
* @author NorthLan
* @date 2020-07-02
* @url https://noahlan.com
*/
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@Conditional(OnReactiveWebApplication.class)
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {
private final ObjectMapper objectMapper;
@NonNull
@Override
public Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
if (response.isCommitted()) {
return Mono.error(ex);
}
// header set
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if (ex instanceof ResponseStatusException) {
response.setStatusCode(((ResponseStatusException) ex).getStatus());
}
return response.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = response.bufferFactory();
String rawStatusCode = String.valueOf(response.getRawStatusCode());
if (rawStatusCode == null) {
rawStatusCode = String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
String errorCode = rawStatusCode;
String msg = ex.getMessage();
if (ex instanceof ResponseStatusException) {
msg = ((ResponseStatusException) ex).getReason();
}
try {
return bufferFactory.wrap(objectMapper.writeValueAsBytes(ApiResult.error(errorCode, msg)));
} catch (JsonProcessingException e) {
log.warn("Error writing response", ex);
return bufferFactory.wrap(new byte[0]);
}
}));
}
}
| 39.55914
| 107
| 0.723023
|
f64c6fa7c3503237e0f2e099c6728abed200b71d
| 2,377
|
package com.mfg.Entity;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
/**
* Created by I309908 on 1/18/2017.
*/
@Entity
public class FunctionalQuality {
@Id
@GeneratedValue
private Long id;
@Column(nullable = true)
private String createdBy;
@Column(nullable = false)
private Timestamp createdTime;
@Column(nullable = false)
private String type;
@ManyToOne(cascade=CascadeType.MERGE)
@JoinColumn(name = "version_id")
private Version version;
@Column(nullable = true)
private int count1;
@Column(nullable = true)
private int count2;
@Column(nullable = true)
private float coverage;
@ManyToOne(cascade=CascadeType.MERGE)
@JoinColumn(name = "jenkinsJob_id")
private JenkinsJob jenkinsJob;
public FunctionalQuality() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Timestamp createdTime) {
this.createdTime = createdTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public int getCount2() {
return count2;
}
public void setCount2(int count2) {
this.count2 = count2;
}
public float getCoverage() {
return coverage;
}
public void setCoverage(float coverage) {
this.coverage = coverage;
}
@PrePersist
protected void onPersist(){
this.createdTime = now();
}
protected static Timestamp now(){
return new Timestamp(new Date().getTime());
}
public JenkinsJob getJenkinsJob() {
return jenkinsJob;
}
public void setJenkinsJob(JenkinsJob jenkinsJob) {
this.jenkinsJob = jenkinsJob;
}
}
| 18.570313
| 55
| 0.615902
|
ee8e2a4a794627937bc5cf3e9c3911cdb71da646
| 4,290
|
/*
* Copyright (c) 2017 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thjolin.download.task.speed;
import android.os.SystemClock;
import java.util.Locale;
public class SpeedAssist {
long timestamp;
long increaseBytes;
long bytesPerSecond;
long beginTimestamp;
long endTimestamp;
long allIncreaseBytes;
public synchronized void reset() {
timestamp = 0;
increaseBytes = 0;
bytesPerSecond = 0;
beginTimestamp = 0;
endTimestamp = 0;
allIncreaseBytes = 0;
}
long nowMillis() {
return SystemClock.uptimeMillis();
}
public synchronized void uu_downloading(long increaseBytes) {
if (timestamp == 0) {
this.timestamp = nowMillis();
this.beginTimestamp = timestamp;
}
this.increaseBytes += increaseBytes;
this.allIncreaseBytes += increaseBytes;
}
public synchronized void flush() {
final long nowMillis = nowMillis();
final long sinceNowIncreaseBytes = increaseBytes;
final long durationMillis = Math.max(1, nowMillis - timestamp);
increaseBytes = 0;
timestamp = nowMillis;
bytesPerSecond = (long) ((float) sinceNowIncreaseBytes / durationMillis * 1000f);
}
/**
* Get instant bytes per-second.
*/
public long getInstantBytesPerSecondAndFlush() {
flush();
return bytesPerSecond;
}
public synchronized long getBytesPerSecondAndFlush() {
final long interval = nowMillis() - timestamp;
if (interval < 1000 && bytesPerSecond != 0) return bytesPerSecond;
if (bytesPerSecond == 0 && interval < 500) return 0;
return getInstantBytesPerSecondAndFlush();
}
public synchronized long getBytesPerSecondFromBegin() {
final long endTimestamp = this.endTimestamp == 0 ? nowMillis() : this.endTimestamp;
final long sinceNowIncreaseBytes = allIncreaseBytes;
final long durationMillis = Math.max(1, endTimestamp - beginTimestamp);
// precision loss
return (long) ((float) sinceNowIncreaseBytes / durationMillis * 1000f);
}
public synchronized void endTask() {
endTimestamp = nowMillis();
}
public String instantSpeed() {
return getSpeedWithSIAndFlush();
}
public String speed() {
return humanReadableSpeed(getBytesPerSecondAndFlush(), true);
}
public String lastSpeed() {
return humanReadableSpeed(bytesPerSecond, true);
}
public synchronized long getInstantSpeedDurationMillis() {
return nowMillis() - timestamp;
}
public String getSpeedWithBinaryAndFlush() {
return humanReadableSpeed(getInstantBytesPerSecondAndFlush(), false);
}
/**
* With wikipedia: https://en.wikipedia.org/wiki/Kilobyte
* <p>
* 1KB = 1000B
* 1MB = 1000KB
*/
public String getSpeedWithSIAndFlush() {
return humanReadableSpeed(getInstantBytesPerSecondAndFlush(), true);
}
public String averageSpeed() {
return speedFromBegin();
}
public String speedFromBegin() {
return humanReadableSpeed(getBytesPerSecondFromBegin(), true);
}
private static String humanReadableSpeed(long bytes, boolean si) {
return humanReadableBytes(bytes, si) + "/s";
}
private static String humanReadableBytes(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format(Locale.ENGLISH, "%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
| 28.986486
| 91
| 0.650583
|
5a21b018825e8ca56943ccd66ad885333eae1ed3
| 1,723
|
package section1_recipe5;
import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyScheduledTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V> {
private RunnableScheduledFuture<V> task;
private ScheduledThreadPoolExecutor executor;
private long period;
private long startDate;
public MyScheduledTask(Runnable runnable, V result, RunnableScheduledFuture<V> task, ScheduledThreadPoolExecutor executor) {
super(runnable, result);
this.task=task;
this.executor=executor;
}
@Override
public long getDelay(TimeUnit unit) {
if (!isPeriodic()) {
return task.getDelay(unit);
} else {
if (startDate==0){
return task.getDelay(unit);
} else {
Date now=new Date();
long delay=startDate-now.getTime();
return unit.convert(delay, TimeUnit.MILLISECONDS);
}
}
}
@Override
public int compareTo(Delayed o) {
return task.compareTo(o);
}
@Override
public boolean isPeriodic() {
return task.isPeriodic();
}
@Override
public void run() {
if (isPeriodic() && (!executor.isShutdown())) {
Date now=new Date();
startDate=now.getTime()+period;
executor.getQueue().add(this);
}
System.out.printf("Pre-MyScheduledTask: %s\n",new Date());
System.out.printf("MyScheduledTask: Is Periodic: %s\n",isPeriodic());
super.runAndReset();
System.out.printf("Post-MyScheduledTask: %s\n",new Date());
}
public void setPeriod(long period) {
this.period=period;
}
}
| 24.971014
| 126
| 0.69704
|
d8a542a16aa962b83d1e8b5a6eaf03b4fc00f125
| 1,910
|
package pl.kz.youtube;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class YouTubeFileDownloadedValidator {
public static void main(String[] args) throws IOException {
final YoutubeInputProperties input = new YoutubeInputProperties(args).getProperties();
final Set<String> youtubeVideos = YoutubeFileTransformer.createYoutubeVideoUrlsSetFromFile(input.getFilePath());
long start = System.currentTimeMillis();
final List<Path> videoPaths = Files.walk(Paths.get("P:\\youtube-dl-download\\"))
.filter(Files::isRegularFile)
.filter(path -> !path.endsWith(".part"))
.collect(Collectors.toList());
long end = System.currentTimeMillis();
System.out.println("File walks takes: " + (end - start) + " ms");
videoPaths.forEach(System.out::println);
System.out.println(videoPaths.size());
youtubeVideos.forEach(videoUrl -> {
YoutubeProcessHandler processHandler = new YoutubeProcessHandler();
String videoName = processHandler.getVideoName(videoUrl);
videoName = videoName.replace(":", " -")
.replace("/", "_")
.replace("\"", "'")
.replace("?", "");
boolean isVideoDownloaded = findDownloadedVideo(videoPaths, videoName);
if(!isVideoDownloaded) {
System.out.println(videoUrl);
processHandler.downloadVideoFromUrl(videoUrl);
}
});
}
private static boolean findDownloadedVideo(List<Path> videoPaths, String videoName) {
return videoPaths.stream().anyMatch(path -> path.toString().contains(videoName));
}
}
| 38.2
| 120
| 0.624084
|
e1fe20ae58a5372400c0b32ede17bf0205fa6141
| 1,790
|
/*
* Copyright (c) 2013-2014. Urban Airship and Contributors
*/
package com.urbanairship.api.client.model;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.List;
public final class APIListTagsResponse {
private final ImmutableList<String> tags;
private APIListTagsResponse(ImmutableList<String> tags) {
this.tags = tags;
}
public static Builder newBuilder() {
return new Builder();
}
public List<String> getTags() {
return tags;
}
@Override
public String toString() {
return "APIListTagResponse{" +
"tags=" + tags +
'}';
}
@Override
public int hashCode() {
return Objects.hashCode(tags);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final APIListTagsResponse other = (APIListTagsResponse) obj;
return Objects.equal(this.tags, other.tags);
}
/**
* APIListTagResponse Builder
*/
public static class Builder {
private ImmutableList.Builder<String> tags = ImmutableList.builder();
private Builder() {
}
public Builder addTag(String tag) {
this.tags.add(tag);
return this;
}
public Builder allAllTags(Iterable<? extends String> tags) {
this.tags.addAll(tags);
return this;
}
public APIListTagsResponse build() {
Preconditions.checkNotNull(tags);
return new APIListTagsResponse(tags.build());
}
}
}
| 22.948718
| 77
| 0.588268
|
72382b43eb69caeca027a9e1a545a4b0f7b65be4
| 5,798
|
package com.buaa.pms.entity;
import java.sql.Timestamp;
public class PmsTask {
private String taskUid;
private Integer taskId;
private String taskName;
private Integer taskType;
private Integer taskInType;
private Integer taskOutType;
private String taskProjUid;
private String taskProcUid;
private String taskParUid;
private String taskManager;
private String taskDescription;
private Integer taskPriority;
private Timestamp taskPlanStartDateTime;
private Timestamp taskPlanFinishDateTime;
private Float taskPlanDur;
private Timestamp taskEarlyStartDateTime;
private Timestamp taskLateFinishDateTime;
private Timestamp taskActStartDateTime;
private Timestamp taskActFinishDateTime;
private Integer taskActDur;
private Integer taskWork;
private Integer taskCompWork;
private Integer taskRemWork;
private Float taskPctWork;
private Integer taskWorkModel;
private Integer taskState;
public String getTaskUid() {
return taskUid;
}
public void setTaskUid(String taskUid) {
this.taskUid = taskUid;
}
public Integer getTaskId() {
return taskId;
}
public void setTaskId(Integer taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public Integer getTaskType() {
return taskType;
}
public void setTaskType(Integer taskType) {
this.taskType = taskType;
}
public Integer getTaskInType() {
return taskInType;
}
public void setTaskInType(Integer taskInType) {
this.taskInType = taskInType;
}
public Integer getTaskOutType() {
return taskOutType;
}
public void setTaskOutType(Integer taskOutType) {
this.taskOutType = taskOutType;
}
public String getTaskProjUid() {
return taskProjUid;
}
public void setTaskProjUid(String taskProjUid) {
this.taskProjUid = taskProjUid;
}
public String getTaskProcUid() {
return taskProcUid;
}
public void setTaskProcUid(String taskProcUid) {
this.taskProcUid = taskProcUid;
}
public String getTaskParUid() {
return taskParUid;
}
public void setTaskParUid(String taskParUid) {
this.taskParUid = taskParUid;
}
public String getTaskManager() {
return taskManager;
}
public void setTaskManager(String taskManager) {
this.taskManager = taskManager;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public Integer getTaskPriority() {
return taskPriority;
}
public void setTaskPriority(Integer taskPriority) {
this.taskPriority = taskPriority;
}
public Timestamp getTaskPlanStartDateTime() {
return taskPlanStartDateTime;
}
public void setTaskPlanStartDateTime(Timestamp taskPlanStartDateTime) {
this.taskPlanStartDateTime = taskPlanStartDateTime;
}
public Timestamp getTaskPlanFinishDateTime() {
return taskPlanFinishDateTime;
}
public void setTaskPlanFinishDateTime(Timestamp taskPlanFinishDateTime) {
this.taskPlanFinishDateTime = taskPlanFinishDateTime;
}
public Float getTaskPlanDur() {
return taskPlanDur;
}
public void setTaskPlanDur(Float taskPlanDur) {
this.taskPlanDur = taskPlanDur;
}
public Timestamp getTaskEarlyStartDateTime() {
return taskEarlyStartDateTime;
}
public void setTaskEarlyStartDateTime(Timestamp taskEarlyStartDateTime) {
this.taskEarlyStartDateTime = taskEarlyStartDateTime;
}
public Timestamp getTaskLateFinishDateTime() {
return taskLateFinishDateTime;
}
public void setTaskLateFinishDateTime(Timestamp taskLateFinishDateTime) {
this.taskLateFinishDateTime = taskLateFinishDateTime;
}
public Timestamp getTaskActStartDateTime() {
return taskActStartDateTime;
}
public void setTaskActStartDateTime(Timestamp taskActStartDateTime) {
this.taskActStartDateTime = taskActStartDateTime;
}
public Timestamp getTaskActFinishDateTime() {
return taskActFinishDateTime;
}
public void setTaskActFinishDateTime(Timestamp taskActFinishDateTime) {
this.taskActFinishDateTime = taskActFinishDateTime;
}
public Integer getTaskActDur() {
return taskActDur;
}
public void setTaskActDur(Integer taskActDur) {
this.taskActDur = taskActDur;
}
public Integer getTaskWork() {
return taskWork;
}
public void setTaskWork(Integer taskWork) {
this.taskWork = taskWork;
}
public Integer getTaskCompWork() {
return taskCompWork;
}
public void setTaskCompWork(Integer taskCompWork) {
this.taskCompWork = taskCompWork;
}
public Integer getTaskRemWork() {
return taskRemWork;
}
public void setTaskRemWork(Integer taskRemWork) {
this.taskRemWork = taskRemWork;
}
public Float getTaskPctWork() {
return taskPctWork;
}
public void setTaskPctWork(Float taskPctWork) {
this.taskPctWork = taskPctWork;
}
public Integer getTaskWorkModel() {
return taskWorkModel;
}
public void setTaskWorkModel(Integer taskWorkModel) {
this.taskWorkModel = taskWorkModel;
}
public Integer getTaskState() {
return taskState;
}
public void setTaskState(Integer taskState) {
this.taskState = taskState;
}
}
| 23.958678
| 77
| 0.682477
|
cfc3b427877f996c2eb2bdf19f4ab0839edeac71
| 165
|
package java.security;
public class PrivilegedActionException extends Exception {
public PrivilegedActionException(Exception exception) {
super(exception);
}
}
| 20.625
| 58
| 0.812121
|
a7b2bf110b7981719d4cedfd0733a8ee02451674
| 1,391
|
/**
* Copyright 2016 - 2017
*
* Daniel Hintze <daniel.hintze@fhdw.de>
* Sebastian Scholz <sebastian.scholz@fhdw.de>
* Rainhard D. Findling <rainhard.findling@fh-hagenberg.at>
* Muhammad Muaaz <muhammad.muaaz@usmile.at>
*
* 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 at.usmile.gaitmodule.utils;
import android.util.Log;
public class SamplingRate {
/**
* This function is responsible for computing sampling rate
*
* @param timeStamps
* @return
*/
public static double computeSamplingRate(double[] timeStamps) {
double[] diffTS = ArrayManupulation.diff(timeStamps);
double meanDiffTS = Math.floor(ArrayManupulation.mean(diffTS));
Log.i("MeanTS", "" + meanDiffTS);
double samplingRate = Math.floor(1000.0 / meanDiffTS);
Log.i("SR", "" + samplingRate);
return samplingRate;
}
}
| 32.348837
| 75
| 0.695902
|
088b009e6b9afd38ab786c76920c93e9b64ed92a
| 587
|
package decaf.error;
import decaf.Location;
/**
* example:incompatible argument 3: int[] given, int/bool/string expected<br>
* 3表示发生错误的是第三个参数<br>
* PA2
*/
public class BadScopySrcError extends DecafError {
private String count;
private String dsttype;
private String srctype;
public BadScopySrcError(Location location, String dsttype, String srctype) {
super(location);
this.count = count;
this.dsttype = dsttype;
this.srctype = srctype;
}
@Override
protected String getErrMsg() {
return "incompatible dst type: " + dsttype+ " and src type: " + srctype;
}
}
| 19.566667
| 77
| 0.722317
|
a2f76756b5864c93eac72f5d81b19dc95e0b4cd6
| 7,365
|
package com.amazon;
import java.util.*;
/**
* The worst case of Kruskal Algorithm E log E
*
* build PQ - E [1 time]
* delete min - log E [E times]
* //union - log V [V times]
* //connected - log V [E times]
*
*/
public class MinCostToConnectAllNodes {
public static void main(String[] args) {
//Output: 7
int n = 6;
int[][] edges = {{1, 4}, {4, 5}, {2, 3}};
int[][] newEdges = {{1, 2, 5}, {1, 3, 10}, {1, 6, 2}, {5, 6, 5}};
SolutionMinCostToConnectAllNodes sl = new SolutionMinCostToConnectAllNodes();
int minCost = sl.solve(n, edges, newEdges);
System.out.println("# MinCostToConnectAllNodes: " + minCost);
}
}
class SolutionMinCostToConnectAllNodes {
public int solve(int n, int[][] edges, int[][] newEdges) {
if (edges == null || newEdges == null || (edges.length == 0 && newEdges.length == 0)) {
return -1;
}
//node 0 exists only for convenience, but the code ignore it
EdgeWeightedGraph g = new EdgeWeightedGraph(n+1);
//init Graph
for (int[] edge : edges) {
g.addEdge(new Edge(edge[0], edge[1], 0));
}
//check Connected Components for this Graph with weights, if all connected (cc.count == 1) then return 0$ cost
if (isNodesConnected(g, n)) {
return 0;
}
//set weights for some edges
for (int[] edge : newEdges) {
g.addEdge(new Edge(edge[0], edge[1], edge[2]));
}
UF uf = new UF(g.V);
KruskalMST mst = new KruskalMST(g, uf);
//print graph
//for (Edge e : mst.mst) {
// System.out.println(" " + e);
//}
// number of components when all cities are connected
// (count - 1) because we use node0 in the code that doesn't count, so 2 cc means 1 cc.
if ((uf.count - 1) == 1) {
return mst.weight;
} else {
return -1;
}
}
public boolean isNodesConnected(EdgeWeightedGraph G, int n) {
boolean[] marked = new boolean[n+1];
//mark unexisted element; node0 is only for convenience
marked[0] = true;
dfs(marked, 1, G);
for (int i = 0; i < n; ++i) {
if ( !marked[i]) {
return false;
}
}
return true;
}
public void dfs(boolean[] marked, int v, EdgeWeightedGraph G) {
marked[v] = true;
for (Edge edge : G.adj(v)) {
if (!marked[edge.w]) {
dfs(marked, edge.w, G);
}
}
}
}
class Edge implements Comparable<Edge> {
int v;
int w;
int weight;
public Edge(int v, int w, int weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
public int either() {
return v;
}
public int other(int other) {
if (other == v) return w;
else if (other == w) return v;
else throw new IllegalArgumentException("Illegal endpoint");
}
public int compareTo(Edge that) {
if( this.weight > that.weight )
return 1;
else if ( this.weight < that.weight )
return -1;
else
return 0;
}
public String toString() {
return String.format("%d-%d %d", v, w, weight);
}
}
class EdgeWeightedGraph {
private static final String NEWLINE = System.getProperty("line.separator");
public final int V;
public int E;
public List<Edge>[] adj;
public EdgeWeightedGraph(int N) {
this.V = N;
this.E = 0;
adj = (ArrayList<Edge>[]) new ArrayList[N];
for (int i = 0; i < N; i++) {
adj[i] = new ArrayList<Edge>();
}
}
public void addEdge(Edge edge) {
int v = edge.either();
int w = edge.other(v);
adj[v].add(edge);
adj[w].add(edge);
E++;
}
public List<Edge> adj(int v) {
return adj[v];
}
public List<Edge> edges() {
List<Edge> list = new ArrayList<Edge>();
for (int v = 0; v < V; v++) {
int selfLoops = 0;
for (Edge e : adj(v)) {
if (e.other(v) > v) {
list.add(e);
}
// add only one copy of each self loop (self loops will be consecutive)
else if (e.other(v) == v) {
if (selfLoops % 2 == 0) list.add(e);
selfLoops++;
}
}
}
return list;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V + " " + E + NEWLINE);
for (int v = 0; v < V; v++) {
s.append(v + ": ");
for (Edge e : adj[v]) {
s.append(e + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
}
class KruskalMST {
public Queue<Edge> mst = new LinkedList<Edge>(); // edges in MST
public int weight; // weight of MST
public UF uf;
public KruskalMST(EdgeWeightedGraph g, UF uf) {
this.uf = uf;
//1. Edges sorted by weight (asc, e.g. 1,2,3,4 ... n)
PriorityQueue<Edge> minHeap = new PriorityQueue<Edge>(10, Comparator.naturalOrder());
for (Edge e : g.edges()) {
minHeap.add(e);
}
//2. connect edge only if it is not create a cycle
while ( !minHeap.isEmpty() && mst.size() <= (g.V - 1) ) {
Edge edge = minHeap.poll();
int p = edge.either();
int q = edge.other(p);
//3 connect p-q in UF if edge p-q does not create a cycle
if ( !uf.connected(p,q)) {
uf.union(p,q);
mst.offer(edge);
weight += edge.weight;
}
}
}
}
class UF {
public int[] parent; // parent[i] = parent of i
public byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
public int count; // number of components
public UF (int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}
}
| 24.966102
| 118
| 0.488663
|
9cb36cf1d3d6d44cdc7bdb66980bb8c49333a6de
| 1,951
|
package org.jspare.vertx.unit;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.ext.unit.TestContext;
import org.jspare.unit.mock.InjectMocks;
import org.jspare.unit.mock.Mock;
import org.jspare.unit.mock.Mocker;
import org.jspare.vertx.unit.ext.junit.VertxJspareUnitRunner;
import org.jspare.vertx.unit.mock.AsyncResultMocker;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
/**
* Created by paulo.ferreira on 25/07/2017.
*/
@RunWith(VertxJspareUnitRunner.class)
public class AsyncResultMockerTest {
@Mock
@InjectMocks
private SomeService someService;
@Test
public void mockTest(TestContext context) {
Mocker.whenReturn(someService, "test", AsyncResultMocker.mock(Future::complete));
someService.test(ar -> context.assertTrue(ar.succeeded()));
}
@Test
public void mockSucceededTest(TestContext context) {
Mocker.whenReturn(someService, "test", AsyncResultMocker::mockSucceeded);
someService.test(ar -> context.assertTrue(ar.succeeded()));
}
@Test
public void mockSucceededWithResultTest(TestContext context) {
Mocker.whenReturn(someService, "test", AsyncResultMocker.mockSucceeded("success"));
someService.test(ar -> {
context.assertTrue(ar.succeeded());
context.assertEquals("success", ar.result());
});
}
@Test
public void mockFailedTest(TestContext context) {
Mocker.whenReturn(someService, "test", AsyncResultMocker::mockFailed);
someService.test(ar -> context.assertTrue(ar.failed()));
}
@Test
public void mockFailedWithThrowableTest(TestContext context) {
Mocker.whenReturn(someService, "test", AsyncResultMocker.mockFailed(new NullPointerException()));
someService.test(ar -> context.assertTrue(ar.cause() instanceof NullPointerException));
}
private interface SomeService {
void test(Handler<AsyncResult<String>> resultHandler);
}
}
| 30.015385
| 101
| 0.752947
|
8393eca9762f99028ba38338b93a99b16659aaa1
| 1,574
|
package git.comalmighty911216mustmeetnow.github.sportmate2;
import java.io.Serializable;
@SuppressWarnings("serial")
public class room_item implements Serializable{
String img;
String name;
String super_user;
String address;
String date;
String time;
String num;
public room_item(String img, String name, String super_user, String address, String date, String time,String phone ) {
this.img = img;
this.name = name;
this.super_user = super_user;
this.address = address;
this.date = date;
this.time = time;
this.num = phone;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSuper_user() {
return super_user;
}
public void setSuper_user(String super_user) {
this.super_user = super_user;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
| 19.675
| 122
| 0.591487
|
08884e6d162889b5aa5609cef0ff474b96dcd643
| 1,790
|
/*
* Copyright 2003-2006 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 event 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.jdon.strutsutil.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import com.jdon.model.ModelHandler;
import com.jdon.model.ModelHandlerManager;
import com.jdon.util.Debug;
/**
* @author <event href="mailto:banqiao@jdon.com">banq</event>
*
*/
public class ViewPageUtil extends EditeViewPageUtil {
private final static String module = ViewPageUtil.class.getName();
public ViewPageUtil(ModelHandlerManager modelManager) {
super(modelManager);
}
protected Object fetchModel(HttpServletRequest request, ServletContext sc, String formName, ModelHandler modelHandler) throws Exception {
Object model = null;
try {
Object keyValue = getParamKeyValue(request, modelHandler);
if (request.getSession(false) == null)
model = modelHandler.findModelIF(keyValue, sc);
else
model = modelHandler.findModelIF(keyValue, request);
} catch (Exception ex) {
Debug.logError("[JdonFramework] the method 'findModelByKey' of your handler or 'getMethod' of service happened error: " + ex, module);
throw new Exception(ex);
}
return model;
}
}
| 34.423077
| 139
| 0.732402
|
ebb52c101da3b99c5c633faf3f0a8f8f318f6d9d
| 724
|
public class Solution {
public boolean isAnagram(String s, String t){
if(s.length() != t.length()) return false;
int[] alphabets = new int[26];
for (int i = 0; i < s.length(); i++) {
++alphabets[s.charAt(i) -'a'];
}
for (int i = 0; i < t.length(); i++) {
if(--alphabets[t.charAt(i)-'a'] < 0)
return false;
}
return true;
}
public static void main(String[] args) {
String s1 = "anagram", t1 = "nagaram";
String s2 = "rat", t2 = "cat";
Solution solution = new Solution();
System.out.println(solution.isAnagram(s1, t1));
System.out.println(solution.isAnagram(s2, t2));
}
}
| 31.478261
| 55
| 0.506906
|
fc3dab1e460a6e35a2c26066177670995385183f
| 2,908
|
package net.dzikoysk.funnyguilds.command.admin;
import net.dzikoysk.funnyguilds.basic.guild.Guild;
import net.dzikoysk.funnyguilds.basic.guild.Region;
import net.dzikoysk.funnyguilds.basic.user.User;
import net.dzikoysk.funnyguilds.basic.guild.GuildUtils;
import net.dzikoysk.funnyguilds.command.util.Executor;
import net.dzikoysk.funnyguilds.data.Manager;
import net.dzikoysk.funnyguilds.data.Messages;
import net.dzikoysk.funnyguilds.data.Settings;
import net.dzikoysk.funnyguilds.data.configs.MessagesConfig;
import net.dzikoysk.funnyguilds.data.configs.PluginConfig;
import net.dzikoysk.funnyguilds.data.database.DatabaseGuild;
import net.dzikoysk.funnyguilds.data.database.DatabaseRegion;
import net.dzikoysk.funnyguilds.data.flat.Flat;
import net.dzikoysk.funnyguilds.event.FunnyEvent.EventCause;
import net.dzikoysk.funnyguilds.event.SimpleEventHandler;
import net.dzikoysk.funnyguilds.event.guild.GuildRenameEvent;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class AxcName implements Executor {
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
PluginConfig config = Settings.getConfig();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
} else if (args.length < 2) {
sender.sendMessage(messages.adminNoNewNameGiven);
return;
}
Guild guild = GuildUtils.getByTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (GuildUtils.nameExists(args[1])) {
sender.sendMessage(messages.createNameExists);
return;
}
User admin = (sender instanceof Player) ? User.get(sender.getName()) : null;
if (!SimpleEventHandler.handle(new GuildRenameEvent(admin == null ? EventCause.CONSOLE : EventCause.ADMIN, admin, guild, args[1]))) {
return;
}
Manager.getInstance().stop();
PluginConfig.DataType dataType = Settings.getConfig().dataType;
if (config.regionsEnabled) {
Region region = guild.getRegion();
if (dataType.flat) {
Flat.getRegionFile(region).delete();
}
if (dataType.mysql) {
new DatabaseRegion(region).delete();
}
region.setName(args[1]);
}
if (dataType.flat) {
Flat.getGuildFile(guild).delete();
}
if (dataType.mysql) {
new DatabaseGuild(guild).delete();
}
guild.setName(args[1]);
Manager.getInstance().start();
sender.sendMessage(messages.adminNameChanged.replace("{GUILD}", guild.getName()));
}
}
| 33.813953
| 141
| 0.651307
|
24d3d4a409c2e8d878095b826cb8897910540472
| 1,030
|
package com.napier.sem;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class CityAppTest {
@Test
void unitTest()
{
assertEquals(5, 5);
}
//Test 1, tests city get name
@Test
public void testCityReportNameSuccess(){
City city = new City("London");
assertEquals("London", city.getName());
}
//Test 2, tests failure when cities are not equal
/*
@Test
public void testCityReportNameFail(){
City city = new City("Madrid");
assertEquals(city.getName(), "Barcelona");
}
*/
//Test 3, tests population get
@Test
public void testCityReportPopulation(){
City city = new City("Madrid");
assertEquals(city.getPopulation(), -1);
}
}
| 22.888889
| 53
| 0.658252
|
064e50503649f6c00a63f69690ba517caa1b9d86
| 875
|
package Aula_12_Polimorfismo_parte1;
public class Ave extends Animal{
protected String corDaPena;
//contrutor
public Ave(String corDaPena) {
this.corDaPena = corDaPena;
}
//get and set
public String getCorDaPena() {
return corDaPena;
}
public void setCorDaPena(String corDaPena) {
this.corDaPena = corDaPena;
}
//metodos da classe
public void fazerNinho(){
System.out.println("Fazendo ninho pra ter filhinho ehueheuhe");
}
//metodos abstratos sobrepostos de Animal
@Override
public void locomover() {
System.out.println("aves voam!");
}
@Override
public void alimentar() {
System.out.println("comendo minhocas");
}
@Override
public void emitirSom() {
System.out.println("emite som de ave.");
}
}
| 19.886364
| 71
| 0.609143
|
50ec74f82388572082dd553700f67292c8fa5076
| 1,845
|
package io.jexxa.jexxatest.infrastructure.drivenadapterstrategy.messaging.recording;
import java.util.Properties;
import io.jexxa.infrastructure.drivenadapterstrategy.messaging.MessageProducer;
import io.jexxa.infrastructure.drivenadapterstrategy.messaging.MessageSender;
/**
* Stores a message that is send via JMS messaging API
*/
public class RecordedMessage
{
private final String serializedMessage;
private final Object message;
private final MessageProducer.DestinationType destinationType;
private final Properties messageProperties;
private final String destinationName;
private final MessageSender.MessageType messageType;
RecordedMessage(
Object message,
String serializedMessage,
MessageProducer.DestinationType destinationType,
String destinationName,
Properties messageProperties,
MessageSender.MessageType messageType)
{
this.message = message;
this.serializedMessage = serializedMessage;
this.destinationType = destinationType;
this.destinationName = destinationName;
this.messageProperties = messageProperties;
this.messageType = messageType;
}
public String getSerializedMessage()
{
return serializedMessage;
}
public Object getMessage()
{
return message;
}
public <T> T getMessage(Class<T> type)
{
return type.cast( getMessage() );
}
public MessageProducer.DestinationType getDestinationType()
{
return destinationType;
}
public Properties getMessageProperties()
{
return messageProperties;
}
public String getDestinationName()
{
return destinationName;
}
public MessageSender.MessageType getMessageType() { return messageType; }
}
| 26.357143
| 84
| 0.705149
|
11a0c9c99bb3a711a5f7b642c2521daf421acbca
| 13,159
|
/*
* Copyright 2013-2014 JIWHIZ Consulting Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jiwhiz.rest.site;
import static com.jiwhiz.rest.UtilConstants.API_ROOT;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_BLOGS;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_BLOGS_BLOG;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_LATEST_BLOG;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_PROFILES;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_PROFILES_USER;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_PROFILES_USER_COMMENTS;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_RECENT_BLOGS;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_RECENT_COMMENTS;
import static com.jiwhiz.rest.site.SiteApiUrls.URL_SITE_TAG_CLOUDS;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.MediaTypes;
import com.jiwhiz.domain.account.UserAccount;
import com.jiwhiz.domain.account.UserAccountRepository;
import com.jiwhiz.domain.post.BlogPost;
import com.jiwhiz.domain.post.BlogPostRepository;
import com.jiwhiz.domain.post.CommentPost;
import com.jiwhiz.domain.post.CommentPostRepository;
import com.jiwhiz.domain.post.CommentStatusType;
import com.jiwhiz.rest.AbstractRestControllerTest;
/**
* @author Yuan Ji
*/
public class WebsiteRestControllerTest extends AbstractRestControllerTest {
@Inject
UserAccountRepository userAccountRepositoryMock;
@Inject
BlogPostRepository blogPostRepositoryMock;
@Inject
CommentPostRepository commentPostRepositoryMock;
@Before
public void setup() {
Mockito.reset(userAccountRepositoryMock);
Mockito.reset(blogPostRepositoryMock);
Mockito.reset(commentPostRepositoryMock);
super.setup();
}
@Test
public void getPublicWebsiteResource_ShouldReturnWebsiteResource() throws Exception {
UserAccount user = getTestLoggedInUserWithAdminRole();
when(userAccountServiceMock.getCurrentUser()).thenReturn(user);
mockMvc.perform(get(API_ROOT + URL_SITE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
//check links
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE)))
.andExpect(jsonPath("$._links.blogs.templated", is(true)))
.andExpect(jsonPath("$._links.blogs.href", endsWith(URL_SITE_BLOGS+"{?page,size,sort}")))
.andExpect(jsonPath("$._links.blog.templated", is(true)))
.andExpect(jsonPath("$._links.blog.href", endsWith(URL_SITE_BLOGS_BLOG)))
.andExpect(jsonPath("$._links.profile.templated", is(true)))
.andExpect(jsonPath("$._links.profile.href", endsWith(URL_SITE_PROFILES_USER)))
.andExpect(jsonPath("$._links.latestBlog.href", endsWith(URL_SITE_LATEST_BLOG)))
.andExpect(jsonPath("$._links.recentBlogs.href", endsWith(URL_SITE_RECENT_BLOGS)))
.andExpect(jsonPath("$._links.recentComments.href", endsWith(URL_SITE_RECENT_COMMENTS)))
.andExpect(jsonPath("$._links.tagCloud.href", endsWith(URL_SITE_TAG_CLOUDS)))
;
}
@Test
public void getPublicWebsiteResource_ShouldReturnWebsiteResourceWithoutAuthenticatedUser() throws Exception {
when(userAccountServiceMock.getCurrentUser()).thenReturn(null);
mockMvc.perform(get(API_ROOT + URL_SITE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
//check links
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE)))
.andExpect(jsonPath("$._links.blogs.templated", is(true)))
.andExpect(jsonPath("$._links.blogs.href", endsWith(URL_SITE_BLOGS+"{?page,size,sort}")))
.andExpect(jsonPath("$._links.blog.templated", is(true)))
.andExpect(jsonPath("$._links.blog.href", endsWith(URL_SITE_BLOGS_BLOG)))
.andExpect(jsonPath("$._links.profile.templated", is(true)))
.andExpect(jsonPath("$._links.profile.href", endsWith(URL_SITE_PROFILES_USER)))
.andExpect(jsonPath("$._links.latestBlog.href", endsWith(URL_SITE_LATEST_BLOG)))
.andExpect(jsonPath("$._links.recentBlogs.href", endsWith(URL_SITE_RECENT_BLOGS)))
.andExpect(jsonPath("$._links.recentComments.href", endsWith(URL_SITE_RECENT_COMMENTS)))
.andExpect(jsonPath("$._links.tagCloud.href", endsWith(URL_SITE_TAG_CLOUDS)))
;
}
@Test
public void getUserProfile_ShouldReturnUserProfile() throws Exception {
UserAccount user = getTestLoggedInUserWithAdminRole();
when(userAccountRepositoryMock.findOne(ADMIN_USER_ID)).thenReturn(user);
mockMvc.perform(get(API_ROOT + URL_SITE_PROFILES_USER, ADMIN_USER_USERNAME))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$.displayName", is (USER_DISPLAY_NAME)))
.andExpect(jsonPath("$.admin", is(true)))
.andExpect(jsonPath("$.author", is(false)))
//check links
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_PROFILES+"/"+ADMIN_USER_USERNAME)))
.andExpect(jsonPath("$._links.comments.templated", is(true)))
.andExpect(jsonPath("$._links.comments.href", endsWith(
URL_SITE_PROFILES+"/"+ADMIN_USER_USERNAME+"/comments{?page,size,sort}")))
;
}
@Test
public void getApprovedUserCommentPosts_ShouldReturnApprovedComments() throws Exception {
UserAccount user = getTestLoggedInUser();
Page<CommentPost> page = new PageImpl<CommentPost>(getTestApprovedCommentPostList(), new PageRequest(0, 10), 2);
when(userAccountServiceMock.loadUserByUserId(USER_USERNAME)).thenReturn(user);
when(commentPostRepositoryMock.findByAuthorAndStatusOrderByCreatedTimeDesc(
eq(user), eq(CommentStatusType.APPROVED), any(Pageable.class)))
.thenReturn(page);
mockMvc.perform(get(API_ROOT + URL_SITE_PROFILES_USER_COMMENTS, USER_USERNAME))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$._embedded.commentPostList", hasSize(2)))
.andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID)))
.andExpect(jsonPath("$._embedded.commentPostList[0].content", is (COMMENTS_1_CONTENT)))
.andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID)))
.andExpect(jsonPath("$._embedded.commentPostList[1].content", is(COMMENTS_2_CONTENT)))
.andExpect(jsonPath("$._links.self.templated", is(true)))
.andExpect(jsonPath("$._links.self.href", endsWith("/comments{?page,size,sort}")))
.andExpect(jsonPath("$.page.size", is(10)))
.andExpect(jsonPath("$.page.totalElements", is(2)))
.andExpect(jsonPath("$.page.totalPages", is(1)))
.andExpect(jsonPath("$.page.number", is(0)))
;
verify(commentPostRepositoryMock, times(1)).findByAuthorAndStatusOrderByCreatedTimeDesc(
any(UserAccount.class), eq(CommentStatusType.APPROVED), any(Pageable.class));
verifyNoMoreInteractions(commentPostRepositoryMock);
}
@Test
public void getLatestBlogPost_ShouldReturnBlogPost() throws Exception {
BlogPost blog = getTestSinglePublishedBlogPost();
when(blogPostRepositoryMock.findByPublishedIsTrueOrderByPublishedTimeDesc(any(Pageable.class)))
.thenReturn(new PageImpl<BlogPost>(Arrays.asList(blog), new PageRequest(0, 1), 1));
mockMvc.perform(get(API_ROOT + URL_SITE_LATEST_BLOG))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$.id", is (BLOG_ID)))
.andExpect(jsonPath("$.title", is (BLOG_TITLE)))
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_BLOGS+"/"+BLOG_ID)))
.andExpect(jsonPath("$._links.comments.templated", is(true)))
.andExpect(jsonPath("$._links.comments.href", endsWith(
URL_SITE_BLOGS+"/"+BLOG_ID+"/comments{?page,size,sort}")))
.andExpect(jsonPath("$._links.author.href", endsWith(URL_SITE_PROFILES+"/"+blog.getAuthor().getUserId())))
;
}
@Test
public void getRecentPublicBlogPosts_ShouldReturnRecentBlogPosts() throws Exception {
Pageable pageable = new PageRequest(0, 4);
when(blogPostRepositoryMock.findByPublishedIsTrueOrderByPublishedTimeDesc(any(Pageable.class)))
.thenReturn(new PageImpl<BlogPost>(getTestPublishedBlogPostList(), pageable, 2));
mockMvc.perform(get(API_ROOT + URL_SITE_RECENT_BLOGS))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$._embedded.blogPostList", hasSize(2)))
.andExpect(jsonPath("$._embedded.blogPostList[0].id", is(BLOGS_1_ID)))
.andExpect(jsonPath("$._embedded.blogPostList[0].title", is(BLOGS_1_TITLE)))
.andExpect(jsonPath("$._embedded.blogPostList[1].id", is(BLOGS_2_ID)))
.andExpect(jsonPath("$._embedded.blogPostList[1].title", is(BLOGS_2_TITLE)))
//check links
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_RECENT_BLOGS)))
;
verify(blogPostRepositoryMock, times(1)).findByPublishedIsTrueOrderByPublishedTimeDesc(pageable);
verifyNoMoreInteractions(blogPostRepositoryMock);
}
@Test
public void getRecentPublicCommentPosts_ShouldReturnRecentCommentPosts() throws Exception {
Pageable pageable = new PageRequest(0, 4);
when(commentPostRepositoryMock.findByStatusOrderByCreatedTimeDesc(eq(CommentStatusType.APPROVED), any(Pageable.class)))
.thenReturn(new PageImpl<CommentPost>(getTestApprovedCommentPostList(), pageable, 2));
mockMvc.perform(get(API_ROOT + URL_SITE_RECENT_COMMENTS))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$._embedded.commentPostList", hasSize(2)))
.andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID)))
.andExpect(jsonPath("$._embedded.commentPostList[0].content", is (COMMENTS_1_CONTENT)))
.andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID)))
.andExpect(jsonPath("$._embedded.commentPostList[1].content", is(COMMENTS_2_CONTENT)))
//check links
.andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_RECENT_COMMENTS)))
;
verify(commentPostRepositoryMock, times(1)).findByStatusOrderByCreatedTimeDesc(CommentStatusType.APPROVED, pageable);
verifyNoMoreInteractions(commentPostRepositoryMock);
}
}
| 51.807087
| 127
| 0.683411
|
8dd6adc1419e837def47935614c6ef339d93764a
| 9,785
|
package ru.job4j.test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* test for Bank.
*
* @author Ayuzyak
* @since 01.05.2017
* @version 1.0
*/
public class BankTest {
/**
* test adding client to bank.
*/
@Test
public void whenAddClientToBank() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
User thirdUser = new User("Mary", 150200);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
bank.addUser(thirdUser);
Map<User, List<Account>> resultMap = bank.getMap();
Map<User, List<Account>> checkMap = new HashMap<>();
checkMap.put(firstUser, new ArrayList<>());
checkMap.put(secondUser, new ArrayList<>());
checkMap.put(thirdUser, new ArrayList<>());
assertThat(resultMap, is(checkMap));
}
/**
* test deleting client from bank.
*/
@Test
public void whenDeleteClientFromBank() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
User thirdUser = new User("Mary", 150200);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
bank.addUser(thirdUser);
try {
bank.deleteUser(secondUser);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
Map<User, List<Account>> resultMap = bank.getMap();
Map<User, List<Account>> checkMap = new HashMap<>();
checkMap.put(firstUser, new ArrayList<>());
checkMap.put(thirdUser, new ArrayList<>());
assertThat(resultMap, is(checkMap));
}
/**
* test adding account to bank client.
*/
@Test
public void whenAddAccountToClient() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account account = new Account(12345);
try {
bank.addAccountToUser(secondUser, account);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
Map<User, List<Account>> resultMap = bank.getMap();
Map<User, List<Account>> checkMap = new HashMap<>();
checkMap.put(firstUser, new ArrayList<>());
List<Account> list = new ArrayList<>();
list.add(account);
checkMap.put(secondUser, list);
assertThat(resultMap, is(checkMap));
}
/**
* test deleting account from client's account list.
*/
@Test
public void whenDeleteAccountFromClient() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account firstAccount = new Account(12345);
Account secondAccount = new Account(234);
try {
bank.addAccountToUser(secondUser, firstAccount);
bank.addAccountToUser(secondUser, secondAccount);
bank.deleteAccountFromUser(secondUser, firstAccount);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
Map<User, List<Account>> resultMap = bank.getMap();
Map<User, List<Account>> checkMap = new HashMap<>();
checkMap.put(firstUser, new ArrayList<>());
List<Account> list = new ArrayList<>();
list.add(secondAccount);
checkMap.put(secondUser, list);
assertThat(resultMap, is(checkMap));
}
/**
* test getting client's account list.
*/
@Test
public void whenGetListOfAccountsFromClient() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account firstAccount = new Account(12345);
Account secondAccount = new Account(234);
Account thirdAccount = new Account(555);
List<Account> resultList = null;
try {
bank.addAccountToUser(secondUser, firstAccount);
bank.addAccountToUser(secondUser, secondAccount);
bank.addAccountToUser(secondUser, thirdAccount);
resultList = bank.getUserAccounts(secondUser);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
List<Account> checkList = new ArrayList<>();
checkList.add(firstAccount);
checkList.add(secondAccount);
checkList.add(thirdAccount);
assertThat(resultList, is(checkList));
}
/**
* test transfer money.
* Transfer from account to other, when balance of source account more than transfer value.
*/
@Test
public void transferWhenOneAccountsMoreThanTransferValue() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account firstAccount = new Account(12345);
firstAccount.setValue(500);
Account secondAccount = new Account(234);
secondAccount.setValue(100);
boolean resultTransfer = false;
try {
bank.addAccountToUser(firstUser, firstAccount);
bank.addAccountToUser(secondUser, secondAccount);
resultTransfer = bank.transferMoney(firstUser, firstAccount, secondUser, secondAccount, 100);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
double resultValueFirstAccount = firstAccount.getValue();
double resultValueSecondAccount = secondAccount.getValue();
double checkValueFirstAccount = 400;
double checkValueSecondAccount = 200;
assertThat(resultTransfer, is(true));
assertThat(resultValueFirstAccount, is(checkValueFirstAccount));
assertThat(resultValueSecondAccount, is(checkValueSecondAccount));
}
/**
* test transfer money.
* Transfer from account to other, when balance of source account less than destination.
*/
@Test
public void transferWhenOneAccountsLessThanTransferValue() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account firstAccount = new Account(12345);
firstAccount.setValue(100);
Account secondAccount = new Account(234);
secondAccount.setValue(100);
boolean resultTransfer = false;
try {
bank.addAccountToUser(firstUser, firstAccount);
bank.addAccountToUser(secondUser, secondAccount);
resultTransfer = bank.transferMoney(firstUser, firstAccount, secondUser, secondAccount, 101);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
assertThat(resultTransfer, is(false));
}
/**
* test transfer money.
* Transfer from account to other, when no source account in client's account list.
*/
@Test
public void transferWhenNoSourceAccount() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
bank.addUser(secondUser);
Account firstAccount = new Account(12345);
firstAccount.setValue(500);
Account secondAccount = new Account(234);
secondAccount.setValue(200);
Account thirdAccount = new Account(555);
thirdAccount.setValue(300);
boolean resultTransfer = false;
try {
bank.addAccountToUser(firstUser, firstAccount);
bank.addAccountToUser(secondUser, secondAccount);
resultTransfer = bank.transferMoney(firstUser, thirdAccount, secondUser, secondAccount, 50);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
assertThat(resultTransfer, is(false));
}
/**
* test throwing NoSuchUserException.
*/
@Test
public void whenBankHasNoClient() {
User firstUser = new User("John", 100555);
User secondUser = new User("Ivan", 200321);
Bank bank = new Bank();
bank.addUser(firstUser);
String resultException = "NoException";
try {
bank.deleteUser(secondUser);
} catch (NoSuchUserException e) {
resultException = "NoSuchUserException was caught";
}
String checkException = "NoSuchUserException was caught";
assertThat(resultException, is(checkException));
}
/**
* test getting client from bank.
*/
@Test
public void whenBankHasClient() {
User firstUser = new User("John", 100555);
Bank bank = new Bank();
bank.addUser(firstUser);
Account account = new Account(1001);
account.setValue(500);
User client = null;
List<Account> accountListFirstUser = null;
List<Account> accountListClient = null;
try {
client = bank.getUser("John", 100555);
bank.addAccountToUser(firstUser, account);
accountListFirstUser = bank.getUserAccounts(firstUser);
accountListClient = bank.getUserAccounts(client);
} catch (NoSuchUserException e) {
e.printStackTrace();
}
assertThat(accountListFirstUser, is(accountListClient));
}
}
| 35.581818
| 105
| 0.61676
|
0e42c217ad3311af9d113c1d3380b2cf001a3eb2
| 774
|
//
// Decompiled by Procyon v0.5.36
//
package org.pitest.mutationtest.build;
import org.pitest.mutationtest.TimeoutLengthStrategy;
public class PercentAndConstantTimeoutStrategy implements TimeoutLengthStrategy
{
private static final long serialVersionUID = 1L;
public static final float DEFAULT_FACTOR = 1.25f;
public static final long DEFAULT_CONSTANT = 4000L;
private final float percent;
private final long constant;
public PercentAndConstantTimeoutStrategy(final float percent, final long constant) {
this.percent = percent;
this.constant = constant;
}
@Override
public long getAllowedTime(final long normalDuration) {
return Math.round(normalDuration * this.percent) + this.constant;
}
}
| 28.666667
| 88
| 0.73385
|
ada0c6f98dba40aafad48b87112794cdd231fdb5
| 4,707
|
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2016 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.visitor;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import org.junit.Test;
import static com.github.javaparser.JavaParser.parseExpression;
import static com.github.javaparser.utils.Utils.EOL;
import static org.junit.Assert.assertEquals;
public class ModifierVisitorTest {
@Test
public void makeSureParentListsCanBeModified() {
NodeList<StringLiteralExpr> list = new NodeList<>();
list.add(new StringLiteralExpr("t"));
list.add(new StringLiteralExpr("a"));
list.add(new StringLiteralExpr("b"));
list.add(new StringLiteralExpr("c"));
list.accept(new ModifierVisitor<Void>() {
@Override
public Visitable visit(final StringLiteralExpr n, final Void arg) {
String v = n.getValue();
list.addFirst(new StringLiteralExpr("extra " + v));
list.remove(new StringLiteralExpr("t"));
if (v.equals("a")) {
return new StringLiteralExpr("x");
}
if (v.equals("b")) {
return null;
}
return n;
}
}, null);
assertEquals("extra c", list.get(0).getValue());
assertEquals("extra b", list.get(1).getValue());
assertEquals("extra a", list.get(2).getValue());
assertEquals("extra t", list.get(3).getValue());
assertEquals("x", list.get(4).getValue());
assertEquals("c", list.get(5).getValue());
assertEquals(6, list.size());
}
@Test
public void binaryExprReturnsLeftExpressionWhenRightSideIsRemoved() {
Expression expression = parseExpression("1+2");
Visitable result = expression.accept(new ModifierVisitor<Void>() {
public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
if (integerLiteralExpr.getValue().equals("1")) {
return null;
}
return integerLiteralExpr;
}
}, null);
assertEquals("2", result.toString());
}
@Test
public void binaryExprReturnsRightExpressionWhenLeftSideIsRemoved() {
final Expression expression = parseExpression("1+2");
final Visitable result = expression.accept(new ModifierVisitor<Void>() {
public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
if (integerLiteralExpr.getValue().equals("2")) {
return null;
}
return integerLiteralExpr;
}
}, null);
assertEquals("1", result.toString());
}
@Test
public void fieldDeclarationCantSurviveWithoutVariables() {
final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("int x=1;");
final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() {
public Visitable visit(VariableDeclarator x, Void arg) {
return null;
}
}, null);
assertEquals(null, result);
}
@Test
public void variableDeclarationCantSurviveWithoutVariables() {
final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("void x() {int x=1;}");
final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() {
public Visitable visit(VariableDeclarator x, Void arg) {
return null;
}
}, null);
assertEquals("void x() {" + EOL + "}", result.toString());
}
}
| 36.773438
| 106
| 0.636711
|
caf598066dfe078effb0c7cd16d3bdda10ad7892
| 566
|
package org.ovirt.engine.ui.uicommonweb.models;
/**
* Simple {@link org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel}
* that has the same detail entity as its list elements.
*
* @param <E> {@link org.ovirt.engine.ui.uicommonweb.models.SearchableListModel.E}
* @param <T> {@link org.ovirt.engine.ui.uicommonweb.models.SearchableListModel.T}
*/
public abstract class ListWithSimpleDetailsModel<E, T> extends ListWithDetailsModel<E, T, T> {
@Override
protected T provideDetailModelEntity(T selectedItem) {
return selectedItem;
}
}
| 35.375
| 94
| 0.745583
|
5d2cc027cafd34b63c24406a0be75aa708d187e6
| 3,568
|
/*
* 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.asterix.spidersilk;
import me.arminb.spidersilk.SpiderSilkRunner;
import me.arminb.spidersilk.dsl.entities.Deployment;
import me.arminb.spidersilk.dsl.entities.PortType;
import me.arminb.spidersilk.dsl.entities.ServiceType;
import me.arminb.spidersilk.exceptions.RuntimeEngineException;
import org.apache.asterix.test.common.TestExecutor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class TestUtil {
private static String mavenVersion;
private static String asterixHome;
public static Deployment getSimpleClusterDeployment() {
mavenVersion = getMavenArtifactVersion();
asterixHome = "/asterix/apache-asterixdb-" + mavenVersion;
return new Deployment.DeploymentBuilder("simpleClusterDeployment")
// Service Definitions
.withService("asterix")
.applicationPath("../asterix-server/target/asterix-server-" + mavenVersion + "-binary-assembly.zip",
"/asterix", false, true, false)
.dockerFileAddress("docker/Dockerfile", false).dockerImage("spidersilk/test-asterix")
.instrumentablePath(asterixHome + "/repo/asterix-server-" + mavenVersion + ".jar")
.libraryPath(asterixHome + "/repo/*.jar").libraryPath(asterixHome + "/lib/*.jar")
.logDirectory(asterixHome + "/logs").serviceType(ServiceType.JAVA).and()
// Node Definitions
.withNode("cc", "asterix").applicationPath("config", "/asterix/config")
.startCommand(asterixHome + "/bin/asterixcc -config-file /asterix/config/cc.conf").tcpPort(19002).and()
.withNode("nc1", "asterix").startCommand(asterixHome + "/bin/asterixncservice").and()
.withNode("nc2", "asterix").startCommand(asterixHome + "/bin/asterixncservice").and().build();
}
public static String getMavenArtifactVersion() {
Properties mavenProperties = new Properties();
try {
mavenProperties.load(new FileInputStream("../asterix-server/target/maven-archiver/pom.properties"));
return mavenProperties.getProperty("version");
} catch (IOException e) {
throw new RuntimeException("Cannot open pom.properties to get the maven version");
}
}
public static void waitForClusterToBeUp(SpiderSilkRunner runner) throws RuntimeEngineException {
runner.runtime().runCommandInNode("cc", asterixHome + "/bin/asterixhelper wait_for_cluster");
}
public static TestExecutor getTestExecutor(SpiderSilkRunner runner) {
return new TestExecutor(runner.runtime().ip("cc"), runner.runtime().portMapping("cc", 19002, PortType.TCP));
}
}
| 48.216216
| 119
| 0.699552
|
a8fa4097bdb27a610273e38a55ee7ec1cbf5c748
| 1,031
|
package com.example.demo;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.SendTo;
@SpringBootApplication
public class SolverApplication {
private static final Logger logger = LoggerFactory.getLogger(SolverApplication.class);
public static void main(String[] args) {
SpringApplication.run(SolverApplication.class, args);
}
@Autowired
QuadraticSolver solver;
@RabbitListener(queues = "equations")
@SendTo("solutions")
public Solution handleMessage(Equation equation) {
return solver.solve(equation);
}
}
| 28.638889
| 87
| 0.823472
|
991f947d75f614fe7bf863c1bd665ba8abec4284
| 1,945
|
package com.puppycrawl.tools.checkstyle.checks.indentation; //indent:0 exp:0
/** //indent:0 exp:0
* This test-input is intended to be checked using following configuration: //indent:1 exp:1
* //indent:1 exp:1
* arrayInitIndent = 4 //indent:1 exp:1
* basicOffset = 4 //indent:1 exp:1
* braceAdjustment = 0 //indent:1 exp:1
* caseIndent = 4 //indent:1 exp:1
* forceStrictCondition = false //indent:1 exp:1
* lineWrappingIndentation = 4 //indent:1 exp:1
* tabWidth = 4 //indent:1 exp:1
* throwsIndent = 4 //indent:1 exp:1
* //indent:1 exp:1
* @author jrichard //indent:1 exp:1
*/ //indent:1 exp:1
public class InputCaseLevel { //indent:0 exp:0
/** Creates a new instance of InputCaseLevel */ //indent:4 exp:4
public InputCaseLevel() { //indent:4 exp:4
int test = 4; //indent:8 exp:8
switch (test) { //indent:8 exp:8
case 4: //indent:8 exp:8
break; //indent:12 exp:12
case 2: //indent:8 exp:8
break; //indent:12 exp:12
default: //indent:10 exp:8 warn
break; //indent:12 exp:12
} //indent:8 exp:8
} //indent:4 exp:4
} //indent:0 exp:0
| 55.571429
| 94
| 0.366581
|
7b92d4b2f946d6ded383c598c0d9c34d0c3dac31
| 6,998
|
/*
* Copyright 2013-2019 Hippo B.V. (http://www.onehippo.com)
*
* 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.hippoecm.repository.security.service;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import org.hippoecm.repository.api.NodeNameCodec;
import org.hippoecm.repository.security.group.GroupManager;
import org.hippoecm.repository.util.JcrUtils;
import org.hippoecm.repository.util.PropertyIterable;
import org.onehippo.repository.security.User;
import com.google.common.collect.ImmutableSet;
import static org.hippoecm.repository.api.HippoNodeType.HIPPOSYS_EMAIL;
import static org.hippoecm.repository.api.HippoNodeType.HIPPOSYS_FIRSTNAME;
import static org.hippoecm.repository.api.HippoNodeType.HIPPOSYS_LASTNAME;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_ACTIVE;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_LASTLOGIN;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_PASSKEY;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_PASSWORD;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_PASSWORDLASTMODIFIED;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_SYSTEM;
import static org.hippoecm.repository.api.HippoNodeType.HIPPO_USERROLES;
import static org.hippoecm.repository.api.HippoNodeType.NT_EXTERNALUSER;
/**
* Implementation of a {@link User}, using lazy loading of its {@link GroupManager#getMembershipIds(String) group memberships}.
*/
public class UserImpl extends AbstractSecurityNodeInfo implements User {
private static final long serialVersionUID = 1L;
private static final Set<String> PROTECTED_PROPERTY_NAMES = ImmutableSet.of(
HIPPO_PASSWORD,
HIPPO_PASSKEY,
HIPPO_PASSWORDLASTMODIFIED,
HIPPO_SYSTEM,
HIPPO_ACTIVE,
HIPPO_LASTLOGIN
);
private final String id;
private final boolean external;
private final HashMap<String, Serializable> properties = new HashMap<>();
private final Set<String> groups;
private final Set<String> userRoles;
public UserImpl(final Node node, final GroupManager groupManager) throws RepositoryException {
// use a pass-through rolesResolver (no resolving) for normal Users
this(node, groupManager, userRoles -> userRoles);
}
protected UserImpl(final Node userNode, final GroupManager groupManager,
final Function<Set<String>, Set<String>> rolesResolver) throws RepositoryException {
this.id = NodeNameCodec.decode(userNode.getName());
this.external = userNode.isNodeType(NT_EXTERNALUSER);
// load and store the String value of all node properties which are:
// - not multiple value
// - of type String|Boolean}Date|Double|Long
// - and not skipped (either to be hidden, or to be loaded with the predefined/interface non-String value below)
for (Property p : new PropertyIterable(userNode.getProperties())) {
if (isInfoProperty(p)) {
properties.put(p.getName(), p.getString());
}
}
// load and store the non-string type values for predefined/interface properties
properties.put(HIPPO_SYSTEM, JcrUtils.getBooleanProperty(userNode, HIPPO_SYSTEM, false));
properties.put(HIPPO_ACTIVE, JcrUtils.getBooleanProperty(userNode, HIPPO_ACTIVE, true));
properties.put(HIPPO_LASTLOGIN, JcrUtils.getDateProperty(userNode, HIPPO_LASTLOGIN, null));
final HashSet<String> collectedUserRoles = new HashSet<>();
final HashSet<String> collectedGroups = new HashSet<>();
// load and store the user roles and groups (memberships) for the user
collectUserRolesAndGroups(userNode, groupManager, collectedUserRoles, collectedGroups);
this.userRoles = rolesResolver.andThen(Collections::unmodifiableSet).apply(collectedUserRoles);
this.groups = Collections.unmodifiableSet(collectedGroups);
}
protected List<String> collectUserRoles(final Node userNode) throws RepositoryException {
return JcrUtils.getStringListProperty(userNode, HIPPO_USERROLES, Collections.emptyList());
}
protected void collectUserRolesAndGroups(final Node userNode, final GroupManager groupManager,
final HashSet<String> userRoles, final HashSet<String> groups)
throws RepositoryException {
userRoles.addAll(collectUserRoles(userNode));
groups.addAll(groupManager.getMembershipIds(getId()));
}
protected Set<String> getProtectedPropertyNames() {
return PROTECTED_PROPERTY_NAMES;
}
@Override
public Set<String> getPropertyNames() {
return properties.entrySet().stream()
.filter(entry -> entry.getValue() instanceof String)
.map(Map.Entry::getKey).collect(Collectors.toSet());
}
@Override
public String getId() {
return id;
}
@Override
public boolean isSystemUser() {
return (Boolean)properties.get(HIPPO_SYSTEM);
}
@Override
public boolean isActive() {
return (Boolean)properties.get(HIPPO_ACTIVE);
}
@Override
public boolean isExternal() {
return external;
}
@Override
public String getFirstName() {
return getProperty(HIPPOSYS_FIRSTNAME);
}
@Override
public String getLastName() {
return getProperty(HIPPOSYS_LASTNAME);
}
@Override
public String getEmail() {
return getProperty(HIPPOSYS_EMAIL);
}
@Override
public Calendar getLastLogin() {
return (Calendar)properties.get(HIPPO_LASTLOGIN);
}
@Override
public String getProperty(final String propertyName) {
Object value = properties.get(propertyName);
return value instanceof String ? (String)value : null;
}
@Override
public Set<String> getMemberships() {
return groups;
}
@Override
public Set<String> getUserRoles() {
return userRoles;
}
@Override
public String toString() {
return "User: " + getId();
}
}
| 36.638743
| 127
| 0.713632
|
207ff347c9a55829b946ce0e2d2efecf67302f70
| 3,826
|
/*
* Copyright (C) 2012 Orange Labs UK. All Rights Reserved.
* Copyright (C) 2011 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 com.orange.labs.uk.omtp.notification;
import android.content.Context;
import android.os.Bundle;
import com.orange.labs.uk.omtp.utils.NetworkManager;
public class NotifChannelNotification extends AbstractNotification {
private NotifChannelNotification(Bundle bundle) {
super(SourceNotification.NOTIF_CHANNEL_ACTION, bundle);
}
/**
* Generates a notification indicating that the connectivity is okay, ie. the connection was
* successful.
*/
public static NotifChannelNotification connectivityOk() {
return new Builder().setConnectivityStatus(ConnectivityStatus.CONNECTIVITY_OK).build();
}
/**
* Generates a notification indicating that the connectivity is KO, adding the cause of the
* failure.
*
* @param context
* Used to determine the reason of the failure.
*/
public static NotifChannelNotification connectivityKo(Context context) {
Builder builder = new Builder().setConnectivityStatus(ConnectivityStatus.CONNECTIVITY_KO);
addErrorCause(context, builder);
return builder.build();
}
/**
* Is used to create error notification in a situation when SMS message construction has failed
* for some reason. Currently implemented in the same way as {@link #connectivityKo(Context)}
*
* @param context
* @return CONNECTIVITY_KO notification
*/
public static NotifChannelNotification messageBuildFailed(Context context) {
// TODO: Think if more specific implementation of this method is required.
return connectivityKo(context);
}
/**
* Notification useful to indicate that a message is waiting on the server. Despite having a
* notification, information were missing and the message could not be stored locally.
*
* @return MESSAGE_WAITING notification
*/
public static NotifChannelNotification messageWaiting() {
return new Builder().setConnectivityStatus(ConnectivityStatus.MESSAGE_WAITING).build();
}
/**
* Notification used to indicate that the SMS sending timeout has expired.
*
* @return CONNECTIVITY_KO notification
*/
public static NotifChannelNotification connectivityTimeout() {
return new Builder().setConnectivityStatus(ConnectivityStatus.CONNECTIVITY_KO)
.setErrorCause(ErrorCause.TIMEOUT).build();
}
/**
* Investigate the cause of the SMS connectivity error.
*/
private static void addErrorCause(Context context, Builder builder) {
NetworkManager monitor = new NetworkManager(context);
if (monitor.isInAirplaneMode()) {
builder.setErrorCause(ErrorCause.AIRPLANE);
} else if (monitor.isSimAbsent()) {
builder.setErrorCause(ErrorCause.SIM_ABSENT);
} else {
builder.setErrorCause(ErrorCause.UNKNOWN);
}
}
public static class Builder {
private Bundle mBundle = new Bundle();
public Builder setConnectivityStatus(ConnectivityStatus status) {
mBundle.putSerializable(SourceNotification.CONNECTIVITY_STATUS_KEY, status);
return this;
}
public Builder setErrorCause(ErrorCause cause) {
mBundle.putSerializable(SourceNotification.ERROR_CAUSE_KEY, cause);
return this;
}
public NotifChannelNotification build() {
return new NotifChannelNotification(mBundle);
}
}
}
| 32.423729
| 96
| 0.759279
|
d22a0916aa9ca3101e5d001a1c627c70dba2da44
| 1,725
|
package home.app.grpc.api.mappers;
import home.app.grpc.UserMessage;
import home.app.grpc.api.model.IMapper;
import home.app.grpc.api.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class UserMapper implements IMapper<User, UserMessage> {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AddressMapper addressMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public User toEntity(UserMessage dto) {
User user = new User();
user.setEmail(dto.getEmail());
user.setFirstName(dto.getFirstName());
user.setId(dto.getId());
user.setLastName(dto.getLastName());
user.setPassword(passwordEncoder.encode(dto.getPassword()));
user.setPhone(dto.getPhone());
user.setBlocked(dto.getBlocked());
user.setRole(userRoleMapper.toEntity(dto.getRole()));
user.setAddress(addressMapper.toEntity(dto.getAddress()));
return user;
}
@Override
public UserMessage toDTO(User user) {
return UserMessage.newBuilder()
.setAddress(addressMapper.toDTO(user.getAddress()))
.setBlocked(user.getBlocked())
.setEmail(user.getEmail())
.setFirstName(user.getFirstName())
.setId(user.getId())
.setLastName(user.getLastName())
.setPassword(user.getPassword())
.setPhone(user.getPhone())
.setRole(userRoleMapper.toDTO(user.getRole()))
.build();
}
}
| 32.54717
| 68
| 0.656812
|
90c4c9c03806a73f8a0defa42d7c8d75b8895b69
| 1,994
|
/*
* 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.aliyuncs.couponnew.model.v20190401;
import com.aliyuncs.RpcAcsRequest;
/**
* @author auto create
* @version
*/
public class GetCouponFullTemplatePageRequest extends RpcAcsRequest<GetCouponFullTemplatePageResponse> {
public GetCouponFullTemplatePageRequest() {
super("CouponNew", "2019-04-01", "GetCouponFullTemplatePage");
}
private String fromApp;
private String param;
private Integer pageNo;
private Integer pageSize;
public String getFromApp() {
return this.fromApp;
}
public void setFromApp(String fromApp) {
this.fromApp = fromApp;
if(fromApp != null){
putQueryParameter("FromApp", fromApp);
}
}
public String getParam() {
return this.param;
}
public void setParam(String param) {
this.param = param;
if(param != null){
putQueryParameter("Param", param);
}
}
public Integer getPageNo() {
return this.pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
if(pageNo != null){
putQueryParameter("PageNo", pageNo.toString());
}
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
if(pageSize != null){
putQueryParameter("PageSize", pageSize.toString());
}
}
@Override
public Class<GetCouponFullTemplatePageResponse> getResponseClass() {
return GetCouponFullTemplatePageResponse.class;
}
}
| 22.91954
| 104
| 0.712638
|
112cc72b05d19cb07640a8ab7ba4ca21ba2e83d4
| 11,083
|
package sqlancer.mysql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import sqlancer.Randomly;
import sqlancer.common.schema.AbstractRowValue;
import sqlancer.common.schema.AbstractSchema;
import sqlancer.common.schema.AbstractTable;
import sqlancer.common.schema.AbstractTableColumn;
import sqlancer.common.schema.AbstractTables;
import sqlancer.common.schema.TableIndex;
import sqlancer.mysql.MySQLSchema.MySQLTable;
import sqlancer.mysql.MySQLSchema.MySQLTable.MySQLEngine;
import sqlancer.mysql.ast.MySQLConstant;
public class MySQLSchema extends AbstractSchema<MySQLTable> {
private static final int NR_SCHEMA_READ_TRIES = 10;
public enum MySQLDataType {
INT, VARCHAR, FLOAT, DOUBLE, DECIMAL;
public static MySQLDataType getRandom(MySQLGlobalState globalState) {
if (globalState.usesPQS()) {
return Randomly.fromOptions(MySQLDataType.INT, MySQLDataType.VARCHAR);
} else {
return Randomly.fromOptions(values());
}
}
public boolean isNumeric() {
switch (this) {
case INT:
case DOUBLE:
case FLOAT:
case DECIMAL:
return true;
case VARCHAR:
return false;
default:
throw new AssertionError(this);
}
}
}
public static class MySQLColumn extends AbstractTableColumn<MySQLTable, MySQLDataType> {
private final boolean isPrimaryKey;
private final int precision;
public enum CollateSequence {
NOCASE, RTRIM, BINARY;
public static CollateSequence random() {
return Randomly.fromOptions(values());
}
}
public MySQLColumn(String name, MySQLDataType columnType, boolean isPrimaryKey, int precision) {
super(name, null, columnType);
this.isPrimaryKey = isPrimaryKey;
this.precision = precision;
}
public int getPrecision() {
return precision;
}
public boolean isPrimaryKey() {
return isPrimaryKey;
}
}
public static class MySQLTables extends AbstractTables<MySQLTable, MySQLColumn> {
public MySQLTables(List<MySQLTable> tables) {
super(tables);
}
public MySQLRowValue getRandomRowValue(Connection con) throws SQLException {
String randomRow = String.format("SELECT %s FROM %s ORDER BY RAND() LIMIT 1", columnNamesAsString(
c -> c.getTable().getName() + "." + c.getName() + " AS " + c.getTable().getName() + c.getName()),
// columnNamesAsString(c -> "typeof(" + c.getTable().getName() + "." +
// c.getName() + ")")
tableNamesAsString());
Map<MySQLColumn, MySQLConstant> values = new HashMap<>();
try (Statement s = con.createStatement()) {
ResultSet randomRowValues = s.executeQuery(randomRow);
if (!randomRowValues.next()) {
throw new AssertionError("could not find random row! " + randomRow + "\n");
}
for (int i = 0; i < getColumns().size(); i++) {
MySQLColumn column = getColumns().get(i);
Object value;
int columnIndex = randomRowValues.findColumn(column.getTable().getName() + column.getName());
assert columnIndex == i + 1;
MySQLConstant constant;
if (randomRowValues.getString(columnIndex) == null) {
constant = MySQLConstant.createNullConstant();
} else {
switch (column.getType()) {
case INT:
value = randomRowValues.getLong(columnIndex);
constant = MySQLConstant.createIntConstant((long) value);
break;
case VARCHAR:
value = randomRowValues.getString(columnIndex);
constant = MySQLConstant.createStringConstant((String) value);
break;
default:
throw new AssertionError(column.getType());
}
}
values.put(column, constant);
}
assert !randomRowValues.next();
return new MySQLRowValue(this, values);
}
}
}
private static MySQLDataType getColumnType(String typeString) {
switch (typeString) {
case "tinyint":
case "smallint":
case "mediumint":
case "int":
case "bigint":
return MySQLDataType.INT;
case "varchar":
case "tinytext":
case "mediumtext":
case "text":
case "longtext":
return MySQLDataType.VARCHAR;
case "double":
return MySQLDataType.DOUBLE;
case "float":
return MySQLDataType.FLOAT;
case "decimal":
return MySQLDataType.DECIMAL;
default:
throw new AssertionError(typeString);
}
}
public static class MySQLRowValue extends AbstractRowValue<MySQLTables, MySQLColumn, MySQLConstant> {
MySQLRowValue(MySQLTables tables, Map<MySQLColumn, MySQLConstant> values) {
super(tables, values);
}
}
public static class MySQLTable extends AbstractTable<MySQLColumn, MySQLIndex> {
public enum MySQLEngine {
INNO_DB("InnoDB"), MY_ISAM("MyISAM"), MEMORY("MEMORY"), HEAP("HEAP"), CSV("CSV"), MERGE("MERGE"),
ARCHIVE("ARCHIVE"), FEDERATED("FEDERATED");
private String s;
MySQLEngine(String s) {
this.s = s;
}
public static MySQLEngine get(String val) {
return Stream.of(values()).filter(engine -> engine.s.equalsIgnoreCase(val)).findFirst().get();
}
}
private final MySQLEngine engine;
public MySQLTable(String tableName, List<MySQLColumn> columns, List<MySQLIndex> indexes, MySQLEngine engine) {
super(tableName, columns, indexes, false /* TODO: support views */);
this.engine = engine;
}
public MySQLEngine getEngine() {
return engine;
}
public boolean hasPrimaryKey() {
return getColumns().stream().anyMatch(c -> c.isPrimaryKey());
}
}
public static final class MySQLIndex extends TableIndex {
private MySQLIndex(String indexName) {
super(indexName);
}
public static MySQLIndex create(String indexName) {
return new MySQLIndex(indexName);
}
@Override
public String getIndexName() {
if (super.getIndexName().contentEquals("PRIMARY")) {
return "`PRIMARY`";
} else {
return super.getIndexName();
}
}
}
public static MySQLSchema fromConnection(Connection con, String databaseName) throws SQLException {
Exception ex = null;
/* the loop is a workaround for https://bugs.mysql.com/bug.php?id=95929 */
for (int i = 0; i < NR_SCHEMA_READ_TRIES; i++) {
try {
List<MySQLTable> databaseTables = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery(
"select TABLE_NAME, ENGINE from information_schema.TABLES where table_schema = '"
+ databaseName + "';")) {
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
String tableEngineStr = rs.getString("ENGINE");
MySQLEngine engine = MySQLEngine.get(tableEngineStr);
List<MySQLColumn> databaseColumns = getTableColumns(con, tableName, databaseName);
List<MySQLIndex> indexes = getIndexes(con, tableName, databaseName);
MySQLTable t = new MySQLTable(tableName, databaseColumns, indexes, engine);
for (MySQLColumn c : databaseColumns) {
c.setTable(t);
}
databaseTables.add(t);
}
}
}
return new MySQLSchema(databaseTables);
} catch (SQLIntegrityConstraintViolationException e) {
ex = e;
}
}
throw new AssertionError(ex);
}
private static List<MySQLIndex> getIndexes(Connection con, String tableName, String databaseName)
throws SQLException {
List<MySQLIndex> indexes = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery(String.format(
"SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME='%s';",
databaseName, tableName))) {
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
indexes.add(MySQLIndex.create(indexName));
}
}
}
return indexes;
}
private static List<MySQLColumn> getTableColumns(Connection con, String tableName, String databaseName)
throws SQLException {
List<MySQLColumn> columns = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery("select * from information_schema.columns where table_schema = '"
+ databaseName + "' AND TABLE_NAME='" + tableName + "'")) {
while (rs.next()) {
String columnName = rs.getString("COLUMN_NAME");
String dataType = rs.getString("DATA_TYPE");
int precision = rs.getInt("NUMERIC_PRECISION");
boolean isPrimaryKey = rs.getString("COLUMN_KEY").equals("PRI");
MySQLColumn c = new MySQLColumn(columnName, getColumnType(dataType), isPrimaryKey, precision);
columns.add(c);
}
}
}
return columns;
}
public MySQLSchema(List<MySQLTable> databaseTables) {
super(databaseTables);
}
public MySQLTables getRandomTableNonEmptyTables() {
return new MySQLTables(Randomly.nonEmptySubset(getDatabaseTables()));
}
}
| 36.943333
| 122
| 0.55716
|
c5878c612beb703ac9d3731986c3a4b3490fb285
| 22,962
|
/*
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.idrsolutions.com
* Help section for developers at http://www.idrsolutions.com/support/
*
* (C) Copyright 1997-2015 IDRsolutions and Contributors.
*
* This file is part of JPedal/JPDF2HTML5
*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* ---------------
* DecoderOptions.java
* ---------------
*/
package org.jpedal.parser;
import org.jpedal.display.*;
import org.jpedal.constants.JPedalSettings;
import org.jpedal.exception.PdfException;
import org.jpedal.external.JPedalHelper;
import org.jpedal.fonts.objects.FontData;
import org.jpedal.grouping.PdfGroupingAlgorithms;
import org.jpedal.objects.PdfData;
import org.jpedal.objects.PdfPageData;
import org.jpedal.parser.text.Tj;
import org.jpedal.render.*;
import org.jpedal.utils.LogWriter;
import java.awt.*;
import java.util.Map;
public class DecoderOptions {
/**
* version number
*/
@SuppressWarnings("UnusedDeclaration")
public static float javaVersion;
/**
* The transparency of the highlighting box around the text stored as a
* float
*/
public static float highlightComposite = 0.35f;
//Show onscreen mouse dragged box
public static boolean showMouseBox;
/**
* flag to enable popup of error messages in JPedal
*/
public static boolean showErrorMessages;
/**
* flag to show if on mac so we can code around certain bugs
*/
public static boolean isRunningOnMac;
public static boolean isRunningOnWindows;
public static boolean isRunningOnAIX;
public static boolean isRunningOnLinux;
/**
* flag to tell software to embed x point after each character so we can
* merge any overlapping text together
*/
public static boolean embedWidthData;
//allow user to override code
@SuppressWarnings("CanBeFinal")
public static JPedalHelper Helper;//new org.jpedal.examples.ExampleHelper();
/**amount we scroll screen to make visible*/
public int scrollInterval=10;
/**
* work out machine type so we can call OS X code to get around Java bugs.
*/
static {
/**
* see if mac
*/
try {
final String name = System.getProperty("os.name");
if (name.equals("Mac OS X")) {
DecoderOptions.isRunningOnMac = true;
} else if (name.startsWith("Windows")) {
DecoderOptions.isRunningOnWindows = true;
}else if (name.startsWith("AIX")) {
DecoderOptions.isRunningOnAIX = true;
} else {
if (name.equals("Linux")) {
DecoderOptions.isRunningOnLinux = true;
}
}
} catch (final Exception e) {
//tell user and log
if(LogWriter.isOutput()) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
//
}
}
private int alignment=Display.DISPLAY_LEFT_ALIGNED;
/**allow for inset of display*/
public int insetW;
public int insetH;
private boolean useHiResImageForDisplay = true;
private boolean useAcceleration=true;
private PageOffsets currentOffset;
/**copy of flag to tell program whether to create
* (and possibly update) screen display
*/
private boolean renderPage;
/**Set default page Layout*/
private int pageMode = Display.SINGLE_PAGE;
/**
* The colour of the highlighting box around the text
*/
public static Color highlightColor = new Color(10,100,170);
/**
* The colour of the text once highlighted
*/
public static Color backgroundColor;
Color nonDrawnPageColor=Color.WHITE;
/**display mode (continuous, facing, single)*/
private int displayView=Display.SINGLE_PAGE;
/**
* page colour for PDF background
*/
public Color altPageColor=Color.WHITE;
public Color altTextColor;
public Color altDisplayBackground;
public int altColorThreshold=255;
boolean changeTextAndLine;
//non-static version
private Integer instance_bestQualityMaxScaling;
private int[] instance_formsNoPrint;
private static int[] formsNoPrint;
//page size for extraction
private static String[] extactionPageSize;
//non-static version
private String[] instance_extactionPageSize;
//page size override
private static Boolean overridePageSize;
//non-static version
private Boolean instance_overridePageSize;
//non-static version
private Boolean instance_allowPagesSmallerThanPageSize=Boolean.FALSE;
public boolean isXMLExtraction() {
return isXMLExtraction;
}
public void setXMLExtraction(final boolean XMLExtraction) {
isXMLExtraction = XMLExtraction;
}
/**
* flag to show if data extracted as text or XML
*/
private boolean isXMLExtraction = true;
public void setPageMode(final int mode){
pageMode = mode;
}
public int getPageMode(){
return pageMode;
}
public int getInsetH() {
return insetH;
}
public int getInsetW() {
return insetW;
}
public int getScrollInterval(){
return scrollInterval;
}
public void setScrollInterval(final int scrollInterval){
this.scrollInterval = scrollInterval;
}
/**
* set an inset display so that display will not touch edge of panel*/
public final void setInset(final int width, final int height) {
this.insetW=width;
this.insetH=height;
}
/**
* XML extraction is the default - pure text extraction is much faster
*/
@SuppressWarnings("UnusedDeclaration")
public void useXMLExtraction() {
isXMLExtraction=true;
}
//<start-adobe>
/**
* returns object containing grouped text of last decoded page
* - if no page decoded, a Runtime exception is thrown to warn user
* Please see org.jpedal.examples.text for example code.
*
*/
public PdfGroupingAlgorithms getGroupingObject(final int lastPageDecoded, final PdfData textData, final PdfPageData pageData) throws PdfException {
if(lastPageDecoded==-1){
throw new RuntimeException("No pages decoded - call decodePage(pageNumber) first");
}else{
//PUT BACK when we remove params
//PdfData textData = getPdfData();
if (textData == null) {
return null;
} else {
return new PdfGroupingAlgorithms(textData, pageData, isXMLExtraction);
}
}
}
/**
* returns object containing grouped text from background grouping - Please
* see org.jpedal.examples.text for example code
* @param pdfBackgroundData
*
*/
public PdfGroupingAlgorithms getBackgroundGroupingObject(final PdfData pdfBackgroundData, final PdfPageData pageData) {
if (pdfBackgroundData == null) {
return null;
} else {
return new PdfGroupingAlgorithms(pdfBackgroundData, pageData, isXMLExtraction);
}
}
//<end-adobe>
public void set(final Map values) throws PdfException {
//read values
for (final Object nextKey : values.keySet()) {
//check it is valid
if (nextKey instanceof Integer) {
final Integer key = (Integer) nextKey;
final Object rawValue = values.get(key);
if (key.equals(JPedalSettings.UNDRAWN_PAGE_COLOR)) {
if (rawValue instanceof Integer) {
nonDrawnPageColor = new Color((Integer) rawValue);
} else {
throw new PdfException("JPedalSettings.UNDRAWN_PAGE_COLOR expects a Integer value");
}
} else if (key.equals(JPedalSettings.PAGE_COLOR)) {
if (rawValue instanceof Integer) {
altPageColor = new Color((Integer) rawValue);
} else {
throw new PdfException("JPedalSettings.PAGE_COLOR expects a Integer value");
}
} else if (key.equals(JPedalSettings.TEXT_COLOR)) {
if (rawValue instanceof Integer) {
altTextColor = new Color((Integer) rawValue);
} else {
throw new PdfException("JPedalSettings.TEXT_COLOR expects a Integer value");
}
} else if (key.equals(JPedalSettings.REPLACEMENT_COLOR_THRESHOLD)) {
if (rawValue instanceof Integer) {
altColorThreshold = ((Integer) rawValue);
} else {
throw new PdfException("JPedalSettings.TEXT_COLOR expects a Integer value");
}
} else if (key.equals(JPedalSettings.DISPLAY_BACKGROUND)) {
if (rawValue instanceof Integer) {
altDisplayBackground = new Color((Integer) rawValue);
} else {
throw new PdfException("JPedalSettings.TEXT_COLOR expects a Integer value");
}
} else if (key.equals(JPedalSettings.CHANGE_LINEART)) {
if (rawValue instanceof Boolean) {
changeTextAndLine = (Boolean) rawValue;
} else {
throw new PdfException("JPedalSettings.CHANGE_LINEART expects a Boolean value");
}
} else if (key.equals(JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING)) {
if (rawValue instanceof Integer) {
instance_bestQualityMaxScaling = (Integer) rawValue;
} else {
throw new PdfException("JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING expects a Integer value");
}
} else if (key.equals(JPedalSettings.EXTRACT_AT_PAGE_SIZE)) {
if (rawValue instanceof String[]) {
instance_extactionPageSize = (String[]) rawValue;
} else {
throw new PdfException("JPedalSettings.EXTRACT_AT_PAGE_SIZE expects a String[] value");
}
} else if (key.equals(JPedalSettings.IGNORE_FORMS_ON_PRINT)) {
if (rawValue instanceof int[]) {
instance_formsNoPrint = (int[]) rawValue;
} else {
throw new PdfException("JPedalSettings.IGNORE_FORMS_ON_PRINT expects a int[] value");
}
} else if (key.equals(JPedalSettings.PAGE_SIZE_OVERRIDES_IMAGE)) {
if (rawValue instanceof Boolean) {
instance_overridePageSize = (Boolean) rawValue;
} else {
throw new PdfException("JPedalSettings.EXTRACT_AT_PAGE_SIZE expects a Boolean value");
}
} else if (key.equals(JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE)) {
if (rawValue instanceof Boolean) {
instance_allowPagesSmallerThanPageSize = (Boolean) rawValue;
} else {
throw new PdfException("JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE expects a Boolean value");
}
//expansion room here
} else //all static values
{
setParameter(values, nextKey);
}
} else {
throw new PdfException("Unknown or unsupported key (not Integer) " + nextKey);
}
}
}
private static void setParameter(final Map values, final Object nextKey) throws PdfException {
//check it is valid
if(nextKey instanceof Integer){
final Integer key=(Integer) nextKey;
final Object rawValue=values.get(key);
if(key.equals(JPedalSettings.INVERT_HIGHLIGHT)){
//set mode if valid
if(rawValue instanceof Boolean){
SwingDisplay.invertHighlight = (Boolean) rawValue;
}else {
throw new PdfException("JPedalSettings.INVERT_HIGHLIGHT expects an Boolean value");
}
}else if(key.equals(JPedalSettings.TEXT_INVERTED_COLOUR)){
//set colour if valid
if(rawValue instanceof Color) {
backgroundColor = (Color) rawValue;
} else {
throw new PdfException("JPedalSettings.TEXT_INVERTED_COLOUR expects a Color value");
}
}else if(key.equals(JPedalSettings.TEXT_HIGHLIGHT_COLOUR)){
//set colour if valid
if(rawValue instanceof Color) {
highlightColor = (Color) rawValue;
} else {
throw new PdfException("JPedalSettings.TEXT_HIGHLIGHT_COLOUR expects a Color value");
}
}else if(key.equals(JPedalSettings.TEXT_PRINT_NON_EMBEDDED_FONTS)){
if(rawValue instanceof Boolean){
PdfStreamDecoder.useTextPrintingForNonEmbeddedFonts = (Boolean)rawValue;
}else {
throw new PdfException("JPedalSettings.TEXT_PRINT_NON_EMBEDDED_FONTS expects a Boolean value");
}
}else if(key.equals(JPedalSettings.DISPLAY_INVISIBLE_TEXT)){
if(rawValue instanceof Boolean){
Tj.showInvisibleText = (Boolean)rawValue;
}else {
throw new PdfException("JPedalSettings.DISPLAY_INVISIBLE_TEXT expects a Boolean value");
}
}else if(key.equals(JPedalSettings.CACHE_LARGE_FONTS)){
if(rawValue instanceof Integer){
FontData.maxSizeAllowedInMemory = (Integer)rawValue;
}else {
throw new PdfException("JPedalSettings.CACHE_LARGE_FONTS expects an Integer value");
}
}else if(key.equals(JPedalSettings.IMAGE_HIRES)){
//<start-adobe><end-adobe>
}else if(key.equals(JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING)){
if(rawValue instanceof Integer){
PDFtoImageConvertor.bestQualityMaxScaling = (Integer) rawValue;
}else {
throw new PdfException("JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING expects a Integer value");
}
//expansion room here
}else if(key.equals(JPedalSettings.EXTRACT_AT_PAGE_SIZE)){
if(rawValue instanceof String[]){
extactionPageSize = (String[]) rawValue;
}else {
throw new PdfException("JPedalSettings.EXTRACT_AT_PAGE_SIZE expects a String[] value");
}
//expansion room here
}else if(key.equals(JPedalSettings.PAGE_SIZE_OVERRIDES_IMAGE)){
if(rawValue instanceof Boolean){
overridePageSize = (Boolean) rawValue;
}else {
throw new PdfException("JPedalSettings.EXTRACT_AT_PAGE_SIZE expects a Boolean value");
}
//expansion room here
}else if(key.equals(JPedalSettings.IGNORE_FORMS_ON_PRINT)){
if(rawValue instanceof int[]){
formsNoPrint = (int[]) rawValue;
}else {
throw new PdfException("JPedalSettings.IGNORE_FORMS_ON_PRINT expects a int[] value");
}
}else if(key.equals(JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE)){
if(rawValue instanceof Boolean){
PDFtoImageConvertor.allowPagesSmallerThanPageSize = (Boolean) rawValue;
}else {
throw new PdfException("JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE expects a Boolean value");
}
}else {
throw new PdfException("Unknown or unsupported key " + key);
}
}else {
throw new PdfException("Unknown or unsupported key (not Integer) " + nextKey);
}
}
public static void modifyJPedalParameters(final Map values) throws PdfException {
//read values
for (final Object nextKey : values.keySet()) {
setParameter(values, nextKey);
}
}
public Color getPageColor() {
return altPageColor;
}
public Color getTextColor() {
return altTextColor;
}
public int getReplacementColorThreshold() {
return altColorThreshold;
}
public Color getDisplayBackgroundColor(){
return altDisplayBackground;
}
public boolean getChangeTextAndLine() {
return changeTextAndLine;
}
public Paint getNonDrawnPageColor() {
return nonDrawnPageColor;
}
public Boolean getInstance_allowPagesSmallerThanPageSize() {
return instance_allowPagesSmallerThanPageSize;
}
public Integer getInstance_bestQualityMaxScaling() {
return instance_bestQualityMaxScaling;
}
public static int[] getFormsNoPrint() {
return formsNoPrint;
}
public int[] getInstance_FormsNoPrint() {
return instance_formsNoPrint;
}
public Boolean getPageSizeToUse() {
Boolean overridePageSizeToUse = Boolean.FALSE;
if(instance_overridePageSize != null) {
overridePageSizeToUse = instance_overridePageSize;
} else if(overridePageSize != null) {
overridePageSizeToUse = overridePageSize;
}
return overridePageSizeToUse;
}
public float getImageDimensions(final int pageIndex, final PdfPageData pageData) {
float multiplyer=-2;
final String overridePageSizeJVM = System.getProperty("org.jpedal.pageSizeOverridesImage");
if (overridePageSizeJVM != null) {
if (instance_overridePageSize != null) {
instance_overridePageSize = Boolean.parseBoolean(overridePageSizeJVM);
} else {
overridePageSize = Boolean.parseBoolean(overridePageSizeJVM);
}
}
final String maxScalingJVM = System.getProperty("org.jpedal.pageMaxScaling");
if(maxScalingJVM != null){
try{
if(instance_bestQualityMaxScaling != null) {
instance_bestQualityMaxScaling = Integer.parseInt(maxScalingJVM);
} else {
PDFtoImageConvertor.bestQualityMaxScaling = Integer.parseInt(maxScalingJVM);
}
}catch(final Exception e){
//tell user and log
if(LogWriter.isOutput()) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
//
}
}
String[] dims=null;
final String dimsJVM=System.getProperty("org.jpedal.pageSize");
if(dimsJVM!=null) {
dims = dimsJVM.split("x");
}
if(dims==null){
if(instance_extactionPageSize!=null) {
dims = instance_extactionPageSize;
} else {
dims = extactionPageSize;
}
}
// prefered size of the extracted page
float prefWidth = 0, prefHeight = 0;
// parse values as ints, if any issues let know that prarameters are invalid
if(dims!=null){
if(dims.length==2){
if(pageData.getRotation(pageIndex)==90 || pageData.getRotation(pageIndex)==270){
prefWidth = Float.parseFloat(dims[1]);
prefHeight = Float.parseFloat(dims[0]);
}else{
prefWidth = Float.parseFloat(dims[0]);
prefHeight = Float.parseFloat(dims[1]);
}
}else{
throw new RuntimeException("Invalid parameters in JVM option -DpageSize ");
}
}
float dScaleW = 0;
final float dScaleH;
if(dims!=null){
//Work out scalings for -DpageSize
final float crw = pageData.getCropBoxWidth2D(pageIndex);
final float crh = pageData.getCropBoxHeight2D(pageIndex);
dScaleW = prefWidth/crw;
dScaleH = prefHeight/crh;
if(dScaleH<dScaleW) {
dScaleW = dScaleH;
}
}
final Boolean overridePageSizeToUse = getPageSizeToUse();
if(dims!=null && overridePageSizeToUse){
multiplyer = dScaleW;
}
return multiplyer;
}
public boolean getRenderPage() {
return renderPage;
}
public void setRenderPage(final boolean newRender) {
renderPage=newRender;
}
public boolean useHardwareAcceleration() {
return useAcceleration;
}
public void useHardwareAcceleration(final boolean newValue) {
useAcceleration=newValue;
}
public boolean useHiResImageForDisplay() {
return useHiResImageForDisplay;
}
public void useHiResImageForDisplay(final boolean value) {
useHiResImageForDisplay=value;
}
public int getPageAlignment() {
return alignment;
}
public void setPageAlignment(final int orientation) {
alignment=orientation;
}
public void setDisplayView(final int displayView) {
this.displayView=displayView;
}
public int getDisplayView() {
return displayView;
}
public PageOffsets getCurrentOffsets() {
return currentOffset;
}
public void setCurrentOffsets(final PageOffsets newOffset) {
currentOffset= newOffset;
}
}
| 31.071719
| 151
| 0.589931
|
94ebd3fe297496aea4f2f00b855efe387aa93c53
| 324
|
package proyecto.modelo.dao;
import java.util.ArrayList;
import proyecto.modelo.entidades.Corte;
public interface CorteDAO {
public Corte conseguirCorte(int id);
public ArrayList<Corte> conseguirCortes();
public int agregarCorte(Corte corte);
public int editarCorte(Corte corte);
public int eliminarCorta(int id);
}
| 23.142857
| 43
| 0.79321
|
a1466840c1d56fa25741b36198974c250ebbc3f4
| 685
|
package org.ice1000.textseq.impl;
import org.ice1000.textseq.TextSequence;
import org.jetbrains.annotations.NotNull;
import java.util.LinkedList;
import java.util.List;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class LinkedListTextSequence extends LinkedList<Character> implements ListTextSequence {
public LinkedListTextSequence() {
}
public LinkedListTextSequence(@NotNull List<@NotNull Character> characters) {
super(characters);
}
@Override
public @NotNull TextSequence subSequence(int start, int end) {
return new LinkedListTextSequence(subList(start, end));
}
@Override
public @NotNull String toString() {
return String.join("", this);
}
}
| 24.464286
| 101
| 0.776642
|
fd4b1fa42bb317b68bcffa7d47c42068bcba6b25
| 9,726
|
/*
* This file was automatically generated by EvoSuite
* Fri Aug 24 14:42:15 GMT 2018
*/
package wheel.asm;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.junit.runner.RunWith;
import wheel.asm.AnnotationVisitor;
import wheel.asm.Attribute;
import wheel.asm.ByteVector;
import wheel.asm.ClassWriter;
import wheel.asm.FieldWriter;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class FieldWriter_ESTest extends FieldWriter_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.9502705392332347
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
String[] stringArray0 = new String[2];
stringArray0[0] = "";
stringArray0[1] = "*?d9Y";
classWriter0.visit(0, 3, "*?d9Y", "*?d9Y", "", stringArray0);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-879), "", "org.apache.commons.io.filefilter.CanWriteFileFilter", "", "");
fieldWriter0.getSize();
fieldWriter0.visitEnd();
}
/**
//Test case number: 1
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, 0, "", " pB{SUx+X2m<#t\"(", "HNA&M%RK8r?+", "");
FieldWriter fieldWriter1 = new FieldWriter(classWriter0, 2, "", "?4D.JIC,pY5)7cL^a", "HNA&M%RK8r?+", "");
FieldWriter fieldWriter2 = fieldWriter1.next;
// Undeclared exception!
try {
fieldWriter1.put((ByteVector) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("wheel.asm.FieldWriter", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=0.9502705392332347
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(2387);
classWriter0.newNameType("bQ", "bQ");
Object object0 = new Object();
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, 185, ":EJ", "LYU", ":EJ", "bQ");
fieldWriter0.visitEnd();
AnnotationVisitor annotationVisitor0 = fieldWriter0.visitAnnotation("", true);
AnnotationVisitor annotationVisitor1 = fieldWriter0.visitAnnotation("char", false);
assertNotSame(annotationVisitor1, annotationVisitor0);
}
/**
//Test case number: 3
/*Coverage entropy=1.2153881010836147
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-879), "", "org.apache.commons.io.filefilter.CanWriteFileFilter", "", "");
ByteVector byteVector0 = classWriter0.pool;
fieldWriter0.put(byteVector0);
fieldWriter0.visitAnnotation("", false);
fieldWriter0.getSize();
fieldWriter0.visitEnd();
fieldWriter0.put(byteVector0);
fieldWriter0.put(byteVector0);
}
/**
//Test case number: 4
/*Coverage entropy=1.277034259466139
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(369);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, 369, "CSH``8j&!06.{@<Nw", "CSH``8j&!06.{@<Nw", "v}^]Ix|;Mf2|$K", "v}^]Ix|;Mf2|$K");
Attribute attribute0 = new Attribute("CSH``8j&!06.{@<Nw");
byte[] byteArray0 = new byte[5];
byteArray0[0] = (byte)0;
fieldWriter0.getSize();
byteArray0[1] = (byte)0;
byteArray0[2] = (byte) (-70);
ByteVector byteVector0 = classWriter0.pool;
fieldWriter0.put(byteVector0);
fieldWriter0.visitEnd();
int int0 = fieldWriter0.getSize();
assertEquals(24, int0);
}
/**
//Test case number: 5
/*Coverage entropy=0.410116318288409
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(3477);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, 1914, "wheel.asm.FieldWriter", "/IAJ3h_kBzt*CnJh!", (String) null, (Object) null);
Object object0 = new Object();
fieldWriter0.getSize();
FieldWriter fieldWriter1 = null;
try {
fieldWriter1 = new FieldWriter(classWriter0, 3477, "", "?4D.JIC,pY5)7cL^a", "", object0);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// value java.lang.Object@2f219056
//
verifyException("wheel.asm.ClassWriter", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=1.242453324894
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-704), "", "dI!", (String) null, (Object) null);
ByteVector byteVector0 = classWriter0.pool;
fieldWriter0.put(byteVector0);
fieldWriter0.visitEnd();
int int0 = fieldWriter0.getSize();
assertEquals(20, int0);
}
/**
//Test case number: 7
/*Coverage entropy=1.1534547943999287
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-879), "", "org.apache.commons.io.filefilter.CanWriteFileFilter", "", "");
ByteVector byteVector0 = new ByteVector();
fieldWriter0.put(byteVector0);
Attribute attribute0 = new Attribute("");
fieldWriter0.visitAttribute(attribute0);
fieldWriter0.visitEnd();
// Undeclared exception!
try {
fieldWriter0.getSize();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("wheel.asm.Attribute", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=1.2636256721237273
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(0);
classWriter0.newConstItem("");
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-879), "", "org.apache.commons.io.filefilter.CanWriteFileFilter", "", "");
ByteVector byteVector0 = classWriter0.pool;
fieldWriter0.put(byteVector0);
fieldWriter0.visitAnnotation("", true);
fieldWriter0.getSize();
fieldWriter0.visitEnd();
fieldWriter0.put(byteVector0);
fieldWriter0.put(byteVector0);
}
/**
//Test case number: 9
/*Coverage entropy=1.0042424730540764
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(369);
String[] stringArray0 = new String[5];
stringArray0[0] = "CA2G3";
stringArray0[1] = "g1+gt.{'b";
stringArray0[2] = "Z4dX.1@r LJ-#=x{";
stringArray0[3] = "M~&f;%EjO3XH%WMvGai";
stringArray0[4] = "Z4dX.1@r LJ-#=x{";
classWriter0.visit(369, 369, "Z4dX.1@r LJ-#=x{", "CA2G3", "g1+gt.{'b", stringArray0);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FieldWriter fieldWriter0 = new FieldWriter(classWriter0, (-2638), "]-`J/p", "Label offset position has not been resolved yet", "The array of names must not be null", "g1+gt.{'b");
ClassWriter classWriter1 = new ClassWriter(48);
ByteVector byteVector0 = classWriter1.pool;
fieldWriter0.put(byteVector0);
FieldWriter fieldWriter1 = classWriter0.lastField;
fieldWriter1.getSize();
Object object0 = new Object();
Object object1 = new Object();
FieldWriter fieldWriter2 = null;
try {
fieldWriter2 = new FieldWriter(classWriter1, 1313, "g1+gt.{'b", "Z4dX.1@r LJ-#=x{", "Label offset position has not been resolved yet", object1);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// value java.lang.Object@e93334f
//
verifyException("wheel.asm.ClassWriter", e);
}
}
/**
//Test case number: 10
/*Coverage entropy=1.0751393240053733
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
ClassWriter classWriter0 = new ClassWriter(369);
ClassWriter classWriter1 = new ClassWriter(369);
ClassWriter classWriter2 = new ClassWriter((-3001));
FieldWriter fieldWriter0 = new FieldWriter(classWriter2, 37, "java/lang/Object", "java/lang/Object", "K/)6*2ho +", "K/)6*2ho +");
fieldWriter0.getSize();
Object object0 = new Object();
Object object1 = new Object();
ByteVector byteVector0 = classWriter2.pool;
Attribute attribute0 = new Attribute("K/)6*2ho +");
fieldWriter0.visitAttribute(attribute0);
// Undeclared exception!
try {
fieldWriter0.put(byteVector0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("wheel.asm.Attribute", e);
}
}
}
| 36.701887
| 185
| 0.656591
|
4c82bf24c727dad9959a50ba5ea181eb349e551a
| 8,372
|
/*************************************************************************
* *
* EJBCA Community: The OpenSource Certificate Authority *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.ejbca.ui.web.admin.approval;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.cesecore.authentication.tokens.AuthenticationToken;
import org.cesecore.authorization.AuthorizationDeniedException;
import org.ejbca.core.model.approval.AdminAlreadyApprovedRequestException;
import org.ejbca.core.model.approval.Approval;
import org.ejbca.core.model.approval.ApprovalDataVO;
import org.ejbca.core.model.approval.ApprovalException;
import org.ejbca.core.model.approval.ApprovalRequest;
import org.ejbca.core.model.approval.ApprovalRequestExecutionException;
import org.ejbca.core.model.approval.ApprovalRequestExpiredException;
import org.ejbca.core.model.approval.SelfApprovalException;
import org.ejbca.core.model.authorization.AccessRulesConstants;
import org.ejbca.core.model.ra.RAAuthorization;
import org.ejbca.core.model.util.EjbLocalHelper;
import org.ejbca.ui.web.admin.BaseManagedBean;
import org.ejbca.ui.web.admin.configuration.EjbcaJSFHelper;
import org.ejbca.ui.web.admin.configuration.EjbcaWebBean;
import org.ejbca.util.query.ApprovalMatch;
import org.ejbca.util.query.BasicMatch;
import org.ejbca.util.query.IllegalQueryException;
import org.ejbca.util.query.Query;
/**
* Session scoped bean for displaying information about an approval request.
*
* @version $Id: ApproveActionManagedBean.java 22858 2016-02-24 15:41:56Z mikekushner $
*/
public class ApproveActionManagedBean extends BaseManagedBean {
private static final long serialVersionUID = 1940920496104779323L;
private static final Logger log = Logger.getLogger(ApproveActionManagedBean.class);
private final EjbLocalHelper ejb = new EjbLocalHelper();
private String comment = "";
private ApprovalDataVOView approveRequestData = new ApprovalDataVOView();
private HashMap<Integer, String> statustext = null;
public HashMap<Integer, String> getStatusText(){
if(statustext == null){
EjbcaWebBean ejbcawebbean = EjbcaJSFHelper.getBean().getEjbcaWebBean();
statustext = new HashMap<Integer, String>();
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_WAITINGFORAPPROVAL), ejbcawebbean.getText("WAITING", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_EXPIRED), ejbcawebbean.getText("EXPIRED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED), ejbcawebbean.getText("EXPIREDANDNOTIFIED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_EXECUTED), ejbcawebbean.getText("EXECUTED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_APPROVED), ejbcawebbean.getText("APPROVED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_REJECTED), ejbcawebbean.getText("REJECTED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_EXECUTIONFAILED), ejbcawebbean.getText("EXECUTIONFAILED", true));
statustext.put(Integer.valueOf(ApprovalDataVO.STATUS_EXECUTIONDENIED), ejbcawebbean.getText("EXECUTIONDENIED", true));
}
return statustext;
}
public ApprovalDataVOView getApproveRequestData() {
return approveRequestData;
}
public boolean isApprovalRequestComparable() {
return approveRequestData.getApproveActionDataVO().getApprovalRequest().getApprovalRequestType() == ApprovalRequest.REQUESTTYPE_COMPARING;
}
public String getWindowWidth(){
if(isApprovalRequestComparable()){
return "1000";
}
return "600";
}
public List<ApprovalView> getApprovalViews() {
List<ApprovalView> approvalViews = new ArrayList<ApprovalView>();
if (approveRequestData != null && approveRequestData.getApproveActionDataVO().getApprovals() != null) {
Iterator<Approval> iter = approveRequestData.getApproveActionDataVO().getApprovals().iterator();
while (iter.hasNext()) {
approvalViews.add(new ApprovalView((Approval) iter.next()));
}
}
return approvalViews;
}
public void setApprovalViews(List<ApprovalView> list){}
public boolean isExistsApprovals(){
return approveRequestData.getApproveActionDataVO().getApprovals().size() >0;
}
public boolean isApprovable(){
if(approveRequestData.getApproveActionDataVO().getStatus() == ApprovalDataVO.STATUS_WAITINGFORAPPROVAL){
return true;
}
return false;
}
public String approve() {
final Approval approval = new Approval(comment);
try {
final AuthenticationToken admin = EjbcaJSFHelper.getBean().getAdmin();
ejb.getApprovalExecutionSession().approve(admin, approveRequestData.getApprovalId(), approval);
updateApprovalRequestData(approveRequestData.getApproveActionDataVO().getId());
} catch (ApprovalRequestExpiredException e) {
addErrorMessage("APPROVALREQUESTEXPIRED");
} catch (ApprovalRequestExecutionException e) {
addErrorMessage("ERROREXECUTINGREQUEST");
} catch (AuthorizationDeniedException e) {
addErrorMessage("AUTHORIZATIONDENIED");
} catch (ApprovalException e) {
addErrorMessage("ERRORHAPPENDWHENAPPROVING");
} catch (AdminAlreadyApprovedRequestException | SelfApprovalException e) {
addErrorMessage(e.getMessage());
}
return "approveaction";
}
public String reject(){
final Approval approval = new Approval(comment);
try {
final AuthenticationToken admin = EjbcaJSFHelper.getBean().getAdmin();
ejb.getApprovalSession().reject(admin, approveRequestData.getApprovalId(), approval);
updateApprovalRequestData(approveRequestData.getApproveActionDataVO().getId());
} catch (ApprovalRequestExpiredException e) {
addErrorMessage("APPROVALREQUESTEXPIRED");
} catch (AuthorizationDeniedException e) {
addErrorMessage("AUTHORIZATIONDENIED");
} catch (ApprovalException e) {
addErrorMessage("ERRORHAPPENDWHENAPPROVING");
} catch (AdminAlreadyApprovedRequestException e) {
addErrorMessage(e.getMessage());
}
return "approveaction";
}
public void setUniqueId(int uniqueId) {
log.debug("ApproveActionSessionBean.setApprovalId setting uniqueId : " + uniqueId);
updateApprovalRequestData(uniqueId);
}
public void updateApprovalRequestData(int id){
Query query = new Query(Query.TYPE_APPROVALQUERY);
query.add(ApprovalMatch.MATCH_WITH_UNIQUEID, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(id));
List<ApprovalDataVO> result;
try {
RAAuthorization raAuthorization = new RAAuthorization(EjbcaJSFHelper.getBean().getAdmin(), ejb.getGlobalConfigurationSession(),
ejb.getAccessControlSession(), ejb.getComplexAccessControlSession(), ejb.getCaSession(), ejb.getEndEntityProfileSession());
result = ejb.getApprovalSession().query( EjbcaJSFHelper.getBean().getAdmin(), query, 0, 1, raAuthorization.getCAAuthorizationString(), raAuthorization.getEndEntityProfileAuthorizationString(AccessRulesConstants.APPROVE_END_ENTITY));
if (result.size() > 0) {
this.approveRequestData = new ApprovalDataVOView(result.get(0));
}
} catch (IllegalQueryException e) {
addErrorMessage("INVALIDQUERY");
} catch (AuthorizationDeniedException e) {
addErrorMessage("AUTHORIZATIONDENIED");
}
}
public String getComment() {
return "";
}
public void setComment(String comment) {
this.comment = comment;
}
}
| 46.511111
| 238
| 0.702819
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.