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
|
---|---|---|---|---|---|
7384835f796ce8b185dde726879275849f34dd5d | 370 | package in.hocg.payment.core.data;
import in.hocg.payment.PaymentResponse;
import in.hocg.payment.sign.SignScheme;
/**
* Created by hocgin on 2019/12/1.
* email: [email protected]
*
* @author hocgin
*/
public class TestResponse extends PaymentResponse {
@Override
public boolean checkSign(SignScheme scheme, String key) {
return true;
}
}
| 19.473684 | 61 | 0.702703 |
bcee704000981776a6610695c2ddbddfa862728b | 469 | package net.rebworks.playlist.watcher.configuration;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
interface Rule {
DayOfWeek getDay();
int getStart();
int getEnd();
int getInterval();
default boolean matches(final LocalDateTime localDateTime) {
return localDateTime.getDayOfWeek().equals(getDay())
&& localDateTime.getHour() >= getStart()
&& localDateTime.getHour() < getEnd();
}
}
| 20.391304 | 64 | 0.654584 |
8ceb200bad516eb11f4dc566a7500737e4c66c41 | 1,860 | /**
* netcell-gui - A Swing GUI for netcell ESB
* Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu
*
* 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 net.segoia.netcell.gui.components;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.List;
import net.segoia.swing.util.shapes.Arrow;
public class JBrokenArrow extends JArrow {
/**
*
*/
private static final long serialVersionUID = 3356557612086486908L;
private List<Point2D> points;
private Color color = Color.black;
public JBrokenArrow(List<Point2D> points) {
this.points = points;
init();
}
public JBrokenArrow(List<Point2D> points, Color c) {
this.points = points;
this.color = c;
init();
}
private void init() {
Point2D headPoint = points.remove(points.size() - 1);
Point2D arrowTailPoint = points.get(points.size() - 1);
arrow = new Arrow(arrowTailPoint, headPoint);
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Point2D prevPoint = points.get(0);
g2.setColor(color);
for (int i = 1; i < points.size(); i++) {
Point2D p = points.get(i);
g2.draw(new Line2D.Double(prevPoint, p));
prevPoint = p;
}
paintArrow(g2);
}
}
| 27.352941 | 77 | 0.697312 |
8eadd9ebfed0071b0c58b8660bbc5656882189e1 | 421 | /**
*
*/
package com.yourpackagename.yourwebproject.service;
import java.util.List;
import com.yourpackagename.framework.data.BaseService;
import com.yourpackagename.yourwebproject.model.entity.GroupContent;
/**
* @author mevan.d.souza
*
*/
public interface GroupContentService extends BaseService<GroupContent, String> {
public List<GroupContent> findByGroupCode(String groupCode, boolean includeExpired);
}
| 21.05 | 85 | 0.790974 |
6786c1938f04562716d2cd7f4559f2a4ebd737bf | 977 | package org.akazakov.common.web.security.impl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
private final Logger log = LogManager.getLogger(Http401UnauthorizedEntryPoint.class);
/**
* Always returns a 401 error code to the client.
*/
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
throws IOException,
ServletException {
log.debug("Pre-authenticated entry point called. Rejecting access");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}
| 32.566667 | 109 | 0.824974 |
765791c7cd35029ae5821498e2c6729abf567e1e | 6,138 | /*
* Copyright 2020 Andrei Pangin
*
* 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 one.jfr;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Parses JFR output produced by async-profiler.
* Note: this class is not supposed to read JFR files produced by other tools.
*/
public class JfrReader implements Closeable {
private static final int
CONTENT_THREAD = 7,
CONTENT_STACKTRACE = 9,
CONTENT_CLASS = 10,
CONTENT_METHOD = 32,
CONTENT_SYMBOL = 33,
CONTENT_STATE = 34,
CONTENT_FRAME_TYPE = 47;
private static final int
EVENT_EXECUTION_SAMPLE = 20;
private final FileChannel ch;
private final ByteBuffer buf;
public final long startNanos;
public final long stopNanos;
public final Map<Integer, Frame[]> stackTraces = new HashMap<>();
public final Map<Long, MethodRef> methods = new HashMap<>();
public final Map<Long, ClassRef> classes = new HashMap<>();
public final Map<Long, byte[]> symbols = new HashMap<>();
public final Map<Integer, byte[]> threads = new HashMap<>();
public final List<Sample> samples = new ArrayList<>();
public JfrReader(String fileName) throws IOException {
this.ch = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ);
this.buf = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
int checkpointOffset = buf.getInt(buf.capacity() - 4);
this.startNanos = buf.getLong(buf.capacity() - 24);
this.stopNanos = buf.getLong(checkpointOffset + 8);
readCheckpoint(checkpointOffset);
readEvents(checkpointOffset);
}
@Override
public void close() throws IOException {
ch.close();
}
private void readEvents(int checkpointOffset) {
buf.position(16);
while (buf.position() < checkpointOffset) {
int size = buf.getInt();
int type = buf.getInt();
if (type == EVENT_EXECUTION_SAMPLE) {
long time = buf.getLong();
int tid = buf.getInt();
int stackTraceId = (int) buf.getLong();
short threadState = buf.getShort();
samples.add(new Sample(time, tid, stackTraceId, threadState));
} else {
buf.position(buf.position() + size - 8);
}
}
Collections.sort(samples);
}
private void readCheckpoint(int checkpointOffset) {
buf.position(checkpointOffset + 24);
readFrameTypes();
readThreadStates();
readStackTraces();
readMethods();
readClasses();
readSymbols();
readThreads();
}
private void readFrameTypes() {
int count = getTableSize(CONTENT_FRAME_TYPE);
for (int i = 0; i < count; i++) {
buf.get();
getSymbol();
}
}
private void readThreadStates() {
int count = getTableSize(CONTENT_STATE);
for (int i = 0; i < count; i++) {
buf.getShort();
getSymbol();
}
}
private void readStackTraces() {
int count = getTableSize(CONTENT_STACKTRACE);
for (int i = 0; i < count; i++) {
int id = (int) buf.getLong();
byte truncated = buf.get();
Frame[] frames = new Frame[buf.getInt()];
for (int j = 0; j < frames.length; j++) {
long method = buf.getLong();
int bci = buf.getInt();
byte type = buf.get();
frames[j] = new Frame(method, type);
}
stackTraces.put(id, frames);
}
}
private void readMethods() {
int count = getTableSize(CONTENT_METHOD);
for (int i = 0; i < count; i++) {
long id = buf.getLong();
long cls = buf.getLong();
long name = buf.getLong();
long sig = buf.getLong();
short modifiers = buf.getShort();
byte hidden = buf.get();
methods.put(id, new MethodRef(cls, name, sig));
}
}
private void readClasses() {
int count = getTableSize(CONTENT_CLASS);
for (int i = 0; i < count; i++) {
long id = buf.getLong();
long loader = buf.getLong();
long name = buf.getLong();
short modifiers = buf.getShort();
classes.put(id, new ClassRef(name));
}
}
private void readSymbols() {
int count = getTableSize(CONTENT_SYMBOL);
for (int i = 0; i < count; i++) {
long id = buf.getLong();
byte[] symbol = getSymbol();
symbols.put(id, symbol);
}
}
private void readThreads() {
int count = getTableSize(CONTENT_THREAD);
for (int i = 0; i < count; i++) {
int id = buf.getInt();
byte[] name = getSymbol();
threads.put(id, name);
}
}
private int getTableSize(int contentType) {
if (buf.getInt() != contentType) {
throw new IllegalArgumentException("Expected content type " + contentType);
}
return buf.getInt();
}
private byte[] getSymbol() {
byte[] symbol = new byte[buf.getShort() & 0xffff];
buf.get(symbol);
return symbol;
}
}
| 31.15736 | 87 | 0.578364 |
6b4b86df9618571d1315fb60bd741de7d5c79ced | 4,178 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.asdctool.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openecomp.sdc.asdctool.impl.UpdatePropertyOnVertex;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
public class UpdateIsVnfMenu {
private static Logger log = Logger.getLogger(UpdateIsVnfMenu.class.getName());
private static void usageAndExit() {
updateIsVnfTrueUsage();
System.exit(1);
}
private static void updateIsVnfTrueUsage() {
System.out.println("Usage: updateIsVnfTrue <janusgraph.properties> <systemServiceName1,systemServiceName2,...,systemServiceNameN>");
}
public static void main(String[] args) {
if (args == null || args.length < 1) {
usageAndExit();
}
UpdatePropertyOnVertex updatePropertyOnVertex = new UpdatePropertyOnVertex();
String operation = args[0];
switch (operation.toLowerCase()) {
case "updateisvnftrue":
boolean isValid = verifyParamsLength(args, 3);
if (false == isValid) {
updateIsVnfTrueUsage();
System.exit(1);
}
Map<String, Object> keyValueToSet = new HashMap<>();
keyValueToSet.put(GraphPropertiesDictionary.IS_VNF.getProperty(), true);
List<Map<String, Object>> orCriteria = buildCriteriaFromSystemServiceNames(args[2]);
Integer updatePropertyOnServiceAtLeastCertified = updatePropertyOnVertex
.updatePropertyOnServiceAtLeastCertified(args[1], keyValueToSet, orCriteria);
if (updatePropertyOnServiceAtLeastCertified == null) {
System.exit(2);
} else if (updatePropertyOnServiceAtLeastCertified >= 0) {
log.debug("Number of updated services is {}", updatePropertyOnServiceAtLeastCertified);
System.exit(0);
}
break;
default:
usageAndExit();
}
}
private static List<Map<String, Object>> buildCriteriaFromSystemServiceNames(String systemList) {
List<Map<String, Object>> systemNames = new ArrayList<>();
String[] split = systemList.split(",");
if (split != null) {
for (String systemName : split) {
systemName = systemName.trim();
Map<String, Object> map = new HashMap();
map.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
map.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName());
systemNames.add(map);
}
}
return systemNames;
}
private static boolean verifyParamsLength(String[] args, int i) {
if (args == null) {
if (i > 0) {
return false;
}
return true;
}
if (args.length >= i) {
return true;
}
return false;
}
}
| 40.960784 | 140 | 0.582097 |
fcea456714a3523b37c3527ac87dc89197dbe0f1 | 11,264 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4826774 4926547
* @summary Tests for {Float, Double}.toHexString methods
* @author Joseph D. Darcy
*/
import java.util.regex.*;
import sun.misc.FpUtils;
import sun.misc.DoubleConsts;
public class ToHexString {
private ToHexString() {}
/*
* Given a double value, create a hexadecimal floating-point
* string via an intermediate long hex string.
*/
static String doubleToHexString(double d) {
return hexLongStringtoHexDoubleString(Long.toHexString(Double.doubleToLongBits(d)));
}
/*
* Transform the hexadecimal long output into the equivalent
* hexadecimal double value.
*/
static String hexLongStringtoHexDoubleString(String transString) {
transString = transString.toLowerCase();
String zeros = "";
StringBuffer result = new StringBuffer(24);
for(int i = 0; i < (16 - transString.length()); i++, zeros += "0");
transString = zeros + transString;
// assert transString.length == 16;
char topChar;
// Extract sign
if((topChar=transString.charAt(0)) >= '8' ) {// 8, 9, a, A, b, B, ...
result.append("-");
// clear sign bit
transString =
Character.toString(Character.forDigit(Character.digit(topChar, 16) - 8, 16)) +
transString.substring(1,16);
}
// check for NaN and infinity
String signifString = transString.substring(3,16);
if( transString.substring(0,3).equals("7ff") ) {
if(signifString.equals("0000000000000")) {
result.append("Infinity");
}
else
result.append("NaN");
}
else { // finite value
// Extract exponent
int exponent = Integer.parseInt(transString.substring(0,3), 16) -
DoubleConsts.EXP_BIAS;
result.append("0x");
if (exponent == DoubleConsts.MIN_EXPONENT - 1) { // zero or subnormal
if(signifString.equals("0000000000000")) {
result.append("0.0p0");
}
else {
result.append("0." + signifString.replaceFirst("0+$", "").replaceFirst("^$", "0") +
"p-1022");
}
}
else { // normal value
result.append("1." + signifString.replaceFirst("0+$", "").replaceFirst("^$", "0") +
"p" + exponent);
}
}
return result.toString();
}
public static int toHexStringTests() {
int failures = 0;
String [][] testCases1 = {
{"Infinity", "Infinity"},
{"-Infinity", "-Infinity"},
{"NaN", "NaN"},
{"-NaN", "NaN"},
{"0.0", "0x0.0p0"},
{"-0.0", "-0x0.0p0"},
{"1.0", "0x1.0p0"},
{"-1.0", "-0x1.0p0"},
{"2.0", "0x1.0p1"},
{"3.0", "0x1.8p1"},
{"0.5", "0x1.0p-1"},
{"0.25", "0x1.0p-2"},
{"1.7976931348623157e+308", "0x1.fffffffffffffp1023"}, // MAX_VALUE
{"2.2250738585072014E-308", "0x1.0p-1022"}, // MIN_NORMAL
{"2.225073858507201E-308", "0x0.fffffffffffffp-1022"}, // MAX_SUBNORMAL
{"4.9e-324", "0x0.0000000000001p-1022"} // MIN_VALUE
};
// Compare decimal string -> double -> hex string to hex string
for (int i = 0; i < testCases1.length; i++) {
String result;
if(! (result=Double.toHexString(Double.parseDouble(testCases1[i][0]))).
equals(testCases1[i][1])) {
failures ++;
System.err.println("For floating-point string " + testCases1[i][0] +
", expected hex output " + testCases1[i][1] + ", got " + result +".");
}
}
// Except for float subnormals, the output for numerically
// equal float and double values should be the same.
// Therefore, we will explicitly test float subnormal values.
String [][] floatTestCases = {
{"Infinity", "Infinity"},
{"-Infinity", "-Infinity"},
{"NaN", "NaN"},
{"-NaN", "NaN"},
{"0.0", "0x0.0p0"},
{"-0.0", "-0x0.0p0"},
{"1.0", "0x1.0p0"},
{"-1.0", "-0x1.0p0"},
{"2.0", "0x1.0p1"},
{"3.0", "0x1.8p1"},
{"0.5", "0x1.0p-1"},
{"0.25", "0x1.0p-2"},
{"3.4028235e+38f", "0x1.fffffep127"}, // MAX_VALUE
{"1.17549435E-38f", "0x1.0p-126"}, // MIN_NORMAL
{"1.1754942E-38", "0x0.fffffep-126"}, // MAX_SUBNORMAL
{"1.4e-45f", "0x0.000002p-126"} // MIN_VALUE
};
// Compare decimal string -> double -> hex string to hex string
for (int i = 0; i < floatTestCases.length; i++) {
String result;
if(! (result=Float.toHexString(Float.parseFloat(floatTestCases[i][0]))).
equals(floatTestCases[i][1])) {
failures++;
System.err.println("For floating-point string " + floatTestCases[i][0] +
", expected hex output\n" + floatTestCases[i][1] + ", got\n" + result +".");
}
}
// Particular floating-point values and hex equivalents, mostly
// taken from fdlibm source.
String [][] testCases2 = {
{"+0.0", "0000000000000000"},
{"-0.0", "8000000000000000"},
{"+4.9e-324", "0000000000000001"},
{"-4.9e-324", "8000000000000001"},
// fdlibm k_sin.c
{"+5.00000000000000000000e-01", "3FE0000000000000"},
{"-1.66666666666666324348e-01", "BFC5555555555549"},
{"+8.33333333332248946124e-03", "3F8111111110F8A6"},
{"-1.98412698298579493134e-04", "BF2A01A019C161D5"},
{"+2.75573137070700676789e-06", "3EC71DE357B1FE7D"},
{"-2.50507602534068634195e-08", "BE5AE5E68A2B9CEB"},
{"+1.58969099521155010221e-10", "3DE5D93A5ACFD57C"},
// fdlibm k_cos.c
{"+4.16666666666666019037e-02", "3FA555555555554C"},
{"-1.38888888888741095749e-03", "BF56C16C16C15177"},
{"+2.48015872894767294178e-05", "3EFA01A019CB1590"},
{"-2.75573143513906633035e-07", "BE927E4F809C52AD"},
{"+2.08757232129817482790e-09", "3E21EE9EBDB4B1C4"},
{"-1.13596475577881948265e-11", "BDA8FAE9BE8838D4"},
// fdlibm e_rempio.c
{"1.67772160000000000000e+07", "4170000000000000"},
{"6.36619772367581382433e-01", "3FE45F306DC9C883"},
{"1.57079632673412561417e+00", "3FF921FB54400000"},
{"6.07710050650619224932e-11", "3DD0B4611A626331"},
{"6.07710050630396597660e-11", "3DD0B4611A600000"},
{"2.02226624879595063154e-21", "3BA3198A2E037073"},
{"2.02226624871116645580e-21", "3BA3198A2E000000"},
{"8.47842766036889956997e-32", "397B839A252049C1"},
// fdlibm s_cbrt.c
{"+5.42857142857142815906e-01", "3FE15F15F15F15F1"},
{"-7.05306122448979611050e-01", "BFE691DE2532C834"},
{"+1.41428571428571436819e+00", "3FF6A0EA0EA0EA0F"},
{"+1.60714285714285720630e+00", "3FF9B6DB6DB6DB6E"},
{"+3.57142857142857150787e-01", "3FD6DB6DB6DB6DB7"},
};
// Compare decimal string -> double -> hex string to
// long hex string -> double hex string
for (int i = 0; i < testCases2.length; i++) {
String result;
String expected;
if(! (result=Double.toHexString(Double.parseDouble(testCases2[i][0]))).
equals( expected=hexLongStringtoHexDoubleString(testCases2[i][1]) )) {
failures ++;
System.err.println("For floating-point string " + testCases2[i][0] +
", expected hex output " + expected + ", got " + result +".");
}
}
// Test random double values;
// compare double -> Double.toHexString with local doubleToHexString
java.util.Random rand = new java.util.Random(0);
for (int i = 0; i < 1000; i++) {
String result;
String expected;
double d = rand.nextDouble();
if(! (expected=doubleToHexString(d)).equals(result=Double.toHexString(d)) ) {
failures ++;
System.err.println("For floating-point value " + d +
", expected hex output " + expected + ", got " + result +".");
}
}
return failures;
}
public static void main(String argv[]) {
int failures = 0;
failures = toHexStringTests();
if (failures != 0) {
throw new RuntimeException("" + failures + " failures while testing Double.toHexString");
}
}
}
| 44.521739 | 111 | 0.487837 |
cd0e88065ee97ea0c629f2f1f60d50f83285f4d9 | 1,531 | package com.podio.notification;
import java.util.Collection;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.joda.time.DateTime;
import com.podio.BaseAPI;
import com.podio.ResourceFactory;
import com.podio.common.CSVUtil;
import com.podio.common.Empty;
import com.podio.serialize.DateTimeUtil;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
/**
* A notification is an information about an event that occured in Podio. A
* notification is directed against a single user, and can have a status of
* either unread or viewed. Notifications have a reference to the action that
* caused the notification.
*/
public class NotificationAPI extends BaseAPI {
public NotificationAPI(ResourceFactory resourceFactory) {
super(resourceFactory);
}
/**
* Returns the number of unread notifications
*
* @return The number of unread notifications
*/
public int getInboxNewCount() {
WebResource resource = getResourceFactory().getApiResource(
"/notification/inbox/new/count");
return resource.get(InboxNewCount.class).getNewNotifications();
}
/**
* Mark the notification as viewed. This will move the notification from the
* inbox to the viewed archive.
*
* @param notificationId
* The id of the notification
*/
public void markAsViewed(int notificationId) {
getResourceFactory()
.getApiResource("/notification/" + notificationId + "/viewed")
.entity(new Empty(), MediaType.APPLICATION_JSON_TYPE).post();
}
} | 28.351852 | 77 | 0.751796 |
ff2c50247c4d901056d8e3213a61bd6f6f84d330 | 2,046 | import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 5.6.2018 г.
* Time: 13:28 ч.
*/
public class _007MapDistricts {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] input = console.nextLine()
.split("\\s+");
int minPopulation = Integer.parseInt(console.nextLine());
Map<String, List<Integer>> cityDistricts = new LinkedHashMap<>();
Arrays.stream(input).forEach(s -> {
String[] cityArgs = s.split(":");
String cityName = cityArgs[0];
int districtPopulation = Integer.parseInt(cityArgs[1]);
cityDistricts.putIfAbsent(cityName, new ArrayList<>());
cityDistricts.get(cityName).add(districtPopulation);
});
cityDistricts.entrySet()
.stream()
.filter(c -> {
int population = c.getValue()
.stream()
.mapToInt(Integer::intValue)
.sum();
return population > minPopulation;
})
.sorted((c1, c2) -> {
int population1 = c1.getValue()
.stream()
.mapToInt(Integer::intValue)
.sum();
int population2 = c2.getValue()
.stream()
.mapToInt(Integer::intValue)
.sum();
return Integer.compare(population2, population1);
})
.forEach(c -> {
System.out.print(c.getKey() + ": ");
c.getValue()
.stream()
.sorted(Comparator.reverseOrder())
.limit(5)
.forEach(d -> System.out.print(d + " "));
System.out.println();
});
}
} | 33.540984 | 73 | 0.429619 |
8f2f6ff1a0f53ef812e6ac6a9705b8071d1c983e | 2,384 | package com.vladmihalcea.book.hpjp.hibernate.identifier;
import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import com.vladmihalcea.book.hpjp.util.transaction.*;
import org.junit.Test;
import javax.persistence.*;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
public class PostgreSQLSerialTest extends AbstractPostgreSQLIntegrationTest {
@Override
protected Class<?>[] entities() {
return new Class<?>[] {
Post.class,
};
}
@Override
protected void additionalProperties(Properties properties) {
properties.put("hibernate.jdbc.batch_size", "5");
}
@Test
public void testCurrentValue() {
doInJPA(entityManager -> {
Post post1 = new Post();
post1.setTitle(
"High-Performance Java Persistence, Part 1"
);
entityManager.persist(post1);
Post post2 = new Post();
post2.setTitle(
"High-Performance Java Persistence, Part 2"
);
entityManager.persist(post2);
entityManager.flush();
assertEquals(
2,
(
(Number) entityManager
.createNativeQuery(
"select currval('post_id_seq')")
.getSingleResult()
).intValue()
);
});
}
@Test
public void testBatch() {
doInJPA((JPATransactionVoidFunction)(entityManager -> {
for (int i = 0; i < 3; i++) {
Post post = new Post();
post.setTitle(
String.format("High-Performance Java Persistence, Part %d", i + 1)
);
entityManager.persist(post);
}
}));
}
@Entity(name = "Post")
@Table(name = "post")
public static class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
| 24.57732 | 86 | 0.530621 |
0e747b51f4a2de4d683eefa96db7a97bb9ecf079 | 5,693 | package inpro.synthesis;
import inpro.incremental.unit.PhraseIU;
import inpro.incremental.unit.WordIU;
import inpro.incremental.util.TTSUtil;
import inpro.synthesis.hts.InteractiveHTSEngine;
import inpro.synthesis.hts.PHTSParameterGeneration;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import org.apache.log4j.Logger;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.datatypes.MaryDataType;
import marytts.exceptions.MaryConfigurationException;
import marytts.htsengine.HMMData;
import marytts.htsengine.HMMVoice;
import marytts.modules.ModuleRegistry;
import marytts.modules.synthesis.Voice;
import marytts.server.Request;
import marytts.util.MaryUtils;
public class MaryAdapter5internal extends MaryAdapter {
private MaryInterface maryInterface;
private static Logger logger = Logger.getLogger(MaryAdapter5internal.class);
protected MaryAdapter5internal() {
maryInterface = null;
try {
maryInterface = new LocalMaryInterface();
} catch (MaryConfigurationException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* implement the main inprotk<->marytts interaction via mary's interface.
* (additional data for HMM synthesis is exchanged via subclassing HTSEngine)
*/
@Override
protected ByteArrayOutputStream process(String query, String inputType,
String outputType, String audioType) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MaryDataType input = MaryDataType.get(inputType);
MaryDataType output = MaryDataType.get(outputType);
assert !(inputType.equals("MBROLA") || outputType.equals("MBROLA")) :
"There's no MBROLA support in internalized Mary 5, please use an external Mary 4 server";
Locale mLocale = MaryUtils.string2locale(System.getProperty("inpro.tts.language", "de"));
String voiceName = System.getProperty("inpro.tts.voice", System.getProperty("inpro.tts.voice", "bits1-hsmm"));
maryInterface.setVoice(voiceName);
Voice voice = Voice.getVoice(voiceName);
AudioFormat audioFormat = voice.dbAudioFormat();
audioFormat = new AudioFormat(16000, audioFormat.getSampleSizeInBits(), audioFormat.getChannels(), true, audioFormat.isBigEndian());
assert audioFormat.getSampleRate() == 16000f : "InproTK cannot handle voices with sample rates other than 16000Hz, your's is " + audioFormat.getSampleRate();
logger.debug("audioFormat is " + audioFormat);
logger.debug("query is " + query);
assert voice != null : "Cannot find the Mary voice " + voiceName;
AudioFileFormat.Type audioFileFormatType = AudioFileFormat.Type.WAVE;
logger.trace("audioFileFormatType is " + audioFileFormatType);
AudioFileFormat audioFileFormat = new AudioFileFormat(
audioFileFormatType, audioFormat, AudioSystem.NOT_SPECIFIED);
logger.trace("audioFileFormat is " + audioFileFormat);
Request req = new Request(input, output, mLocale, voice, (String) null,
(String) null, 1, audioFileFormat);
try {
req.setInputData(query);
req.process();
req.writeOutputData(baos);
} catch (Exception e) {
e.printStackTrace();
}
return baos;
}
/** needs to be overridden for IHTSE access */
@Override
public List<PhraseIU> fullySpecifiedMarkup2PhraseIUs(String markup) {
InteractiveHTSEngine ihtse = (InteractiveHTSEngine) ModuleRegistry.getModule(InteractiveHTSEngine.class);
ihtse.resetUttHMMstore();
ihtse.synthesizeAudio = false;
InputStream is = fullySpecifiedMarkup2maryxml(markup);
// useful for looking at Mary's XML (for debugging):
//printStream(is); ihtse.resetUttHMMstore(); is = fullyCompleteMarkup2maryxml(markup);
List<PhraseIU> groundedIn = TTSUtil.phraseIUsFromMaryXML(is, ihtse.getUttData(), true);
return groundedIn;
}
/** needs to be overridden for IHTSE access */
@Override
protected synchronized List<? extends WordIU> text2IUs(String tts, boolean keepPhrases, boolean connectPhrases) {
InteractiveHTSEngine ihtse = (InteractiveHTSEngine) ModuleRegistry.getModule(InteractiveHTSEngine.class);
ihtse.resetUttHMMstore();
ihtse.synthesizeAudio = false;
InputStream is = text2maryxml(tts);
//printStream(is); ihtse.resetUttHMMstore(); is = markup2maryxml(markup);
try {
return createIUsFromInputStream(is, ihtse.getUttData(), keepPhrases, connectPhrases);
} catch (AssertionError ae) {
is = text2maryxml(tts);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String line = null;
try {
while((line = in.readLine()) != null) {
System.err.println(line);
}
} catch (IOException e) { }
throw new RuntimeException(ae);
}
}
public static HMMData getDefaultHMMData() {
String defaultVoiceName = System.getProperty("inpro.tts.voice", System.getProperty("inpro.tts.voice", "bits1-hsmm"));
Voice voice = Voice.getVoice(defaultVoiceName);
assert (voice instanceof HMMVoice);
return ((HMMVoice) voice).getHMMData();
}
public static PHTSParameterGeneration getNewParamGen() {
return new PHTSParameterGeneration(getDefaultHMMData());
}
/** print Mary's XML to stderr */
@SuppressWarnings("unused")
private void printStream(InputStream is) {
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String line = null;
try {
while((line = in.readLine()) != null) {
System.err.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 36.967532 | 159 | 0.753206 |
f9ee4c3a165de092fb9cfdff7288501623d3763e | 3,120 | package net.castlecraftmc.playervaults;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionAttachmentInfo;
public class PlayerVaultsFunctions {
public static List<Player> pendingInventories = new ArrayList<Player>();
public static boolean hasVault(Player p, int vaultNum) {
if (p.hasPermission("playervaults.vault." + String.valueOf(vaultNum))) {
return true;
} else {
return false;
}
}
public static void openVault(Player p, int vaultNum) {
if (hasVault(p, vaultNum)) {
if (!pendingInventories.contains(p)) {
Inventory vault = parseFileToInventory(p, vaultNum);
p.openInventory(vault);
} else {
p.sendMessage("Your Vault is still saving...");
}
}
}
public static Inventory parseFileToInventory(Player p, int vaultNum) {
String uuid = p.getUniqueId().toString();
Inventory vault = Bukkit.createInventory(null, PlayerVaults.getVaultSize(), "Vault " + String.valueOf(vaultNum));
File file = new File(PlayerVaults.getPlugin().getDataFolder().toString() + "/vaults/" + uuid + ".yml");
if(file.exists() && !file.isDirectory()) {
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
if (yaml.contains("vaults." + String.valueOf(vaultNum))) {
ItemStack[] contents = new ItemStack[]{};
for (String key : yaml.getConfigurationSection("vaults." + vaultNum).getKeys(false)) {
vault.setItem(Integer.parseInt(key), yaml.getItemStack("vaults." + vaultNum + "." + key));
}
}
} else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return vault;
}
public static void saveVault(Player p) {
if (p.getOpenInventory() != null && p.getOpenInventory().getTopInventory().getTitle().startsWith("Vault")) {
pendingInventories.add(p);
Inventory inv = p.getOpenInventory().getTopInventory();
File file = new File(PlayerVaults.getPlugin().getDataFolder().toString() + "/vaults/" + p.getUniqueId().toString() + ".yml");
YamlConfiguration vaultFile = YamlConfiguration.loadConfiguration(file);
for (int i = 0; i < PlayerVaults.getVaultSize(); i++) {
ItemStack itemToPut = inv.getItem(i);
if (itemToPut != null && itemToPut.getType() != Material.AIR) {
vaultFile.set("vaults." + inv.getTitle().split(" ")[1] + "." + String.valueOf(i), itemToPut);
} else {
vaultFile.set("vaults." + inv.getTitle().split(" ")[1] + "." + String.valueOf(i), null);
}
}
try {
vaultFile.save(file);
} catch (IOException e1) {
e1.printStackTrace();
}
pendingInventories.remove(p);
}
}
} | 36.27907 | 129 | 0.675 |
55c62ddc59fdc5b49d4e410395cd0b73bd5b5281 | 1,899 | /*
* Copyright 2015 Artem Mironov
*
* 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.jeesy.classinfo;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import static java.util.Arrays.asList;
import static org.jeesy.classinfo.Utils.uncheckedThrow;
/**
* Method information
* @author Artem Mironov
*/
public class MethodInfo extends AnnotatedNode.BaseAnnotatedNode {
private Method method;
private ParameterInfo [] parameters;
MethodInfo(Method m) {
name = m.getName();
method = m;
collectParameters(m);
}
private void collectParameters(Method m) {
}
public Object invoke(Object target, Object ... parameters) {
try {
return method.invoke(target,parameters);
} catch (InvocationTargetException e) {
uncheckedThrow(e.getTargetException());
} catch (IllegalAccessException e) {
uncheckedThrow(e);
}
return null;
}
public static class ParameterInfo<T> extends AnnotatedNode.BaseAnnotatedNode {
private Class<T> type;
private int pos;
public Class<T> getType(){return type;}
public int getPostion() {return pos;}
}
public Method getMethod() {return method;}
}
| 28.772727 | 82 | 0.692996 |
c8e0f2442d79766166cd6cd62bf58236b393e916 | 2,629 | package cn.iocoder.yudao.module.system.dal.mysql.logger;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.logger.vo.operatelog.OperateLogExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.logger.vo.operatelog.OperateLogPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.logger.OperateLogDO;
import org.apache.ibatis.annotations.Mapper;
import java.util.Collection;
import java.util.List;
@Mapper
public interface OperateLogMapper extends BaseMapperX<OperateLogDO> {
default PageResult<OperateLogDO> selectPage(OperateLogPageReqVO reqVO, Collection<Long> userIds) {
LambdaQueryWrapperX<OperateLogDO> query = new LambdaQueryWrapperX<OperateLogDO>()
.likeIfPresent(OperateLogDO::getModule, reqVO.getModule())
.inIfPresent(OperateLogDO::getUserId, userIds)
.eqIfPresent(OperateLogDO::getType, reqVO.getType())
.betweenIfPresent(OperateLogDO::getStartTime, reqVO.getBeginTime(), reqVO.getEndTime());
if (Boolean.TRUE.equals(reqVO.getSuccess())) {
query.eq(OperateLogDO::getResultCode, GlobalErrorCodeConstants.SUCCESS.getCode());
} else if (Boolean.FALSE.equals(reqVO.getSuccess())) {
query.gt(OperateLogDO::getResultCode, GlobalErrorCodeConstants.SUCCESS.getCode());
}
query.orderByDesc(OperateLogDO::getId); // 降序
return selectPage(reqVO, query);
}
default List<OperateLogDO> selectList(OperateLogExportReqVO reqVO, Collection<Long> userIds) {
LambdaQueryWrapperX<OperateLogDO> query = new LambdaQueryWrapperX<OperateLogDO>()
.likeIfPresent(OperateLogDO::getModule, reqVO.getModule())
.inIfPresent(OperateLogDO::getUserId, userIds)
.eqIfPresent(OperateLogDO::getType, reqVO.getType())
.betweenIfPresent(OperateLogDO::getStartTime, reqVO.getBeginTime(), reqVO.getEndTime());
if (Boolean.TRUE.equals(reqVO.getSuccess())) {
query.eq(OperateLogDO::getResultCode, GlobalErrorCodeConstants.SUCCESS.getCode());
} else if (Boolean.FALSE.equals(reqVO.getSuccess())) {
query.gt(OperateLogDO::getResultCode, GlobalErrorCodeConstants.SUCCESS.getCode());
}
query.orderByDesc(OperateLogDO::getId); // 降序
return selectList(query);
}
}
| 53.653061 | 104 | 0.729935 |
b3b53965410cad8f6d4b56e3914c0d9735ecc0d7 | 2,677 | package org.innovateuk.ifs.file.resource;
import com.google.common.collect.Sets;
import java.util.Set;
import static com.google.common.collect.Sets.union;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.joining;
public enum FileTypeCategory {
SPREADSHEET("spreadsheet",
union(MimeTypes.MS_SPREADSHEET, MimeTypes.OPEN_SPREADSHEET),
FileExtensions.SPREADSHEET
),
PDF("PDF",
MimeTypes.PDF,
FileExtensions.PDF
),
DOCUMENT("text document",
union(MimeTypes.MS_DOCUMENT, MimeTypes.OPEN_DOCUMENT),
FileExtensions.DOCUMENT
),
OPEN_DOCUMENT(MimeTypes.OPEN_DOCUMENT),
OPEN_SPREADSHEET(MimeTypes.OPEN_SPREADSHEET);
private String displayName;
private Set<String> mimeTypes;
private Set<String> fileExtensions;
FileTypeCategory(String displayName, Set<String> mimeTypes, Set<String> fileExtensions) {
this.displayName = displayName;
this.mimeTypes = mimeTypes;
this.fileExtensions = fileExtensions;
}
FileTypeCategory(Set<String> mimeTypes) {
this(null, mimeTypes, emptySet());
}
public String getDisplayName() {
return displayName;
}
public Set<String> getMimeTypes() {
return mimeTypes;
}
public Set<String> getFileExtensions() {
return fileExtensions;
}
public String getDisplayMediaTypes() {
return fileExtensions.stream().collect(joining(", "));
}
public static class MimeTypes {
private MimeTypes() {}
public static final Set<String> PDF = singleton("application/pdf");
private static final Set<String> MS_SPREADSHEET =
Sets.newHashSet("application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
private static final Set<String> OPEN_SPREADSHEET = singleton("application/vnd.oasis.opendocument.spreadsheet");
private static final Set<String> MS_DOCUMENT =
Sets.newHashSet("application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
private static final Set<String> OPEN_DOCUMENT = singleton("application/vnd.oasis.opendocument.text");
}
public static class FileExtensions {
private FileExtensions() {}
public static final Set<String> PDF = singleton(".pdf");
private static final Set<String> SPREADSHEET = Sets.newHashSet(".ods", ".xls", ".xlsx");
private static final Set<String> DOCUMENT = Sets.newHashSet(".odt", ".doc", ".docx");
}
}
| 33.049383 | 129 | 0.684722 |
d1997a5c83190b914a9eea93b2d9322c4a97039e | 2,489 | package ru.r2cloud.jradio.siriussat;
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor;
import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import ru.r2cloud.jradio.AssertJson;
import ru.r2cloud.jradio.fec.ViterbiTest;
public class SiriusSatBeaconTest {
@Test
public void testBeacon() throws Exception {
byte[] data = ViterbiTest.hexStringToByteArray("A464829C8C4060A4A66266A6406300F016420200010042008C140212EB0AA60002001B003A000000000004000100070007000600070000200000141F2707000020FA385FBA04070787851F0FF40E21FA385F260700001C00431F");
SiriusSatBeacon result = new SiriusSatBeacon();
result.readBeacon(data);
AssertJson.assertObjectsEqual("SiriusSatBeacon-short.json", result);
}
@Test
public void testUnknownBeacon() throws Exception {
byte[] data = ViterbiTest.hexStringToByteArray(
"A464829C8C4060A4A66266A6406300F03B541A000100EE000C4EB058375F030A00000300000000000300010000000500000000000500010000000400010000000400000000000700000000000400000000000700000000000600000000000300000000000500000000000000000000000500000000000800010000000000000000000400000000000500000000000800000000000500000000000000000000000600000000000400000000000400000000000100010000000900000000000500020000000400000000000300000000000300000000000200010000000300010000000400020000000200000000000700000000000600000000000400000000000300000000B5");
SiriusSatBeacon result = new SiriusSatBeacon();
result.readBeacon(data);
AssertJson.assertObjectsEqual("SiriusSatBeacon-unknown.json", result);
}
@Test
public void testExtendedBeacon() throws Exception {
byte[] data = ViterbiTest.hexStringToByteArray("A464829C8C4060A4A66266A6406300F017420200010051000E00EB999B44E7E0A4C55750FB4600135DC0400B4DC100426FC00000008E27485F008E27485F00000000000000006E7614475F000000000000000000000000CB57CA57000000000000FF7F000000000000");
SiriusSatBeacon result = new SiriusSatBeacon();
result.readBeacon(data);
AssertJson.assertObjectsEqual("SiriusSatBeacon-extended.json", result);
}
@Test
public void testPojo() {
assertThat(SiriusSatBeacon.class, allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
assertThat(ShortBeacon.class, allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
assertThat(ExtendedBeacon.class, allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
}
}
| 52.957447 | 532 | 0.868622 |
16c4cc76034c2436ae4b3a6beec666a882b963d3 | 60,325 | // File: Assembler.java
// Author: Julie Lobur
// SDK Version: 1.4.1
// Date: November 9, 2002
// Notice: Copyright 2003
// This code may be freely used for noncommercial purposes.
package MarieSimulator;
import java.io.*;
import java.util.*;
public class Assembler implements Serializable {
/****************************************************************************************************
* This program assembles code written for the MARIE (Machine Architecture that is Really *
* Intuitive and Easy) computer as described in *The Essentials of Computer Organization and *
* Architecture* by Null & Lobur. As with most assemblers, this assembler works in two passes *
* over the source code: The first pass performs simple translation of mnemonics to their *
* hex equivalent, e.g., LOAD = 1, and adding whatever symbols that it finds to a symbol table *
* maintaned by this program. The first pass of the program creates an intermediate workfile *
* of serialized AssembledCodeLine objects, still containing symbolic names instead of memory *
* addresses. *
* *
* The second pass of the assembler, reads the intermediate workfile and supplies addresses *
* for the symbols using addresses found in the symbol table. (Or producing an error if the *
* symbol can't be found.) The output of this phase is written to another workfile. *
* *
* The final output of the assembler, the "MARIE EXecutable" file is produced from the second- *
* pass workfile if there are no errors. A map of symbol addresses from the symbol table is *
* also produced so that it can be used as an online reference when running the MARIE simulator. *
* A listing file is produced whether or not the assembly was successful. The output format of *
* both the assemby listing and symbol table is HTML to facilitate access within the environment *
* of the MARIE simulator. *
* *
* *
* Implementation Notes: 1. Unlike "real" assemblers, this assembler does not produce binary *
* machine code (though it would be easy to make it do so). The *
* output is instead an object stream that is used by both the listing- *
* formatting method (below) and the MARIE simulator program. The MARIE *
* simulator is the only place where output code from this program will *
* run, so we format our output accordingly. *
* 2. The reader may be curious as to why the author chose to use Java *
* integers instead of Java short integers, which are exactly the *
* same size as a MARIE word. Java integers were used because they *
* offered the path of least resistance, eliminating the need for *
* type casts throughout programs related to the MARIE system. *
* This decision meant that some fancy footwork had to be done when *
* converting between radices, but overall fewer difficulties were *
* presented by using this approach. *
****************************************************************************************************/
/*
Notes: Labels are case sensitive, otherwise codeline is case insensitive.
Hex literals must begin with a digit, e.g., BABE must be 0BABE.
Address literals (instruction operands) must be in hex and in MARIE-addressable range.
Numeric literals must be in the range of -32768 to 32767. MARIE uses 16 bits only
so 0 -> 7FFF = 0 to 32767 and
8000 -> 0 = -32768 to 0.
*/
/* -- -- */
/* -- File definitions. -- */
/* -- -- */
public BufferedReader sourceFile = null; // Buffered reader for source code.
public File objectFile = null; // Object input/output file.
public ObjectOutputStream objFileOut = null; // Object writer for intermediate code.
public BufferedWriter lstFile = null; // Buffered writer for text output.
public ObjectInputStream objFileIn = null; // Object reader for intermediate code.
public BufferedWriter mapFile = null; // Output symbol table reference file.
public String sourceFileName = null; // Name of sourcefile to process.
public static final String sourceType = "mas"; // File exentions: MAS = MARIE Source
public static final String listType = "lst"; // LST = Assembler listing (text)
public static final String mapType = "map"; // MAP = Symbol table (text)
public static final String exeType = "mex"; // MEX = Executable for simulator
/* -- -- */
/* -- Constants. -- */
/* -- -- */
public static final int MAX_MARIE_INT = 32767;
public static final int MIN_MARIE_INT = -32768;
public static final int MAX_MARIE_ADDR = 4095;
public static final int DEC = -1;
public static final int OCT = -2;
public static final int HEX = -3;
public static final int ORG = -4;
public static final int END = -5;
public static final int MAX_SYMBOL_PRINT_LEN = 24; // Maximum size of symbol when printing
// symbol table. All chars significant,
// only this many shown.
public static final int LABEL_DELIM = (int) ','; // Punctuation for a label statement.
public static final int COMMENT_DELIM = (int) '/'; // Punctuation for inline comment.
public static final String fileSeparator = System.getProperty("file.separator");
public static final String lineFeed = System.getProperty("line.separator");
public static final String formFeed = "\014";
public static final String[] errorMsgs = {
"ORiGination directive must be first noncomment line of program ", // 0
"A label cannot have 0..9 as its beginning character.", // 1
"Statement label must be unique.", // 2
"Instruction not recognized.", // 3
"Missing instruction.", // 4
"Missing operand.", // 5
"Hex address literal out of range 0 to 0FFF allowable.", // 6
"Invalid decimal value: -32768 to 32767 allowable.", // 7
"Invalid octal value: 00000 to 177777 allowable.", // 8
"Invalid hexadecimal value: 0 to FFFF allowable.", // 9
"Operand undefined.", // 10
"Maximum source lines exceeded. Assembly halted.", // 11
"Maximum line number exceeded. Assembly halted." // 12
};
/* -- -- */
/* -- Instance variables -- */
/* -- -- */
// Hashtables are used for the instruction set and the
// symbol table so that we can easily search them and
// retrieve values.
public Hashtable symbolTable // Initial capacity 18, load factor 0.75.
= new Hashtable(18, (float) 0.75);
public final Hashtable instructionSet = new Hashtable(18);
public int lineNumber; // Current instruction address.
public int errorCount = 0; // Total number of errors in assembly.
public boolean errorFound = false; // "Temporary" error flag.
public boolean done; // Terminating condition found (e.g.EOF)?
public ArrayList errorList = new ArrayList(); // Holds text of any errors found.
public boolean operandReqd = false; // Does current instruction need an operand?
public boolean hasLabel = false; // Is current instruction labeled?
public int maxSymbolLength = 0; // Longest symbol in code (for formatting).
class SymbolEntry {
/******************************************************************************************
* Inner class SymbolEntry is the framework for the objects that are used to store and *
* retrieve values that form the Assembler's symbol table. As these objects are *
* instantiated, they are placed in a HashTable structure. As references to the symbols *
* are found, they are added to the SymbolEntry's vector of references. *
******************************************************************************************/
String symbol = null; // The symbol itself.
String address = null; // Where it is defined.
Vector referencedAt; // List of locations where referenced.
SymbolEntry(String s, String a) {
symbol = s;
address = a;
referencedAt = new Vector();
} // SymbolEntry()
} // SymbolEntry
class Instruction implements Serializable {
/******************************************************************************************
* Inner class Instruction stores the important components of a Marie machine instruction. *
******************************************************************************************/
String mnemonic; // Instruction mnemonic
byte hexCode; // Hex code of instruction
boolean addrReqd; // Flag to indicate whether an operand is required.
Instruction(String mnemonic, byte hexCode, boolean addrReqd) {
this.mnemonic = mnemonic;
this.hexCode = hexCode;
this.addrReqd = addrReqd;
} // Instruction()
} // Instruction
/******************************************************************************************
* Create searchable instruction set hashtable from a stream of literal values. The *
* Instruction objects end up in a Hashtable. The format for this hashtable is given *
* in the class definition for Instruction (above). *
******************************************************************************************/
void loadInstructionSet() {
instructionSet.put("JNS", new Instruction("JNS", (byte) 0, true));
instructionSet.put("LOAD", new Instruction("LOAD", (byte) 1, true));
instructionSet.put("STORE", new Instruction("STORE", (byte) 2, true));
instructionSet.put("ADD", new Instruction("ADD", (byte) 3, true));
instructionSet.put("SUBT", new Instruction("SUBT", (byte) 4, true));
instructionSet.put("INPUT", new Instruction("INPUT", (byte) 5, false));
instructionSet.put("OUTPUT", new Instruction("OUTPUT", (byte) 6, false));
instructionSet.put("HALT", new Instruction("HALT", (byte) 7, true));
instructionSet.put("SKIPCOND", new Instruction("SKIPCOND", (byte) 8, true));
instructionSet.put("JUMP", new Instruction("JUMP", (byte) 9, true));
instructionSet.put("CLEAR", new Instruction("CLEAR", (byte) 10, false));
instructionSet.put("ADDI", new Instruction("ADDI", (byte) 11, true));
instructionSet.put("JUMPI", new Instruction("JUMPI", (byte) 12, true));
instructionSet.put("DEC", new Instruction("DEC", (byte) DEC, true));
instructionSet.put("OCT", new Instruction("OCT", (byte) OCT, true));
instructionSet.put("HEX", new Instruction("HEX", (byte) HEX, true));
instructionSet.put("ORG", new Instruction("ORG", (byte) ORG, true));
instructionSet.put("END", new Instruction("END", (byte) END, false));
} // loadInstructionSet()
/* ------------------------------------------------------------------------------------- */
/* -- Input parsing and output creation -- */
/* ------------------------------------------------------------------------------------- */
String statementLabel(String stmt) {
/******************************************************************************************
* Looks for label punctuation in the parameter String. Returns the label if found *
* and calls method to add the symbol to the instruction table. *
******************************************************************************************/
String aSymbol = null;
int i = stmt.indexOf(LABEL_DELIM); // Find the delimiter.
if (i < 0) // If none found, we're outta here.
return " ";
hasLabel = true; // Set this for anything delimited.
if (i == 0) // Note: Index == 0 => label punct in first
return " "; // position => null label.
aSymbol = stmt.substring(0, i);
char ch = aSymbol.charAt(0);
if (Character.isDigit(ch)) {
setErrorMessage(errorMsgs[1]);
return " ";
}
if (!addedToSymbolTable(aSymbol)) {
return " ";
}
return aSymbol;
} // statementLabel()
boolean tokenIsLiteral(String token) {
/******************************************************************************************
* This method determines whether the token passed as a parameter is a valid hex literal. *
* If a hex literal is used as an address literal (as opposed to a symbolic reference to *
* an address) the address must begin with a zero, even if it means the literal will be *
* longer than 3 characters. (This is the only way we can tell the address A from the *
* symbol A.) Note, the check of the token is case insensitive. *
******************************************************************************************/
char[] tokenChars = token.toCharArray();
if (!Character.isDigit(tokenChars[0])) // First character of a numeric
return false; // literal must be 0..9.
for (int i = 0; i < token.length(); i++) // Now check that the rest of the literal is
if (!Character.isDigit(tokenChars[i])) // a valid hex number.
switch (tokenChars[i]) {
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
case 'D':
case 'd':
case 'E':
case 'e':
case 'F':
case 'f':break;
default: return false;
} // switch
return true;
} // tokenIsLiteral()
int validMarieValue(int number) {
/******************************************************************************************
* Used by the literalToInt() method to check the value of the parameter integer with *
* respect to the 16-bit word size of Marie. Specifically, Java values in the 32768 to *
* 65535 (absolute value) translate to -32768 -> 0 in MARIE memory. Otherwise, anything *
* out of the -32768 to 32767 range returns Integer.MAX_VALUE. *
******************************************************************************************/
if ((number >= MIN_MARIE_INT) && (number <= MAX_MARIE_INT))
return number;
int absNumber = Math.abs(number);
if ((absNumber >= MAX_MARIE_INT) && (absNumber <= (2*MAX_MARIE_INT)+1))
return (absNumber - 2*(MAX_MARIE_INT+1));
return Integer.MAX_VALUE;
} // isValidMarieValue()
int literalToInt(int literalType, String literal, boolean directive) {
/******************************************************************************************
* Converts a String literal to integer. *
* Parameters: *
* int literalType = DEC, OCT, HEX, ORG, and END (final static int constants), *
* the String literal to be converted to an integer, and *
* a boolean to indicate whether the String literal was found in a directive *
* statement, such as OCT or HEX, or whether it was found as an address literal *
* in an imperative MARIE assembler statement. *
* This method will return Integer.MAX_VALUE to flag any exceptions thrown. (We can get *
* away with this because Marie's word size is smaller than Java's.) *
******************************************************************************************/
int result = Integer.MAX_VALUE;
switch (literalType) {
case (DEC): { // DECimal literal.
try {
result = validMarieValue(Integer.parseInt(literal, 10));
if (result == Integer.MAX_VALUE)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
setErrorMessage(errorMsgs[7]);
result = Integer.MAX_VALUE;
}
break;
}
case (OCT): { // OCTal literal.
try {
result = validMarieValue(Integer.parseInt(literal, 8));
if (result == Integer.MAX_VALUE)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
setErrorMessage(errorMsgs[8]);
result = Integer.MAX_VALUE;
}
break;
}
case (HEX):
case (ORG): { // HEXadecimal literal or ORiGination directive.
try {
result = validMarieValue(Integer.parseInt(literal, 16));
if (result == Integer.MAX_VALUE)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
if (literalType == ORG)
setErrorMessage(errorMsgs[6]);
else
setErrorMessage(errorMsgs[9]);
result = Integer.MAX_VALUE;
}
break;
}
case (END):
} // switch()
if ( result == Integer.MAX_VALUE ) // If we found an error, we're done.
return 0;
if (!directive) { // If the String argument is part of
if ((result < 0) || (result > MAX_MARIE_ADDR)) {
setErrorMessage(errorMsgs[6]); // an address literal, make sure
result = 0; // the address is within addressible
} // Marie memory.
}
return result;
} // literalToInt()
String to3CharHexStr(int number) {
/******************************************************************************************
* Converts the argument number to a string containing exactly 3 characters by padding *
* shorter strings and truncating longer strings. So an argument larger than 8092 or *
* smaller than 0 will be truncated to end up in the (unsigned) range 0 - 4095. *
******************************************************************************************/
// If number negative, convert to 16-bit 2's
if (number < 0) { // complement by shifting the low-order 20
number = number << 20; // bits to the high-order bits. (We lose the
} // rightmost bits below.)
String hexStr = Integer.toHexString(number).toUpperCase();
switch (hexStr.length()) {
case 1: hexStr = "00"+hexStr; // Pad strings shorter than 3 chars.
break;
case 2: hexStr = "0" +hexStr;
break;
case 3: break;
default: hexStr = hexStr.substring(0, 3); // Truncate strings longer than 3 chars
} // switch()
return hexStr;
} // to3CharHexStr()
String to4CharHexStr(int number) {
/******************************************************************************************
* Same as above (to3CharHexStr()), only returns a string of exactly 4-characters that are *
* in the (decimal) range -32,768 to 32,767. *
******************************************************************************************/
if (number < 0) { // If number negative, convert to 16-bit 2's
number = number << 16; // complement by shifting the low-order 16
} // bits to the high-order bits. (We lose the
// rightmost 16 bits below.)
String hexStr = Integer.toHexString(number).toUpperCase();
switch (hexStr.length()) {
case 1: hexStr = "000"+hexStr; // Pad strings shorter than 4 chars.
break;
case 2: hexStr = "00" +hexStr;
break;
case 3: hexStr = "0" +hexStr;
break;
case 4: break;
default: return hexStr.substring(0, 4); // Truncate strings longer than 4 chars.
} // switch()
return hexStr;
} // to4CharHexStr()
boolean addedToSymbolTable(String symbol) {
/******************************************************************************************
* Returns true if argument symbol (along with the line number where it is defined) is *
* successfully added to the symbol table. If the symbol is already in the symbol table, *
* this method will return false. *
******************************************************************************************/
SymbolEntry se;
if (symbolTable.containsKey(symbol)) {
setErrorMessage(errorMsgs[2]);
return false;
}
se = new SymbolEntry(symbol, to3CharHexStr(lineNumber));
symbolTable.put(symbol, se);
if (symbol.length() > maxSymbolLength) // Get this size for output formatting
maxSymbolLength = symbol.length();
return true;
} // addToSymbolTable()
String getSymbolAddress(String symbol, String referenceLine) {
/******************************************************************************************
* Retrieves the address where the symbol is defined from the symbol table. *
******************************************************************************************/
SymbolEntry se;
String address = null;
if (symbolTable.containsKey(symbol)) {
se =(SymbolEntry) symbolTable.get(symbol);
address = se.address;
se.referencedAt.add(referenceLine);
symbolTable.put(symbol, se);
}
else
setErrorMessage(errorMsgs[10]);
return address;
} // getSymbolAddress()
String padStr(String s, int size) {
/******************************************************************************************
* Adds trailing blanks to pad the string s to the length (size) specified in the *
* argument list, if it is longer than "size." Truncates if shorter. *
******************************************************************************************/
int strLen = s.length();
if (strLen > size)
strLen = size;
StringBuffer sb = new StringBuffer(s.substring(0, strLen));
for (int i = strLen; i < size; i++)
sb.append(" ");
return sb.toString();
} // padStr()
int getOpcode(String stmt) {
/******************************************************************************************
* Tries to find the argument stmt in the Hashmap instructionSet. If not found, returns *
* Java Integer.MIN_VALUE (a number we'd never see in a MARIE instruction set). *
* Also makes a "special case" check that an ORiGination statement must be the first *
* non-comment line of a MARIE program. *
******************************************************************************************/
Instruction instruction;
int value = 0;
if (instructionSet.containsKey(stmt)) { // Try to find stmt value in
instruction = (Instruction) instructionSet.get(stmt); // instruction set.
operandReqd = instruction.addrReqd;
value = instruction.hexCode;
if (instruction.hexCode == ORG) { // If found and is an
if (lineNumber > 0) { // ORiGination, return error
setErrorMessage(errorMsgs[0]); // if not the first non-
value = Integer.MIN_VALUE; // comment line.
}
}
}
else {
setErrorMessage(errorMsgs[3]); // Instruction not found.
value = Integer.MIN_VALUE;
}
return value;
} // getOpcode()
void setErrorMessage(String msg) {
/******************************************************************************************
* Increments the error count, sets the error flag and adds the message string of the *
* argument to the list (Vector) of errors for the current code line being parsed. *
******************************************************************************************/
errorCount++;
errorFound = true;
errorList.add(msg);
} // setErrorMessage()
/* -- -- */
/* -- The "meat" of this program .... -- */
/* -- -- */
AssembledCodeLine parseCodeLine(String inputLine) {
/******************************************************************************************
* This method controls extraction of symbols from a single line of source code passed as *
* a String argument. The return value is an object composed of the extracted tokens *
* along with a Vector containing any error messages found, and the input line itself. *
* If the inputLine is a blank line or a comment, the token-related fields in the returned *
* object are all spaces, and the object is populated only with the source code line *
* itself. *
* *
* Side effects: *
* As noncomment code lines are processed, the (global) line counter (or address *
* value) is incremented. Also, if any errors are found (such as a missing token), *
* the error count and global error flag are updated through calls to the *
* error handler. *
******************************************************************************************/
AssembledCodeLine aCodeLine = new AssembledCodeLine(); // Create the output object
StringBuffer codeLine = new StringBuffer(" "), // String buffer for parsing source code.
instructionLabel = new StringBuffer(" "), // String buffer for statement label.
operand = new StringBuffer(" "); // String buffer for the operand.
int instructionCode = 0,
anIntValue = 0;
errorList.clear(); // Reset all short-term error control
errorFound = false; // fields.
codeLine.delete(0, codeLine.length());
// Consider the line only up to any comments.
int codeLength = inputLine.indexOf(COMMENT_DELIM);
if (codeLength < 0) // Implies no comment present.
codeLength = inputLine.length();
if (codeLength > 0) { // Copy noncomment code to working buffer.
codeLine.append(inputLine.substring(0, codeLength));
int lineLength = inputLine.length(); // and save the comment.
if ((lineLength > 1) && ((lineLength - codeLength) > 0) )
aCodeLine.comment = inputLine.substring(codeLength, lineLength);
}
aCodeLine.sourceLine = inputLine; // Copy the source to output object.
instructionLabel.delete(0, instructionLabel.length());
StringTokenizer st = new StringTokenizer(codeLine.substring(0, codeLine.length()));
if (st.countTokens()== 0) { // If there are no tokens, we have a blank
aCodeLine.comment = inputLine; // line (or comment). No need to parse it.
return aCodeLine;
}
lineNumber++; // Make sure we haven't exceeded the
if (lineNumber > MAX_MARIE_ADDR) { // storage capacity for source code.
setErrorMessage(errorMsgs[12]); // If so, halt assembly.
int size = errorList.size();
for (int i = 0; i < size; i++)
aCodeLine.errors.add((String) errorList.get(i));
errorFound = true;
done = true;
return aCodeLine;
}
/* -- -- */
/* -- Get the label, if any. -- */
/* -- We assume Assume there is no label, the statementLabel() method sets the -- */
/* -- hasLabel flag to true if it finds one. -- */
/* -- -- */
String aToken = st.nextToken();
hasLabel = false;
instructionLabel.append(statementLabel(aToken.trim()));
aCodeLine.stmtLabel = instructionLabel.toString();
/* -- -- */
/* -- Get the opcode. (There better be one at this point.) -- */
/* -- Once we have the opcode, we also know whether an operand is needed. -- */
/* -- -- */
operandReqd = true; // Assume operand is needed.
if (hasLabel) { // If no label at all,
if (st.hasMoreTokens()) { // get the next token.
aToken = st.nextToken().toUpperCase();
instructionCode = getOpcode(aToken);
aCodeLine.mnemonic = aToken;
} // Otherwise, process the current
else { // token as an opCode.
setErrorMessage(errorMsgs[4]);
operandReqd = false; // If no operator, we need
instructionCode = Integer.MIN_VALUE; // no operand.
}
}
else {
instructionCode = getOpcode(aToken.toUpperCase());
aCodeLine.mnemonic = aToken.toUpperCase();
}
/* -- -- */
/* -- Get the operand. If no operand is needed, we would have found out when we got -- */
/* -- the opcode. In the process of finding the opcode, the operandReqd flag is set -- */
/* -- based upon the characteristics of the Instruction. -- */
/* -- -- */
operand.delete(0, operand.length());
if (operandReqd) {
if (st.hasMoreTokens()) {
aToken = st.nextToken();
if ((instructionCode >= ORG) && (instructionCode < 0)) { // Do we have a "constant" directive?
anIntValue = literalToInt(instructionCode, aToken.toUpperCase(), true);
if ((instructionCode > ORG) || (errorFound)) {
operand.append(to4CharHexStr(anIntValue));
instructionCode = literalToInt(HEX, operand.substring(0, 1), false);
operand.deleteCharAt(0); // Put first char of literal
aCodeLine.operandToken = aToken.toUpperCase(); // in instructionCode field
}
else { // Handle ORiGination
lineNumber = anIntValue - 1; // directive. (No code
aCodeLine.operandToken = aToken.toUpperCase(); // generated.)
return aCodeLine;
}
} // If so, get value.
else { // Otherwise, we must have an address
if (tokenIsLiteral(aToken)) { // literal or label.
anIntValue = literalToInt(HEX, aToken, false);
aToken = to3CharHexStr(anIntValue).toUpperCase(); // Convert literal to uppercase
operand.append(aToken);
aCodeLine.operandToken = aToken;
}
else {
operand.append("_"); // Flag token for later lookup.
operand.append(aToken);
aCodeLine.operandToken = aToken;
}
}
}
else {
setErrorMessage(errorMsgs[5]);
operand.append("???");
}
} // operandReqd
else operand.append("000");
/* -- -- */
/* -- Finish populating the intermediate code object. -- */
/* -- -- */
aCodeLine.lineNo = to3CharHexStr(lineNumber);
if (instructionCode >= 0)
aCodeLine.hexCode = Integer.toHexString(instructionCode).toUpperCase();
else if (instructionCode < -15) // Invalid instruction found.
aCodeLine.hexCode = "?";
else if (instructionCode == END) { // "END" directive has been found.
aCodeLine.lineNo = " ";
aCodeLine.hexCode = " "; // Clear code line except for directive.
operand.delete(0, operand.length());
operand.append(" ");
done = true;
}
aCodeLine.operand = operand.toString();
if (errorFound) { // Add any errors found to the output object.
int last = errorList.size();
for (int i = 0; i < last; i++) {
aCodeLine.errors.add((String) errorList.get(i));
}
}
return aCodeLine;
} // parseCodeLine()
AssembledCodeLine symbolsToAddresses(AssembledCodeLine codeLine) {
/******************************************************************************************
* This is the second pass of the assembler. All we need to do is find the addresses of *
* the symbols in the assembler program. We either find them in the symbol table or we *
* don't. *
******************************************************************************************/
String currAddress = codeLine.lineNo;
errorFound = false;
errorList.clear();
if (codeLine.lineNo.charAt(0) == ' ') // If not an executable statement,
return codeLine; // we don't care about any symbols.
if (codeLine.operand.indexOf((int) '_') == 0) {
currAddress = getSymbolAddress
(codeLine.operand.substring(1, codeLine.operand.length()),
currAddress);
if (currAddress != null) {
codeLine.operand = currAddress;
}
else codeLine.operand = "???"; // Error: Symbol not found.
}
if (errorFound) { // We have only one possible kind
codeLine.errors.add((String) errorList.get(0)); // of error from this pass.
}
return codeLine;
} // symbolsToAddresses()
int performFirstPass() {
/******************************************************************************************
* This method calls methods to open all of the first-pass files, read the source file, *
* parse the input, and write the output to the intermediate output file. When complete, *
* all related files are closed. *
* Note: A negative return value indicates a critical error in the file handling *
* only and has nothing to do with any errors found in the assembly program *
* code. *
* *
* When this pass is complete, the "binary" program output is ready for second-pass *
* processing. *
******************************************************************************************/
AssembledCodeLine aCodeLine = new AssembledCodeLine();
done = false;
errorFound = false;
loadInstructionSet();
openFirstPassFiles();
if (errorFound) { // Negative return value is fatal error
return -1;
}
while (!done) { // Loop through source file input.
try {
String inputLine = sourceFile.readLine();
if (inputLine != null) {
aCodeLine = parseCodeLine(inputLine);
objFileOut.writeObject(aCodeLine);
}
else {
done = true;
}
} // try
catch (EOFException e) {
done = true;
} // catch
catch (IOException e) {
System.err.println(e);
return -1;
} // catch
} // while
closeFirstPassFiles();
return 0;
} // performFirstPass()
int performSecondPass() {
/******************************************************************************************
* This method reads the partially assembled code file produced by the first pass *
* and calls the method that supplies addresses for the symbols in that file. The *
* The output is <filename>.MEX that is the MARIE executable used by the MARIE *
* machine simulator. A file, <filename>.map, containing the symbol table is also *
* produced for the user's reference while running the MARIE simulator. *
* Note: A negative return value indicates a critical error in the file handling *
* only and has nothing to do with any errors found in the assembly program *
* code. *
******************************************************************************************/
errorFound = false;
openSecondPassFiles();
AssembledCodeLine aCodeLine = new AssembledCodeLine();
done = false;
if (errorFound) {
return -1; // Negative return value is fatal error
}
while (!done) {
try {
aCodeLine = (AssembledCodeLine) objFileIn.readObject();
if (aCodeLine != null) {
aCodeLine = symbolsToAddresses(aCodeLine);
objFileOut.writeObject(aCodeLine);
}
else
done = true;
} // try
catch (EOFException e) {
done = true;
} // catch
catch (ClassNotFoundException e) {
done = true;
System.err.println(e);
return -1;
} // catch
catch (IOException e) {
System.err.println(e);
return -1;
} // catch
} // while
closeSecondPassFiles();
return 0;
} // performSecondPass()
void produceFinalOutput() {
/******************************************************************************************
* This method produces the final outputs from the MARIE assembler, using the ".MO2" *
* file as input. An assembly listing, <filename>.LST is always produced by this step. *
* If assembly was error-free, a ".MEX" (MARIE EXecutable) file is produced along with *
* a <filename>.MAP file containing the symbol table which can be used for later *
* reference when running the simulator. *
******************************************************************************************/
AssembledCodeLine aCodeLine = new AssembledCodeLine();
done = false;
openFinalFiles();
int dirEndPos = 0; // Strip the path from the fileName
dirEndPos = sourceFileName.lastIndexOf(fileSeparator);
String currFilePrefix = sourceFileName.substring(dirEndPos+1, sourceFileName.length());
try {
for (int i = 0; i < 5; i++) // Write title heading.
lstFile.write(" ");
lstFile.write("Assembly listing for: "+currFilePrefix+"."+sourceType+lineFeed);
for (int i = 0; i < 5; i++)
lstFile.write(" ");
lstFile.write(" Assembled: "+new Date()+lineFeed);
lstFile.write(lineFeed);
}
catch (IOException e) {
done = true;
System.err.println(e);
} // catch
if (maxSymbolLength < 6) // Format the symbol printing so that the
maxSymbolLength = 6; // table won't wrap off of the right
else if (maxSymbolLength > MAX_SYMBOL_PRINT_LEN) // margin (assuming reasonable font size).
maxSymbolLength = MAX_SYMBOL_PRINT_LEN;
while (!done) {
try {
aCodeLine = (AssembledCodeLine) objFileIn.readObject(); // Print a formatted
if (aCodeLine == null) // line on the listing.
done = true;
else {
lstFile.write(aCodeLine.lineNo+" ");
lstFile.write(aCodeLine.hexCode);
lstFile.write(aCodeLine.operand+" | ");
lstFile.write(" "+padStr(aCodeLine.stmtLabel, maxSymbolLength));
lstFile.write(" "+aCodeLine.mnemonic);
lstFile.write(" "+padStr(aCodeLine.operandToken, //Put spaces after the operand...
maxSymbolLength+(9-aCodeLine.mnemonic.length())));
lstFile.write(" "+aCodeLine.comment+lineFeed); //...so comments will line up.
for (int i = 0; i < aCodeLine.errors.size(); i++) // Error list prints
lstFile.write(" **** " + aCodeLine.errors.get(i)+lineFeed); // for each line.
}
} // try
catch (ClassNotFoundException e) {
done = true;
System.err.println(e);
} // catch
catch (EOFException e) {
done = true;
} // catch
catch (IOException e) {
System.err.println(e);
done = true;
} // catch
if (done)
break;
} // while
try {
lstFile.write(lineFeed);
if (errorCount > 0) {
lstFile.write(errorCount + " error");
if (errorCount > 1)
lstFile.write("s");
lstFile.write(" found. Assembly unsuccessful."+lineFeed);
}
else
lstFile.write("Assembly successful."+lineFeed);
dumpSymbolTable();
} // try
catch (IOException e) {
System.err.println(e);
done = true;
} // catch
closeFinalFiles();
} // produceFinalOutput()
void dumpSymbolTable() throws IOException {
/******************************************************************************************
* Place the contents of the symbol table, including line number where defined and line *
* numbers where referenced, on the assembly listing. We attempt to make a nicely- *
* formatted table, padding out all symbol names to match the length of the longest name. *
* The "symbol name" column will be a minumum of 6 characters and a maximum of *
* MAX_SYMBOL_PRINT_LEN. Symbols longer than MAX_SYMBOL_PRINT_LEN will be truncated for *
* printing purposes, but the entire symbol name is significant (up to the limits imposed *
* by the Java language). *
* If assembly was successful, we also write symbol table entries to a plain text *
* "mapfile" for later reference (by the progammer) while the MARIE program is executing. *
******************************************************************************************/
SymbolEntry se;
int referenceCount = 0;
String indent = " ";
ArrayList keyList = new ArrayList();
Enumeration v, e = symbolTable.elements();
while (e.hasMoreElements()) {
se = (SymbolEntry) e.nextElement();
keyList.add(se.symbol);
}
Collections.sort(keyList); // Sort the names of the symbols.
for (int i = 1; i < 2; i++)
lstFile.write(lineFeed);
lstFile.write(indent); // First heading line.
lstFile.write("SYMBOL TABLE"+lineFeed);
lstFile.write(indent+"-------"); // Second heading line.
for (int i = 0; i < (maxSymbolLength-5); i++) {
lstFile.write("-");
}
lstFile.write("------------------------------------------"+lineFeed);
lstFile.write(indent + " Symbol"); // Third heading line.
for (int i = 0; i < (maxSymbolLength-5); i++)
lstFile.write(" ");
lstFile.write("| Defined | References "+lineFeed);
lstFile.write(indent+"-------"); // Fourth heading line.
for (int i = 0; i < (maxSymbolLength-5); i++)
lstFile.write("-");
lstFile.write("+---------+-------------------------------");
if (mapFile != null) { // Write headings to symbol map file
mapFile.write(" -----"); // if assembly was successful.
for (int i = 0; i < (maxSymbolLength-4); i++)
mapFile.write("-");
mapFile.write("----------"+lineFeed);
mapFile.write(" Symbol");
for (int i = 0; i < (maxSymbolLength-5); i++)
mapFile.write(" ");
mapFile.write("| Location"+lineFeed);
mapFile.write(" ");
mapFile.write("-----");
for (int i = 0; i < (maxSymbolLength-4); i++)
mapFile.write("-");
mapFile.write("+---------");
}
for (int i = 0; i < keyList.size(); i++) { // Print table body.
se = (SymbolEntry) symbolTable.get(keyList.get(i));
lstFile.write(lineFeed);
lstFile.write(indent+" "+padStr(se.symbol, maxSymbolLength) + " | " + se.address+" | ");
if (mapFile != null) {
mapFile.write(lineFeed);
mapFile.write( " "+padStr(se.symbol, maxSymbolLength) + " | " + se.address);
}
v = se.referencedAt.elements();
referenceCount = 0;
boolean first = true;
while (v.hasMoreElements()) {
if (first) {
lstFile.write(v.nextElement().toString());
referenceCount++;
first = false;
}
else {
lstFile.write(", ");
if ((referenceCount % 6) == 0) {
lstFile.write(lineFeed);
lstFile.write(indent+padStr(" ", maxSymbolLength)+" |"+indent+"| ");
}
lstFile.write(v.nextElement().toString());
referenceCount++;
}
}
}
lstFile.write(lineFeed); // Table bottom.
lstFile.write(indent+"-------");
for (int i = 0; i < (maxSymbolLength-5); i++)
lstFile.write("-");
lstFile.write("------------------------------------------"+lineFeed);
lstFile.write(lineFeed);
} // dumpSymbolTable()
/* ------------------------------------------------------------------------------------- */
/* -- Mainline processing. -- */
/* ------------------------------------------------------------------------------------- */
public static int assembleFile(String fileName) {
/******************************************************************************************
* This method is the mainline for the MARIE assembler. It expects to be passed the *
* name of a MARIE assembly code file, <filename>, that will be opened as <filename>.MAS. *
* Ultimately, a <filename>.LST, <filename>.MAP and <filename>.MEX files will be created *
* from the <filename>.MAS file. *
******************************************************************************************/
Assembler assembler = new Assembler();
int irrecoverableError = 0;
if ( fileName == null) { // Make sure we have an
System.err.println("\nNull input file to assembler."); // input file specified.
return -1;
}
int i = fileName.lastIndexOf('.'); // If the user supplied an
if (i > 0) // extension to the filename,
fileName = fileName.substring(0, i); // ignore it.
assembler.sourceFileName = fileName;
assembler.lineNumber = -1;
irrecoverableError = assembler.performFirstPass(); // Call functional methods.
if (irrecoverableError == 0) // irrecoverableError(s) occur
irrecoverableError = assembler.performSecondPass(); // as a result of unexpected
else { // file IO problems.
System.err.println("Irrecoverable IO error occurred during first assembly pass.");
}
if (irrecoverableError == 0)
assembler.produceFinalOutput();
else {
System.err.println("Irrecoverable IO error occurred during second assembly pass.");
return -1;
}
return assembler.errorCount;
} // assembleFile()
/* ------------------------------------------------------------------------------------- */
/* -- File handling -- */
/* ------------------------------------------------------------------------------------- */
void openFirstPassFiles() {
/******************************************************************************************
* Opens files required by first-pass processing. *
* The filename, sourceFileName (class field), has ".MAS" appended to it prior to any *
* sourcefile open attempts. An intermediate file <sourceFileName>.MO1 is created to *
* hold assembled code "objects" used for input by the second pass of the assembler. *
******************************************************************************************/
try { // Try to open the input.
sourceFile = new BufferedReader( new FileReader(sourceFileName+"."+sourceType) );
} // try
catch (FileNotFoundException e) {
System.err.println(lineFeed+"File " + sourceFileName + "."+sourceType+" not found.");
errorFound = true;
return;
} // catch
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
return;
} // catch
try { // Create the intermediate output code.
objectFile = new File(sourceFileName+".MO1"); // MO1 = Marie Object, first pass
objFileOut = new ObjectOutputStream( new FileOutputStream(objectFile) );
} // try
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
} // catch
} // openFirstPassFiles()
void closeFirstPassFiles() {
/******************************************************************************************
* Closes files opened in the first pass. *
******************************************************************************************/
try { // Close source file.
sourceFile.close();
} // try
catch (IOException e) {
System.err.println(e);
} // catch
try { // Close intermediate file.
objFileOut.close();
} // try
catch (IOException e) {
System.err.println(e);
} // catch
} // closeFirstPassFiles()
void openSecondPassFiles() {
/******************************************************************************************
* Opens files required by second-pass processing. *
* We expect to see an ".M01" file that was created by the first pass. We will write the *
* output of this assembler phase to an ".MEX" file, which consists of assembled MARIE *
* code lines. *
******************************************************************************************/
try { // Try to open the input.
objectFile = new File(sourceFileName+".MO1");
objFileIn = new ObjectInputStream( new FileInputStream(objectFile) );
} // try
catch (FileNotFoundException e) {
System.err.println(lineFeed+"File " + sourceFileName + ".MO1 not found.");
errorFound = true;
return;
} // catch
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
return;
} // catch
try {
objFileOut = new ObjectOutputStream( new FileOutputStream(sourceFileName+"."+exeType) );
} // try
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
} // catch
} // openSecondPassFiles()
void closeSecondPassFiles() {
/******************************************************************************************
* Closes files opened in the second pass, deleting the workfile (<fileName>.MO1) created *
* by the first pass. *
******************************************************************************************/
try { // Close intermediate file.
objFileIn.close(); // and delete it.
objectFile.delete();
objectFile = null;
} // try
catch (IOException e) {
System.err.println(e);
} // catch
try { // Close assembled file.
objFileOut.close();
} // try
catch (IOException e) {
System.err.println(e);
} // catch
} // closeSecondPassFiles()
void openFinalFiles() {
/******************************************************************************************
* The "final" assembler phase writes the output to a text listing file and creating the *
* "binary" output. Note the objectFile workfile from the second pass is our input. *
******************************************************************************************/
try { // Create the output listing.
lstFile = new BufferedWriter( new FileWriter(sourceFileName+"."+listType) );
} // try
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
return;
} // catch
try { // Open output and
objectFile = new File(sourceFileName+"."+exeType); // try to open the input.
objFileIn = new ObjectInputStream( new FileInputStream(objectFile) );
} // try
catch (FileNotFoundException e) {
System.err.println(lineFeed+"File " + sourceFileName + "."+exeType+" not found.");
errorFound = true;
return;
} // catch
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
return;
} // catch
if (errorCount == 0) { // If no errors, create a
try { // symbol table reference file.
mapFile = new BufferedWriter( new FileWriter(sourceFileName+"."+mapType) );
} // try
catch (IOException e) {
System.err.println(lineFeed+e);
errorFound = true;
return;
} // catch
} // if
} // openFinalFiles()
void closeFinalFiles() {
/******************************************************************************************
* Closes files opened in the final pass, deleting the "binary" objectFile if assembly *
* was unsuccessful. *
******************************************************************************************/
try { // Close listing file.
lstFile.write(formFeed); // We supply a formfeed to please
lstFile.flush(); // certain printers that need one.
lstFile.close();
} // try
catch (IOException e) {
System.err.println(e);
} // catch
try { // Close assembled file.
objFileIn.close();
} // try
catch (IOException e) {
System.err.println(e);
} // catch
if (errorCount == 0) {
try {
mapFile.write(lineFeed);
mapFile.write(formFeed);
mapFile.flush(); // Close symbol table reference
mapFile.close(); // file if we opened it.
} // try
catch (IOException e) {
System.err.println(e);
} // catch
}
else { // If the assembly was unsuccessful, delete
objectFile.delete(); // the "executable" object file.
} // else
} // closeFinalFiles()
public static void main(String args[]) {
/******************************************************************************************
* This main method runs the MARIE assembler in standalone console mode by providing a *
* hook to the mainline processing method assembleFile(). We do this so that the *
* assembler can be used easily as a class method from another program. *
******************************************************************************************/
assembleFile(args[0]);
} // main()
} // Assembler
| 51.427962 | 102 | 0.468214 |
3c7a178755f871676711f897980141831d79ea62 | 3,024 | package pl.egalit.vocab.server.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import pl.egalit.vocab.server.controller.TaskWorker;
import pl.egalit.vocab.server.dao.MulticastDao;
import pl.egalit.vocab.server.dao.RegistrationInfoDao;
import pl.egalit.vocab.server.dao.WordDao;
import pl.egalit.vocab.server.dao.WordsUnitDao;
import pl.egalit.vocab.server.entity.Course;
import pl.egalit.vocab.server.entity.Multicast;
import pl.egalit.vocab.server.entity.RegistrationInfo;
import pl.egalit.vocab.server.entity.School;
import pl.egalit.vocab.server.entity.Word;
import pl.egalit.vocab.server.entity.WordsUnit;
import pl.egalit.vocab.server.security.GwtMethod;
import pl.egalit.vocab.server.security.VocabUser;
import pl.egalit.vocab.server.service.WordService;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.common.collect.Lists;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
@Service
public class WordServiceImpl extends AbstractService implements WordService {
@Autowired
private WordDao wordDao;
@Autowired
private WordsUnitDao wordsUnitDao;
@Autowired
private MulticastDao multicastDao;
@Autowired
private RegistrationInfoDao registrationInfoDao;
private final Queue queue = QueueFactory.getDefaultQueue();
@Override
@GwtMethod
@Secured("ROLE_USER")
public void saveAndSend(List<Word> words, long courseId) {
VocabUser vocabUser = getVocabUser();
Ref<WordsUnit> wordsUnitRef = wordsUnitDao.saveWordsUnit(
vocabUser.getSchoolId(), courseId, vocabUser.getUsername());
wordDao.saveAll(words, wordsUnitRef);
List<String> regIds = findRegIds(vocabUser.getSchoolKey());
Multicast multicast = new Multicast();
multicast.setRegIds(regIds);
multicast.setId(wordsUnitRef.getKey().getId());
multicast.setCourseKey(Key.create(vocabUser.getSchoolKey(),
Course.class, courseId));
multicastDao.save(multicast);
TaskOptions taskOptions = TaskOptions.Builder.withUrl("/task/send")
.param(TaskWorker.PARAMETER_MULTICAST, "" + multicast.getId())
.method(Method.GET);
queue.add(taskOptions);
}
private List<String> findRegIds(Key<School> schoolKey) {
List<String> result = Lists.newArrayList();
List<RegistrationInfo> registrationInfos = registrationInfoDao
.listByProperty("schoolId", schoolKey.getId());
for (RegistrationInfo r : registrationInfos) {
result.add(r.getDeviceRegistrationId());
}
return result;
}
@Override
@GwtMethod
@Secured("ROLE_USER")
public List<Word> getWordsForWordsUnit(long courseId, long wordsUnitId) {
VocabUser vocabUser = getVocabUser();
return wordDao.getWordsForWordsUnit(vocabUser.getSchoolId(), courseId,
wordsUnitId);
}
}
| 32.869565 | 77 | 0.794974 |
d48e4dc671327558217bc4f1d768065a5ad20373 | 1,752 | package com.btk5h.skriptmirror.skript.custom.expression;
import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.log.ErrorQuality;
import ch.njol.util.Kleenean;
import com.btk5h.skriptmirror.util.SkriptUtil;
import org.bukkit.event.Event;
public class EffReturn extends Effect {
static {
Skript.registerEffect(EffReturn.class, "return [%-objects%]");
}
public Expression<Object> objects;
@Override
protected void execute(Event e) {
throw new UnsupportedOperationException();
}
@Override
protected TriggerItem walk(Event e) {
if (objects != null) {
((ExpressionGetEvent) e).setOutput(objects.getAll(e));
} else {
((ExpressionGetEvent) e).setOutput(new Object[0]);
}
return null;
}
@Override
public String toString(Event e, boolean debug) {
if (objects == null) {
return "empty return";
}
return "return " + objects.toString(e, debug);
}
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
SkriptParser.ParseResult parseResult) {
if (!ScriptLoader.isCurrentEvent(ExpressionGetEvent.class, ConstantGetEvent.class)) {
Skript.error("Return may only be used in custom expression getters.", ErrorQuality.SEMANTIC_ERROR);
return false;
}
if (!isDelayed.isTrue()) {
Skript.error("Return may not be used if the code before it contains any delays.", ErrorQuality.SEMANTIC_ERROR);
}
objects = SkriptUtil.defendExpression(exprs[0]);
return SkriptUtil.canInitSafely(objects);
}
}
| 28.721311 | 117 | 0.710616 |
5d8065b2c50cde874eae273c7c9345a39fcfb396 | 1,521 | package dagger.internal.codegen.collect;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
public class ImmutableSortedSet<T> extends ImmutableSet<T> {
private static final ImmutableSortedSet<?> EMPTY = new ImmutableSortedSet<>(Collections.emptySortedSet());
private ImmutableSortedSet(SortedSet<T> delegate) {
super(delegate);
}
public static <E extends Comparable<E>> Builder<E> naturalOrder() {
return new Builder<>(Comparator.<E>naturalOrder());
}
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<E> comparator,
Iterable<? extends E> elements) {
if (elements instanceof ImmutableSortedSet) {
return (ImmutableSortedSet<E>) elements;
}
TreeSet<E> result = new TreeSet<>(comparator);
elements.forEach(result::add);
return new ImmutableSortedSet<>(result);
}
public static final class Builder<E> {
private final TreeSet<E> delegate;
public Builder(Comparator<E> comparator) {
this.delegate = new TreeSet<>(comparator);
}
public Builder<E> add(E element) {
delegate.add(element);
return this;
}
public Builder<E> addAll(Collection<E> elements) {
delegate.addAll(elements);
return this;
}
public ImmutableSortedSet<E> build() {
return new ImmutableSortedSet<>(delegate);
}
}
public static <E> ImmutableSortedSet<E> of() {
return (ImmutableSortedSet<E>) EMPTY;
}
}
| 26.224138 | 108 | 0.694938 |
a3a70e4e7885d40bdef57ee45b48f120797cba13 | 260 | package io.basc.framework.factory;
/**
* 对一个创建者的定义
*
* @author shuchaowen
*
* @param <T> 返回结果类型
* @param <E> 异常类型
*/
@FunctionalInterface
public interface Creator<T, E extends Throwable> {
/**
* 创建一个对象
*
* @return
*/
T create() throws E;
}
| 13 | 50 | 0.619231 |
d0ba198496ae0d90602edb2cb4b06fca77b74619 | 491 | package com.snowball.location.transport_api.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@JsonIgnoreProperties({"opening_hours", "photos", "rating"})
public class GooglePlace {
@JsonProperty("formatted_address")
@Getter @Setter protected String address;
@Getter @Setter protected GoogleGeometry geometry;
@Getter @Setter protected String name;
}
| 28.882353 | 61 | 0.792261 |
eac01e08e133f2df92bf6062afd61500e2d41741 | 7,558 | package com.svcg.StockCustom.service.impl;
import com.svcg.StockCustom.component.Messages;
import com.svcg.StockCustom.enums.RolName;
import com.svcg.StockCustom.repository.RolRepository;
import com.svcg.StockCustom.repository.UserRepository;
import com.svcg.StockCustom.service.UserService;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
@Service("userServiceImpl")
public class UserServiceImpl implements UserDetailsService, UserService {
@Autowired
@Qualifier("userRepository")
private UserRepository userRepository;
@Autowired
@Qualifier("rolRepository")
private RolRepository rolRepository;
@Autowired
Messages messages;
private static final Logger logger = LoggerFactory
.getLogger(UserServiceImpl.class);
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
com.svcg.StockCustom.entity.User user = userRepository.findByUsername(username);
List<GrantedAuthority> authorities = buildAuthorities(user);
return buildUser(user, authorities);
}
@Override
public com.svcg.StockCustom.entity.User saveUser(com.svcg.StockCustom.entity.User user) {
if (user == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, this.messages.get("MESSAGE_CANT_CREATE_USER"), null);
}
if (userNameExist(user.getUsername())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, this.messages.get("MESSAGE_USER_EXISTS") + user.getUsername(), null);
}
if (emailExist(user.getEmail())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, this.messages.get("MESSAGE_MAIL_EXISTS") + user.getEmail(), null);
}
if (user.getPassword() != null) {
user.setPassword(user.getPassword());
}
/**
* Guardo el usuario con sus roles
*/
user = saveUserAndRol(user);
return user;
}
/**
* Guardo el usuario con sus roles
*/
private com.svcg.StockCustom.entity.User saveUserAndRol(com.svcg.StockCustom.entity.User user) {
try {
user.setRol(rolRepository.findRolByNombre(user.getRol().getNombre()).get());
user = userRepository.save(user);
/**
* Devuelvo el user creado con el rol seteado
*/
} catch (Exception e) {
logger.error("Exception: {} ", e);
throw new ResponseStatusException(HttpStatus.CONFLICT, this.messages.get("MESSAGE_CANT_CREATE_USER"), null);
}
return user;
}
@Override
public com.svcg.StockCustom.entity.User updateUser(com.svcg.StockCustom.entity.User user) {
if (user == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, this.messages.get("MESSAGE_CANT_CREATE_USER"), null);
}
com.svcg.StockCustom.entity.User previousUser = userRepository.findByUsername(user.getUsername());
if (previousUser == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, this.messages.get("MESSAGE_NOT_FOUND_USUARIO"), null);
}
if (!previousUser.getEmail().equals(user.getEmail()) && emailExist(user.getEmail())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, this.messages.get("MESSAGE_MAIL_EXISTS") + user.getEmail());
}
user = saveUserAndRol(user);
return user;
}
@Override
public Page<com.svcg.StockCustom.entity.User> getUsers(Pageable pageable) {
Page<com.svcg.StockCustom.entity.User> users = userRepository.findAll(pageable);
if (users.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, this.messages.get("MESSAGE_NOT_FOUND_USUARIOS"), null);
}
return users;
}
private User buildUser(com.svcg.StockCustom.entity.User user, List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
private List<GrantedAuthority> buildAuthorities(com.svcg.StockCustom.entity.User user) {
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority(user.getRol().getNombre()));
authorities.add(new SimpleGrantedAuthority(user.getUserId().toString()));
return new ArrayList<>(authorities);
}
private boolean emailExist(String email) {
com.svcg.StockCustom.entity.User user = userRepository.findByEmail(email);
return user != null;
}
private boolean userNameExist(String username) {
com.svcg.StockCustom.entity.User user = userRepository.findByUsername(username);
return user != null;
}
@Override
public List<RolName> getRolesUsers() {
List<RolName> rolNames = Arrays.asList(RolName.values());
return rolNames;
}
@Override
public com.svcg.StockCustom.entity.User getUserByUsername(String username) {
com.svcg.StockCustom.entity.User user = userRepository.findByUsername(username);
if(user == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, this.messages.get("MESSAGE_NOT_FOUND_USUARIO"), null);
}
return user;
}
@Override
public com.svcg.StockCustom.entity.User getUserById(Long id) {
com.svcg.StockCustom.entity.User user = userRepository.findByUserId(id);
if(user == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, this.messages.get("MESSAGE_NOT_FOUND_USUARIO"), null);
}
return user;
}
public String obtenerToken(HttpServletRequest request) {
try {
String authorization = request.getHeader("authorization");
authorization = authorization.replace("Barer", "");
authorization = authorization.trim();
org.apache.tomcat.util.codec.binary.Base64 decoder = new Base64(true);
return new String(decoder.decode(authorization.getBytes()));
} catch (Exception e) {
logger.error("Error en obtenerToken" + e.getMessage());
throw new RuntimeException(e);
}
}
public JSONObject obtenerJsonDeToken(String token) {
try {
token = token.replace("}{", "}, {");
String[] split = token.split(", ");
return new JSONObject(split[1]);
} catch (Exception e) {
logger.error("Error en obtenerJsonDeToken" + e.getMessage());
throw new RuntimeException(e);
}
}
}
| 39.160622 | 139 | 0.689336 |
29dcf104927a3b04644c792f618b695feff75f8d | 6,628 | package uw.task.conf;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import uw.task.TaskCroner;
import uw.task.TaskData;
import uw.task.TaskRunner;
import uw.task.entity.TaskCronerConfig;
import uw.task.entity.TaskCronerLog;
import uw.task.entity.TaskRunnerConfig;
/**
* Task元信息管理器
* @author aexon,liliang
*/
public class TaskMetaInfoManager {
/**
* 运行主机配置
*/
static List<String> targetConfig = null;
/**
* Runner任务实例缓存。
*/
@SuppressWarnings("rawtypes")
static Map<String, TaskRunner> runnerMap = new HashMap<>();
/**
* Cron任务实例缓存。
*/
static Map<String, TaskCroner> cronerMap = new HashMap<>();
/**
* Runner任务配置缓存
*/
static ConcurrentHashMap<String, TaskRunnerConfig> runnerConfigMap = new ConcurrentHashMap<>();
/**
* Cron任务配置缓存。
*/
static ConcurrentHashMap<String, TaskCronerConfig> cronerConfigMap = new ConcurrentHashMap<>();
/**
* 获得任务运行实例。
*
* @param taskClass
* @return
*/
public static TaskRunner<?, ?> getRunner(String taskClass) {
return runnerMap.get(taskClass);
}
/**
* 检查一个runner是否可以在本地运行。
*
* @param taskData
* @return
*/
public static boolean checkRunnerRunLocal(TaskData<?, ?> taskData) {
return runnerMap.containsKey(taskData.getTaskClass());
}
/**
* 根据服务器端Queue列表,返回合适的key。
*
* @return
*/
public static String getFitQueue(TaskData<?, ?> data) {
StringBuilder sb = new StringBuilder(100);
sb.append(data.getTaskClass()).append("#");
if (data.getTaskTag() != null && data.getTaskTag().length() > 0) {
sb.append(data.getTaskTag());
}
sb.append("$");
if (data.getRunTarget() != null && data.getRunTarget().length() > 0) {
sb.append(data.getRunTarget());
}
String all = sb.toString();
if (runnerConfigMap.containsKey(all)) {
return all;
}
// 检测去除TAG的情况
if (!all.contains("#$")) {
String test = all.substring(0, all.indexOf('#') + 1) + all.substring(all.lastIndexOf('$'), all.length());
if (runnerConfigMap.containsKey(test)) {
return test;
}
}
// 检测去除目标的情况
if (!all.endsWith("$")) {
String test = all.substring(0, all.lastIndexOf('$') + 1);
if (runnerConfigMap.containsKey(test)) {
return test;
}
}
// 两个都去除的情况
if (!all.endsWith("#$")) {
String test = data.getTaskClass() + "#$";
if (runnerConfigMap.containsKey(test)) {
return test;
}
}
// 最后都没匹配到,返回原始数据
return all;
}
/**
* 获得任务配置
*
* @param data
* @return
*/
public static TaskRunnerConfig getRunnerConfig(TaskData<?, ?> data) {
TaskRunnerConfig config = null;
StringBuilder sb = new StringBuilder(100);
sb.append(data.getTaskClass()).append("#");
if (data.getTaskTag() != null && data.getTaskTag().length() > 0) {
sb.append(data.getTaskTag());
}
sb.append("$");
if (data.getRunTarget() != null && data.getRunTarget().length() > 0) {
sb.append(data.getRunTarget());
}
String all = sb.toString();
config = runnerConfigMap.get(all);
if (config != null) {
return config;
}
// 检测去除TAG的情况
if (!all.contains("#$")) {
String test = all.substring(0, all.indexOf('#') + 1) + all.substring(all.lastIndexOf('$'), all.length());
config = runnerConfigMap.get(test);
if (config != null) {
return config;
}
}
// 检测去除目标的情况
if (!all.endsWith("$")) {
String test = all.substring(0, all.lastIndexOf('$') + 1);
config = runnerConfigMap.get(test);
if (config != null) {
return config;
}
}
// 两个都去除的情况
if (!all.endsWith("#$")) {
String test = data.getTaskClass() + "#$";
config = runnerConfigMap.get(test);
if (config != null) {
return config;
}
}
throw new RuntimeException("找不到任务配置: taskClass = " + data.getTaskClass());
}
/**
* 更新系统队列表。
*
* @param config
*/
static void updateSysQueue(final TaskRunnerConfig config) {
String key = getRunnerConfigKey(config);
// 检测是否老的TaskRunnerConfig是否是本地的完整配置,如果是,则不管。
TaskRunnerConfig old = runnerConfigMap.get(key);
if (old == null || (old != null && old.getCreateDate() == null)) {
if (config.getState() < 1) {
runnerConfigMap.remove(key);
} else {
runnerConfigMap.put(key, config);
}
}
}
/**
* 获得croner配置键。 使用taskClass#Id$target来配置
*
* @return
*/
public static String getCronerConfigKey(TaskCronerConfig config) {
StringBuilder sb = new StringBuilder(100);
sb.append(config.getTaskClass()).append("#");
if (config.getTaskParam() != null && config.getTaskParam().length() > 0) {
sb.append(config.getId());
}
sb.append("$");
if (config.getRunTarget() != null && config.getRunTarget().length() > 0) {
sb.append(config.getRunTarget());
}
return sb.toString();
}
/**
* 获得Runner配置结合Host。
*
* @return
*/
public static String getRunnerConfigKey(TaskRunnerConfig config) {
StringBuilder sb = new StringBuilder(100);
sb.append(config.getTaskClass()).append("#");
if (config.getTaskTag() != null && config.getTaskTag().length() > 0) {
sb.append(config.getTaskTag());
}
sb.append("$");
if (config.getRunTarget() != null && config.getRunTarget().length() > 0) {
sb.append(config.getRunTarget());
}
return sb.toString();
}
/**
* 获得RunnerLog配置KEY
*
* @return
*/
public static String getRunnerLogKey(TaskData<?,?> log) {
StringBuilder sb = new StringBuilder(100);
sb.append(log.getTaskClass()).append("#");
if (log.getTaskTag() != null && log.getTaskTag().length() > 0) {
sb.append(log.getTaskTag());
}
sb.append("$");
if (log.getRunTarget() != null && log.getRunTarget().length() > 0) {
sb.append(log.getRunTarget());
}
return sb.toString();
}
/**
* 获得CronerLog配置KEY
*
* @return
*/
public static String getCronerLogKey(TaskCronerLog log) {
StringBuilder sb = new StringBuilder(100);
sb.append(log.getTaskClass()).append("#");
if (log.getTaskParam() != null && log.getTaskParam().length()>0){
sb.append(log.getTaskParam());
}
sb.append("$");
if (log.getRunTarget() != null && log.getRunTarget().length() > 0) {
sb.append(log.getRunTarget());
}
return sb.toString();
}
}
| 26.512 | 118 | 0.587508 |
beba4209591822b6901698bbb12dcbeab420bf2c | 58,435 | /*
* 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.oodt.cas.filemgr.system;
import org.apache.oodt.cas.filemgr.catalog.Catalog;
import org.apache.oodt.cas.filemgr.datatransfer.DataTransfer;
import org.apache.oodt.cas.filemgr.datatransfer.TransferStatusTracker;
import org.apache.oodt.cas.filemgr.metadata.ProductMetKeys;
import org.apache.oodt.cas.filemgr.metadata.extractors.FilemgrMetExtractor;
import org.apache.oodt.cas.filemgr.repository.RepositoryManager;
import org.apache.oodt.cas.filemgr.structs.Element;
import org.apache.oodt.cas.filemgr.structs.ExtractorSpec;
import org.apache.oodt.cas.filemgr.structs.FileTransferStatus;
import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.ProductPage;
import org.apache.oodt.cas.filemgr.structs.ProductType;
import org.apache.oodt.cas.filemgr.structs.Query;
import org.apache.oodt.cas.filemgr.structs.Reference;
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.filemgr.structs.exceptions.DataTransferException;
import org.apache.oodt.cas.filemgr.structs.exceptions.QueryFormulationException;
import org.apache.oodt.cas.filemgr.structs.exceptions.RepositoryManagerException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ValidationLayerException;
import org.apache.oodt.cas.filemgr.structs.exceptions.VersioningException;
import org.apache.oodt.cas.filemgr.structs.query.ComplexQuery;
import org.apache.oodt.cas.filemgr.structs.query.QueryFilter;
import org.apache.oodt.cas.filemgr.structs.query.QueryResult;
import org.apache.oodt.cas.filemgr.structs.query.QueryResultComparator;
import org.apache.oodt.cas.filemgr.structs.query.filter.ObjectTimeEvent;
import org.apache.oodt.cas.filemgr.structs.query.filter.TimeEvent;
import org.apache.oodt.cas.filemgr.structs.type.TypeHandler;
import org.apache.oodt.cas.filemgr.util.GenericFileManagerObjectFactory;
import org.apache.oodt.cas.filemgr.util.XmlRpcStructFactory;
import org.apache.oodt.cas.filemgr.versioning.Versioner;
import org.apache.oodt.cas.filemgr.versioning.VersioningUtils;
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.metadata.exceptions.MetExtractionException;
import org.apache.oodt.commons.date.DateUtils;
import org.apache.xmlrpc.WebServer;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author mattmann
* @author bfoster
* @version $Revision$
* <p/>
* <p> An XML RPC-based File manager. </p>
*/
public class XmlRpcFileManager {
/* the port to run the XML RPC web server on, default is 1999 */
private int webServerPort = 1999;
/* our Catalog */
private Catalog catalog = null;
/* our RepositoryManager */
private RepositoryManager repositoryManager = null;
/* our DataTransfer */
private DataTransfer dataTransfer = null;
/* our log stream */
private static final Logger LOG = Logger.getLogger(XmlRpcFileManager.class.getName());
/* our xml rpc web server */
private WebServer webServer = null;
/* our data transfer status tracker */
private TransferStatusTracker transferStatusTracker = null;
/* whether or not to expand a product instance into met */
private boolean expandProductMet;
/**
* <p> Creates a new XmlRpcFileManager with the given metadata store factory, and the given data store factory, on the
* given port. </p>
*
* @param port The web server port to run the XML Rpc server on, defaults to 1999.
*/
public XmlRpcFileManager(int port) throws IOException {
webServerPort = port;
// start up the web server
webServer = new WebServer(webServerPort);
webServer.addHandler("filemgr", this);
webServer.start();
this.loadConfiguration();
LOG.log(Level.INFO, "File Manager started by "
+ System.getProperty("user.name", "unknown"));
}
public void setCatalog(Catalog catalog) {
this.catalog = catalog;
}
public boolean isAlive() {
return true;
}
public boolean refreshConfigAndPolicy() {
boolean status = false;
try {
this.loadConfiguration();
status = true;
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG
.log(
Level.SEVERE,
"Unable to refresh configuration for file manager " +
"server: server may be in inoperable state: Message: "
+ e.getMessage());
}
return status;
}
public boolean transferringProduct(Hashtable<String, Object> productHash) {
return this.transferringProductCore(productHash);
}
public boolean transferringProductCore(Map<String, Object> productHash) {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
transferStatusTracker.transferringProduct(p);
return true;
}
public Map<String, Object> getCurrentFileTransferCore() {
FileTransferStatus status = transferStatusTracker
.getCurrentFileTransfer();
if (status == null) {
return new ConcurrentHashMap<String, Object>();
} else {
return XmlRpcStructFactory.getXmlRpcFileTransferStatus(status);
}
}
public List<Map<String, Object>> getCurrentFileTransfers() {
List<FileTransferStatus> currentTransfers = transferStatusTracker.getCurrentFileTransfers();
if (currentTransfers != null && currentTransfers.size() > 0) {
return XmlRpcStructFactory
.getXmlRpcFileTransferStatuses(currentTransfers);
} else {
return new Vector<Map<String, Object>>();
}
}
public double getProductPctTransferred(Hashtable<String, Object> productHash) {
return this.getProductPctTransferredCore(productHash);
}
public double getProductPctTransferredCore(Map<String, Object> productHash) {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return transferStatusTracker.getPctTransferred(product);
}
public double getRefPctTransferred(Hashtable<String, Object> refHash) {
return getRefPctTransferredCore(refHash);
}
public double getRefPctTransferredCore(Map<String, Object> refHash) {
Reference reference = XmlRpcStructFactory
.getReferenceFromXmlRpc(refHash);
double pct = 0.0;
try {
pct = transferStatusTracker.getPctTransferred(reference);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.WARNING,
"Exception getting transfer percentage for ref: ["
+ reference.getOrigReference() + "]: Message: "
+ e.getMessage());
}
return pct;
}
public boolean removeProductTransferStatus(Hashtable<String, Object> productHash) {
return removeProductTransferStatusCore(productHash);
}
public boolean removeProductTransferStatusCore(Map<String, Object> productHash) {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
transferStatusTracker.removeProductTransferStatus(product);
return true;
}
public boolean isTransferComplete(Hashtable<String, Object> productHash) {
return this.isTransferCompleteCore(productHash);
}
public boolean isTransferCompleteCore(Map<String, Object> productHash) {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return transferStatusTracker.isTransferComplete(product);
}
public Map<String, Object> pagedQuery(
Hashtable<String, Object> queryHash,
Hashtable<String, Object> productTypeHash,
int pageNum) throws CatalogException {
return this.pagedQueryCore(queryHash, productTypeHash, pageNum);
}
public Map<String, Object> pagedQueryCore(
Map<String, Object> queryHash,
Map<String, Object> productTypeHash,
int pageNum) throws CatalogException {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
Query query = XmlRpcStructFactory.getQueryFromXmlRpc(queryHash);
ProductPage prodPage;
try {
prodPage = catalog.pagedQuery(this.getCatalogQuery(query, type), type, pageNum);
if (prodPage == null) {
prodPage = ProductPage.blankPage();
} else {
// it is possible here that the underlying catalog did not
// set the ProductType
// to obey the contract of the File Manager, we need to make
// sure its set here
setProductType(prodPage.getPageProducts());
}
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.WARNING,
"Catalog exception performing paged query for product type: ["
+ type.getProductTypeId() + "] query: [" + query
+ "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
return XmlRpcStructFactory.getXmlRpcProductPage(prodPage);
}
public Map<String, Object> getFirstPage(
Hashtable<String, Object> productTypeHash) {
return this.getFirstPageCore(productTypeHash);
}
public Map<String, Object> getFirstPageCore(
Map<String, Object> productTypeHash) {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
ProductPage page = catalog.getFirstPage(type);
try {
setProductType(page.getPageProducts());
} catch (Exception e) {
LOG.log(Level.WARNING,
"Unable to set product types for product page list: ["
+ page + "]");
}
return XmlRpcStructFactory.getXmlRpcProductPage(page);
}
public Map<String, Object> getLastPage(
Hashtable<String, Object> productTypeHash) {
return this.getLastPageCore(productTypeHash);
}
public Map<String, Object> getLastPageCore(
Map<String, Object> productTypeHash) {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
ProductPage page = catalog.getLastProductPage(type);
try {
setProductType(page.getPageProducts());
} catch (Exception e) {
LOG.log(Level.WARNING,
"Unable to set product types for product page list: ["
+ page + "]");
}
return XmlRpcStructFactory.getXmlRpcProductPage(page);
}
public Map<String, Object> getNextPage(
Hashtable<String, Object> productTypeHash,
Hashtable<String, Object> currentPageHash) {
return this.getNextPageCore(productTypeHash, currentPageHash);
}
public Map<String, Object> getNextPageCore(
Map<String, Object> productTypeHash,
Map<String, Object> currentPageHash) {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
ProductPage currPage = XmlRpcStructFactory
.getProductPageFromXmlRpc(currentPageHash);
ProductPage page = catalog.getNextPage(type, currPage);
try {
setProductType(page.getPageProducts());
} catch (Exception e) {
LOG.log(Level.WARNING,
"Unable to set product types for product page list: ["
+ page + "]");
}
return XmlRpcStructFactory.getXmlRpcProductPage(page);
}
public Map<String, Object> getPrevPage(
Hashtable<String, Object> productTypeHash,
Hashtable<String, Object> currentPageHash) {
return this.getPrevPageCore(productTypeHash, currentPageHash);
}
public Map<String, Object> getPrevPageCore(
Map<String, Object> productTypeHash,
Map<String, Object> currentPageHash) {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
ProductPage currPage = XmlRpcStructFactory
.getProductPageFromXmlRpc(currentPageHash);
ProductPage page = catalog.getPrevPage(type, currPage);
try {
setProductType(page.getPageProducts());
} catch (Exception e) {
LOG.log(Level.WARNING,
"Unable to set product types for product page list: ["
+ page + "]");
}
return XmlRpcStructFactory.getXmlRpcProductPage(page);
}
public String addProductType(Hashtable<String, Object> productTypeHash)
throws RepositoryManagerException {
return this.addProductTypeCore(productTypeHash);
}
public String addProductTypeCore(Map<String, Object> productTypeHash)
throws RepositoryManagerException {
ProductType productType = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
repositoryManager.addProductType(productType);
return productType.getProductTypeId();
}
public synchronized boolean setProductTransferStatus(
Hashtable<String, Object> productHash)
throws CatalogException {
return this.setProductTransferStatusCore(productHash);
}
public synchronized boolean setProductTransferStatusCore(
Map<String, Object> productHash)
throws CatalogException {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
catalog.setProductTransferStatus(product);
return true;
}
public int getNumProducts(Hashtable<String, Object> productTypeHash)
throws CatalogException {
return this.getNumProductsCore(productTypeHash);
}
public int getNumProductsCore(Map<String, Object> productTypeHash)
throws CatalogException {
int numProducts;
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
try {
numProducts = catalog.getNumProducts(type);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.WARNING,
"Exception when getting num products: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
return numProducts;
}
public List<Map<String, Object>> getTopNProducts(int n)
throws CatalogException {
List<Product> topNProducts;
try {
topNProducts = catalog.getTopNProducts(n);
return XmlRpcStructFactory.getXmlRpcProductList(topNProducts);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.WARNING,
"Exception when getting topN products: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public List<Map<String, Object>> getTopNProducts(int n,
Hashtable<String, Object> productTypeHash)
throws CatalogException {
return this.getTopNProductsCore(n, productTypeHash);
}
public List<Map<String, Object>> getTopNProductsCore(int n,
Map<String, Object> productTypeHash)
throws CatalogException {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
List<Product> topNProducts;
try {
topNProducts = catalog.getTopNProducts(n, type);
return XmlRpcStructFactory.getXmlRpcProductList(topNProducts);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.WARNING,
"Exception when getting topN products by product type: ["
+ type.getProductTypeId() + "]: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public boolean hasProduct(String productName) throws CatalogException {
Product p = catalog.getProductByName(productName);
return p != null
&& p.getTransferStatus().equals(Product.STATUS_RECEIVED);
}
public Map<String, Object> getMetadata(
Hashtable<String, Object> productHash) throws CatalogException {
return this.getMetadataCore(productHash);
}
public Map<String, Object> getMetadataCore(
Map<String, Object> productHash) throws CatalogException {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return this.getMetadata(product).getHashTable();
}
public Map<String, Object> getReducedMetadata(
Hashtable<String, Object> productHash, Vector<String> elements)
throws CatalogException {
return this.getReducedMetadataCore(productHash, elements);
}
public Map<String, Object> getReducedMetadataCore(
Map<String, Object> productHash, Vector<String> elements)
throws CatalogException {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return this.getReducedMetadata(product, elements).getHashTable();
}
public List<Map<String, Object>> getProductTypes()
throws RepositoryManagerException {
List<ProductType> productTypeList;
try {
productTypeList = repositoryManager.getProductTypes();
return XmlRpcStructFactory
.getXmlRpcProductTypeList(productTypeList);
} catch (RepositoryManagerException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Unable to obtain product types from repository manager: Message: "
+ e.getMessage());
throw new RepositoryManagerException(e.getMessage(), e);
}
}
public List<Map<String, Object>> getProductReferences(
Hashtable<String, Object> productHash)
throws CatalogException {
return this.getProductReferencesCore(productHash);
}
public List<Map<String, Object>> getProductReferencesCore(
Map<String, Object> productHash)
throws CatalogException {
List<Reference> referenceList;
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
try {
referenceList = catalog.getProductReferences(product);
return XmlRpcStructFactory.getXmlRpcReferences(referenceList);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "Unable to obtain references for product: ["
+ product.getProductName() + "]: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public Map<String, Object> getProductById(String productId)
throws CatalogException {
Product product = null;
try {
product = catalog.getProductById(productId);
// it is possible here that the underlying catalog did not
// set the ProductType
// to obey the contract of the File Manager, we need to make
// sure its set here
product.setProductType(this.repositoryManager
.getProductTypeById(product.getProductType()
.getProductTypeId()));
return XmlRpcStructFactory.getXmlRpcProduct(product);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "Unable to obtain product by id: ["
+ productId + "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
} catch (RepositoryManagerException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "Unable to obtain product type by id: ["
+ product.getProductType().getProductTypeId()
+ "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public Map<String, Object> getProductByName(String productName)
throws CatalogException {
Product product = null;
try {
product = catalog.getProductByName(productName);
// it is possible here that the underlying catalog did not
// set the ProductType
// to obey the contract of the File Manager, we need to make
// sure its set here
product.setProductType(this.repositoryManager
.getProductTypeById(product.getProductType()
.getProductTypeId()));
return XmlRpcStructFactory.getXmlRpcProduct(product);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "Unable to obtain product by name: ["
+ productName + "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
} catch (RepositoryManagerException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "Unable to obtain product type by id: ["
+ product.getProductType().getProductTypeId()
+ "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public List<Map<String, Object>> getProductsByProductType(
Hashtable<String, Object> productTypeHash)
throws CatalogException {
return this.getProductsByProductTypeCore(productTypeHash);
}
public List<Map<String, Object>> getProductsByProductTypeCore(
Map<String, Object> productTypeHash)
throws CatalogException {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
List<Product> productList;
try {
productList = catalog.getProductsByProductType(type);
return XmlRpcStructFactory.getXmlRpcProductList(productList);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception obtaining products by product type for type: ["
+ type.getName() + "]: Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
public List<Map<String, Object>> getElementsByProductType(
Map<String, Object> productTypeHash)
throws ValidationLayerException {
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
List<Element> elementList;
try {
elementList = catalog.getValidationLayer().getElements(type);
return XmlRpcStructFactory.getXmlRpcElementList(elementList);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception obtaining elements for product type: ["
+ type.getName() + "]: Message: " + e.getMessage());
throw new ValidationLayerException(e.getMessage(), e);
}
}
public Map<String, Object> getElementById(String elementId)
throws ValidationLayerException {
Element element;
try {
element = catalog.getValidationLayer().getElementById(elementId);
return XmlRpcStructFactory.getXmlRpcElement(element);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "exception retrieving element by id: ["
+ elementId + "]: Message: " + e.getMessage());
throw new ValidationLayerException(e.getMessage(), e);
}
}
public Map<String, Object> getElementByName(String elementName)
throws ValidationLayerException {
Element element;
try {
element = catalog.getValidationLayer()
.getElementByName(elementName);
return XmlRpcStructFactory.getXmlRpcElement(element);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "exception retrieving element by name: ["
+ elementName + "]: Message: " + e.getMessage());
throw new ValidationLayerException(e.getMessage(), e);
}
}
public List<Map<String, Object>> complexQuery(Hashtable<String, Object> complexQueryHash) throws CatalogException {
return this.complexQueryCore(complexQueryHash);
}
public List<Map<String, Object>> complexQueryCore(
Map<String, Object> complexQueryHash) throws CatalogException {
try {
ComplexQuery complexQuery = XmlRpcStructFactory
.getComplexQueryFromXmlRpc(complexQueryHash);
// get ProductTypes
List<ProductType> productTypes;
if (complexQuery.getReducedProductTypeNames() == null) {
productTypes = this.repositoryManager.getProductTypes();
} else {
productTypes = new Vector<ProductType>();
for (String productTypeName : complexQuery
.getReducedProductTypeNames()) {
productTypes.add(this.repositoryManager
.getProductTypeByName(productTypeName));
}
}
// get Metadata
List<QueryResult> queryResults = new LinkedList<QueryResult>();
for (ProductType productType : productTypes) {
List<String> productIds = catalog.query(this.getCatalogQuery(
complexQuery, productType), productType);
for (String productId : productIds) {
Product product = catalog.getProductById(productId);
product.setProductType(productType);
QueryResult qr = new QueryResult(product, this
.getReducedMetadata(product, complexQuery
.getReducedMetadata()));
qr.setToStringFormat(complexQuery
.getToStringResultFormat());
queryResults.add(qr);
}
}
LOG.log(Level.INFO, "Query returned " + queryResults.size()
+ " results");
// filter query results
if (complexQuery.getQueryFilter() != null) {
queryResults = applyFilterToResults(queryResults, complexQuery
.getQueryFilter());
LOG.log(Level.INFO, "Filter returned " + queryResults.size()
+ " results");
}
// sort query results
if (complexQuery.getSortByMetKey() != null) {
queryResults = sortQueryResultList(queryResults, complexQuery
.getSortByMetKey());
}
return XmlRpcStructFactory.getXmlRpcQueryResults(queryResults);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
throw new CatalogException("Failed to perform complex query : "
+ e.getMessage(), e);
}
}
public List<Map<String, Object>> query(
Hashtable<String, Object> queryHash,
Hashtable<String, Object> productTypeHash)
throws CatalogException {
return this.queryCore(queryHash, productTypeHash);
}
public List<Map<String, Object>> queryCore(
Map<String, Object> queryHash,
Map<String, Object> productTypeHash)
throws CatalogException {
Query query = XmlRpcStructFactory.getQueryFromXmlRpc(queryHash);
ProductType type = XmlRpcStructFactory
.getProductTypeFromXmlRpc(productTypeHash);
return XmlRpcStructFactory.getXmlRpcProductList(this.query(query, type));
}
public Map<String, Object> getProductTypeByName(String productTypeName)
throws RepositoryManagerException {
ProductType type = repositoryManager
.getProductTypeByName(productTypeName);
return XmlRpcStructFactory.getXmlRpcProductType(type);
}
public Map<String, Object> getProductTypeById(String productTypeId)
throws RepositoryManagerException {
ProductType type;
try {
type = repositoryManager.getProductTypeById(productTypeId);
return XmlRpcStructFactory.getXmlRpcProductType(type);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception obtaining product type by id for product type: ["
+ productTypeId + "]: Message: " + e.getMessage());
throw new RepositoryManagerException(e.getMessage(), e);
}
}
public synchronized boolean updateMetadata(Hashtable<String, Object> productHash,
Hashtable<String, Object> metadataHash) throws CatalogException {
return this.updateMetadataCore(productHash, metadataHash);
}
public synchronized boolean updateMetadataCore(Map<String, Object> productHash,
Map<String, Object> metadataHash) throws CatalogException {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
Metadata met = new Metadata();
met.addMetadata(metadataHash);
Metadata oldMetadata = catalog.getMetadata(product);
catalog.removeMetadata(oldMetadata, product);
catalog.addMetadata(met, product);
return true;
}
public synchronized String catalogProduct(Hashtable<String, Object> productHash)
throws CatalogException {
return this.catalogProductCore(productHash);
}
public synchronized String catalogProductCore(Map<String, Object> productHash)
throws CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return catalogProduct(p);
}
public synchronized boolean addMetadata(Hashtable<String, Object> productHash,
Hashtable<String, String> metadata) throws CatalogException {
return this.addMetadataCore(productHash, metadata);
}
public synchronized boolean addMetadataCore(Map<String, Object> productHash,
Map<String, String> metadata) throws CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
Metadata m = new Metadata();
m.addMetadata((Map) metadata);
return addMetadata(p, m) != null;
}
public synchronized boolean addProductReferencesCore(Map<String, Object> productHash)
throws CatalogException {
Product product = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
return addProductReferences(product);
}
public synchronized boolean addProductReferences(Hashtable<String, Object> productHash)
throws CatalogException {
return this.addProductReferencesCore(productHash);
}
public String ingestProduct(Hashtable<String, Object> ph, Hashtable<String, String> m, boolean ct)
throws CatalogException {
return this.ingestProductCore(ph, m, ct);
}
public String ingestProductCore(Map<String, Object> productHash,
Map<String, String> metadata, boolean clientTransfer)
throws
CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
try {
// first, create the product
p.setTransferStatus(Product.STATUS_TRANSFER);
catalogProduct(p);
// now add the metadata
Metadata m = new Metadata();
m.addMetadata((Map) metadata);
Metadata expandedMetdata = addMetadata(p, m);
// version the product
if (!clientTransfer || (Boolean.getBoolean("org.apache.oodt.cas.filemgr.serverside.versioning"))) {
Versioner versioner;
try {
versioner = GenericFileManagerObjectFactory
.getVersionerFromClassName(p.getProductType().getVersioner());
if (versioner != null) {
versioner.createDataStoreReferences(p, expandedMetdata);
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"ingestProduct: VersioningException when versioning Product: "
+ p.getProductName() + " with Versioner "
+ p.getProductType().getVersioner() + ": Message: "
+ e.getMessage());
throw new VersioningException(e);
}
// add the newly versioned references to the data store
addProductReferences(p);
}
if (!clientTransfer) {
LOG.log(Level.FINEST,
"File Manager: ingest: no client transfer enabled, "
+ "server transfering product: [" + p.getProductName() + "]");
// now transfer the product
try {
dataTransfer.transferProduct(p);
// now update the product's transfer status in the data store
p.setTransferStatus(Product.STATUS_RECEIVED);
try {
catalog.setProductTransferStatus(p);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, "ingestProduct: CatalogException "
+ "when updating product transfer status for Product: "
+ p.getProductName() + " Message: " + e.getMessage());
throw e;
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"ingestProduct: DataTransferException when transfering Product: "
+ p.getProductName() + ": Message: " + e.getMessage());
throw new DataTransferException(e);
}
}
// that's it!
return p.getProductId();
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
throw new CatalogException("Error ingesting product [" + p + "] : "
+ e.getMessage(), e);
}
}
public byte[] retrieveFile(String filePath, int offset, int numBytes)
throws DataTransferException {
FileInputStream is = null;
try {
byte[] fileData = new byte[numBytes];
(is = new FileInputStream(filePath)).skip(offset);
int bytesRead = is.read(fileData);
if (bytesRead != -1) {
byte[] fileDataTruncated = new byte[bytesRead];
System.arraycopy(fileData, 0, fileDataTruncated, 0, bytesRead);
return fileDataTruncated;
} else {
return new byte[0];
}
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to read '" + numBytes
+ "' bytes from file '" + filePath + "' at index '" + offset
+ "' : " + e.getMessage(), e);
throw new DataTransferException("Failed to read '" + numBytes
+ "' bytes from file '" + filePath + "' at index '" + offset
+ "' : " + e.getMessage(), e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception ignored) {
}
}
}
public boolean transferFile(String filePath, byte[] fileData, int offset,
int numBytes) {
File outFile = new File(filePath);
boolean success = true;
FileOutputStream fOut = null;
if (outFile.exists()) {
try {
fOut = new FileOutputStream(outFile, true);
} catch (FileNotFoundException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"FileNotFoundException when trying to use RandomAccess file on "
+ filePath + ": Message: " + e.getMessage());
success = false;
}
finally {
try {
if (fOut != null) {
fOut.close();
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Could not close file stream", e.getMessage());
}
}
} else {
// create the output directory
String outFileDirPath = outFile.getAbsolutePath().substring(0,
outFile.getAbsolutePath().lastIndexOf("/"));
LOG.log(Level.INFO, "Outfile directory: " + outFileDirPath);
File outFileDir = new File(outFileDirPath);
outFileDir.mkdirs();
try {
fOut = new FileOutputStream(outFile, false);
} catch (FileNotFoundException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"FileNotFoundException when trying to use RandomAccess file on "
+ filePath + ": Message: " + e.getMessage());
success = false;
}
}
if (success) {
try {
fOut.write(fileData, (int) offset, (int) numBytes);
} catch (IOException e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE, "IOException when trying to write file "
+ filePath + ": Message: " + e.getMessage());
success = false;
} finally {
try {
fOut.close();
} catch (Exception ignore) {
}
}
}
return success;
}
public boolean moveProduct(Hashtable<String, Object> productHash, String newPath)
throws DataTransferException {
return this.moveProductCore(productHash, newPath);
}
public boolean moveProductCore(Map<String, Object> productHash, String newPath)
throws DataTransferException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
// first thing we care about is if the product is flat or heirarchical
if (p.getProductStructure().equals(Product.STRUCTURE_FLAT)) {
// we just need to get its first reference
if (p.getProductReferences() == null || (p.getProductReferences().size() != 1)) {
throw new DataTransferException(
"Flat products must have a single reference: cannot move");
}
// okay, it's fine to move it
// first, we need to update the data store ref
Reference r = p.getProductReferences().get(0);
if (r.getDataStoreReference().equals(
new File(newPath).toURI().toString())) {
throw new DataTransferException("cannot move product: ["
+ p.getProductName() + "] to same location: ["
+ r.getDataStoreReference() + "]");
}
// create a copy of the current data store path: we'll need it to
// do the data transfer
Reference copyRef = new Reference(r);
// update the copyRef to have the data store ref as the orig ref
// the the newLoc as the new ref
copyRef.setOrigReference(r.getDataStoreReference());
copyRef.setDataStoreReference(new File(newPath).toURI().toString());
p.getProductReferences().clear();
p.getProductReferences().add(copyRef);
// now transfer it
try {
this.dataTransfer.transferProduct(p);
} catch (IOException e) {
throw new DataTransferException(e);
}
// now delete the original copy
try {
if (!new File(new URI(copyRef.getOrigReference())).delete()) {
LOG.log(Level.WARNING, "Deletion of original file: ["
+ r.getDataStoreReference()
+ "] on product move returned false");
}
} catch (URISyntaxException e) {
throw new DataTransferException(
"URI Syntax exception trying to remove original product ref: Message: "
+ e.getMessage(), e);
}
// now save the updated reference
try {
this.catalog.modifyProduct(p);
return true;
} catch (CatalogException e) {
throw new DataTransferException(e.getMessage(), e);
}
} else {
throw new UnsupportedOperationException(
"Moving of heirarhical and stream products not supported yet");
}
}
public boolean removeFile(String filePath) throws DataTransferException, IOException {
// TODO(bfoster): Clean this up so that it deletes by product not file.
Product product = new Product();
Reference r = new Reference();
r.setDataStoreReference(filePath);
product.setProductReferences(Lists.newArrayList(r));
dataTransfer.deleteProduct(product);
return true;
}
public boolean modifyProduct(Hashtable<?, ?> productHash) throws CatalogException {
return this.modifyProductCore(productHash);
}
public boolean modifyProductCore(Map<?, ?> productHash) throws CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
try {
catalog.modifyProduct(p);
} catch (CatalogException e) {
LOG.log(Level.WARNING, "Exception modifying product: ["
+ p.getProductId() + "]: Message: " + e.getMessage(), e);
throw e;
}
return true;
}
public boolean removeProduct(Hashtable table) throws CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(table);
try {
catalog.removeProduct(p);
} catch (CatalogException e) {
LOG.log(Level.WARNING, "Exception modifying product: ["
+ p.getProductId() + "]: Message: " + e.getMessage(), e);
throw e;
}
return true;
}
public boolean removeProduct(Map<String, Object> productHash) throws CatalogException {
Product p = XmlRpcStructFactory.getProductFromXmlRpc(productHash);
try {
catalog.removeProduct(p);
} catch (CatalogException e) {
LOG.log(Level.WARNING, "Exception modifying product: ["
+ p.getProductId() + "]: Message: " + e.getMessage(), e);
throw e;
}
return true;
}
public Map<String, Object> getCatalogValues(
Hashtable<String, Object> metadataHash,
Hashtable<String, Object> productTypeHash)
throws RepositoryManagerException {
return this.getCatalogValuesCore(metadataHash, productTypeHash);
}
public Map<String, Object> getCatalogValuesCore(
Map<String, Object> metadataHash,
Map<String, Object> productTypeHash)
throws RepositoryManagerException {
Metadata m = new Metadata();
m.addMetadata(metadataHash);
ProductType productType = XmlRpcStructFactory.getProductTypeFromXmlRpc(productTypeHash);
return this.getCatalogValues(m, productType).getHashTable();
}
public Map<String, Object> getOrigValues(
Hashtable<String, Object> metadataHash,
Hashtable<String, Object> productTypeHash)
throws RepositoryManagerException {
return this.getOrigValuesCore(metadataHash, productTypeHash);
}
public Map<String, Object> getOrigValuesCore(
Map<String, Object> metadataHash,
Map<String, Object> productTypeHash)
throws RepositoryManagerException {
Metadata m = new Metadata();
m.addMetadata(metadataHash);
ProductType productType = XmlRpcStructFactory.getProductTypeFromXmlRpc(productTypeHash);
return this.getOrigValues(m, productType).getHashTable();
}
public Map<String, Object> getCatalogQuery(
Hashtable<String, Object> queryHash,
Hashtable<String, Object> productTypeHash)
throws RepositoryManagerException, QueryFormulationException {
return this.getCatalogQueryCore(queryHash, productTypeHash);
}
public Map<String, Object> getCatalogQueryCore(
Map<String, Object> queryHash,
Map<String, Object> productTypeHash)
throws RepositoryManagerException, QueryFormulationException {
Query query = XmlRpcStructFactory.getQueryFromXmlRpc(queryHash);
ProductType productType = XmlRpcStructFactory.getProductTypeFromXmlRpc(productTypeHash);
return XmlRpcStructFactory.getXmlRpcQuery(this.getCatalogQuery(query, productType));
}
public static void main(String[] args) throws IOException {
int portNum = -1;
String usage = "FileManager --portNum <port number for xml rpc service>\n";
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--portNum")) {
portNum = Integer.parseInt(args[++i]);
}
}
if (portNum == -1) {
System.err.println(usage);
System.exit(1);
}
@SuppressWarnings("unused")
XmlRpcFileManager manager = new XmlRpcFileManager(portNum);
for (; ; ) {
try {
Thread.currentThread().join();
} catch (InterruptedException ignore) {
}
}
}
public boolean shutdown() {
if (this.webServer != null) {
this.webServer.shutdown();
this.webServer = null;
return true;
} else {
return false;
}
}
private synchronized String catalogProduct(Product p)
throws CatalogException {
try {
catalog.addProduct(p);
} catch (CatalogException e) {
LOG.log(Level.SEVERE,
"ingestProduct: CatalogException when adding Product: "
+ p.getProductName() + " to Catalog: Message: "
+ e.getMessage());
throw e;
}
return p.getProductId();
}
private synchronized Metadata addMetadata(Product p, Metadata m)
throws CatalogException {
//apply handlers
try {
m = this.getCatalogValues(m, p.getProductType());
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to get handlers for product '" + p
+ "' : " + e.getMessage());
}
// first do server side metadata extraction
Metadata metadata = runExtractors(p, m);
try {
catalog.addMetadata(metadata, p);
} catch (CatalogException e) {
LOG.log(Level.SEVERE,
"ingestProduct: CatalogException when adding metadata "
+ metadata + " for product: " + p.getProductName()
+ ": Message: " + e.getMessage());
throw e;
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"ingestProduct: General Exception when adding metadata "
+ metadata + " for product: " + p.getProductName()
+ ": Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
return metadata;
}
private Metadata runExtractors(Product product, Metadata metadata) throws CatalogException {
// make sure that the product type definition is present
if (product.getProductType() == null) {
LOG.log(Level.SEVERE, "Failed to run extractor for: " + product.getProductId() + ":" + product
.getProductName() + " product type cannot be null.");
throw new CatalogException("Failed to run extractor for: " + product.getProductId() + ":" + product
.getProductName() + " product type cannot be null.");
}
try {
product.setProductType(repositoryManager.getProductTypeById(product
.getProductType().getProductTypeId()));
} catch (RepositoryManagerException e) {
LOG.log(Level.SEVERE, "Failed to load ProductType " + product
.getProductType().getProductTypeId(), e);
return null;
}
Metadata met = new Metadata();
met.addMetadata(metadata.getHashTable());
if (product.getProductType().getExtractors() != null) {
for (ExtractorSpec spec : product.getProductType().getExtractors()) {
FilemgrMetExtractor extractor = GenericFileManagerObjectFactory
.getExtractorFromClassName(spec.getClassName());
if (extractor != null) {
extractor.configure(spec.getConfiguration());
}
LOG.log(Level.INFO, "Running Met Extractor: ["
+ (extractor != null ? extractor.getClass().getName() : null)
+ "] for product type: ["
+ product.getProductType().getName() + "]");
try {
met = extractor != null ? extractor.extractMetadata(product, met) : null;
} catch (MetExtractionException e) {
LOG.log(Level.SEVERE,
"Exception extractor metadata from product: ["
+ product.getProductName()
+ "]: using extractor: ["
+ extractor.getClass().getName()
+ "]: Message: " + e.getMessage(), e);
}
}
}
return met;
}
private synchronized boolean addProductReferences(Product product)
throws CatalogException {
catalog.addProductReferences(product);
return true;
}
private void setProductType(List<Product> products) throws RepositoryManagerException {
if (products != null && products.size() > 0) {
for (Product p : products) {
p.setProductType(repositoryManager.getProductTypeById(p
.getProductType().getProductTypeId()));
}
}
}
private List<Product> query(Query query, ProductType productType) throws CatalogException {
List<String> productIdList;
List<Product> productList;
try {
productIdList = catalog.query(this.getCatalogQuery(query, productType), productType);
if (productIdList != null && productIdList.size() > 0) {
productList = new Vector<Product>(productIdList.size());
for (String productId : productIdList) {
Product product = catalog.getProductById(productId);
// it is possible here that the underlying catalog did not
// set the ProductType
// to obey the contract of the File Manager, we need to make
// sure its set here
product.setProductType(this.repositoryManager
.getProductTypeById(product.getProductType()
.getProductTypeId()));
productList.add(product);
}
return productList;
} else {
return new Vector<Product>(); // null values not supported by XML-RPC
}
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception performing query against catalog for product type: ["
+ productType.getName() + "] Message: " + e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
private Metadata getReducedMetadata(Product product, List<String> elements) throws CatalogException {
try {
Metadata m;
if (elements != null && elements.size() > 0) {
m = catalog.getReducedMetadata(product, elements);
} else {
m = this.getMetadata(product);
}
if (this.expandProductMet) {
m = this.buildProductMetadata(product, m);
}
return this.getOrigValues(m, product.getProductType());
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception obtaining metadata from catalog for product: ["
+ product.getProductId() + "]: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
private Metadata getMetadata(Product product) throws CatalogException {
try {
Metadata m = catalog.getMetadata(product);
if (this.expandProductMet) {
m = this.buildProductMetadata(product, m);
}
return this.getOrigValues(m, product.getProductType());
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
LOG.log(Level.SEVERE,
"Exception obtaining metadata from catalog for product: ["
+ product.getProductId() + "]: Message: "
+ e.getMessage());
throw new CatalogException(e.getMessage(), e);
}
}
private Metadata getOrigValues(Metadata metadata, ProductType productType)
throws RepositoryManagerException {
List<TypeHandler> handlers = this.repositoryManager.getProductTypeById(
productType.getProductTypeId()).getHandlers();
if (handlers != null) {
for (TypeHandler handler : handlers) {
handler.postGetMetadataHandle(metadata);
}
}
return metadata;
}
private Metadata getCatalogValues(Metadata metadata, ProductType productType)
throws RepositoryManagerException {
List<TypeHandler> handlers = this.repositoryManager.getProductTypeById(
productType.getProductTypeId()).getHandlers();
if (handlers != null) {
for (TypeHandler handler : handlers) {
handler.preAddMetadataHandle(metadata);
}
}
return metadata;
}
private Query getCatalogQuery(Query query, ProductType productType)
throws RepositoryManagerException, QueryFormulationException {
List<TypeHandler> handlers = this.repositoryManager.getProductTypeById(
productType.getProductTypeId()).getHandlers();
if (handlers != null) {
for (TypeHandler handler : handlers) {
handler.preQueryHandle(query);
}
}
return query;
}
@SuppressWarnings("unchecked")
private List<QueryResult> applyFilterToResults(
List<QueryResult> queryResults, QueryFilter queryFilter)
throws Exception {
List<TimeEvent> events = new LinkedList<TimeEvent>();
for (QueryResult queryResult : queryResults) {
Metadata m = new Metadata();
m.addMetadata(queryFilter.getPriorityMetKey(), queryResult
.getMetadata().getMetadata(queryFilter.getPriorityMetKey()));
events.add(new ObjectTimeEvent<QueryResult>(
DateUtils.getTimeInMillis(DateUtils.toCalendar(queryResult
.getMetadata().getMetadata(queryFilter.getStartDateTimeMetKey()),
DateUtils.FormatType.UTC_FORMAT), DateUtils.julianEpoch),
DateUtils.getTimeInMillis(DateUtils.toCalendar(queryResult.getMetadata()
.getMetadata(queryFilter.getEndDateTimeMetKey()),
DateUtils.FormatType.UTC_FORMAT),
DateUtils.julianEpoch), queryFilter.getConverter()
.convertToPriority(this.getCatalogValues(m,
queryResult.getProduct().getProductType())
.getMetadata(queryFilter.getPriorityMetKey())),
queryResult));
}
events = queryFilter.getFilterAlgor().filterEvents(events);
List<QueryResult> filteredQueryResults = new LinkedList<QueryResult>();
for (TimeEvent event : events) {
filteredQueryResults.add(((ObjectTimeEvent<QueryResult>) event)
.getTimeObject());
}
return filteredQueryResults;
}
private List<QueryResult> sortQueryResultList(List<QueryResult> queryResults,
String sortByMetKey) {
QueryResult[] resultsArray = queryResults
.toArray(new QueryResult[queryResults.size()]);
QueryResultComparator qrComparator = new QueryResultComparator();
qrComparator.setSortByMetKey(sortByMetKey);
Arrays.sort(resultsArray, qrComparator);
return Arrays.asList(resultsArray);
}
private Metadata buildProductMetadata(Product product, Metadata metadata)
throws CatalogException {
Metadata pMet = new Metadata();
pMet.replaceMetadata(ProductMetKeys.PRODUCT_ID, product.getProductId() != null ?
product.getProductId() : "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_NAME, product.getProductName() != null ?
product.getProductName() : "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_STRUCTURE, product
.getProductStructure() != null ? product
.getProductStructure() : "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_TRANSFER_STATUS, product
.getTransferStatus() != null ? product
.getTransferStatus() : "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_ROOT_REFERENCE, product.getRootRef() != null ?
VersioningUtils
.getAbsolutePathFromUri(
product.getRootRef().getDataStoreReference())
: "unknown");
List<Reference> refs = product.getProductReferences();
if (refs == null || (refs.size() == 0)) {
refs = this.catalog.getProductReferences(product);
}
for (Reference r : refs) {
pMet.replaceMetadata(ProductMetKeys.PRODUCT_ORIG_REFS, r.getOrigReference() != null
? VersioningUtils
.getAbsolutePathFromUri(r.getOrigReference())
: "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_DATASTORE_REFS,
r.getDataStoreReference() != null ?
VersioningUtils.getAbsolutePathFromUri(r.getDataStoreReference()) : "unknown");
pMet.replaceMetadata(ProductMetKeys.PRODUCT_FILE_SIZES, String.valueOf(r
.getFileSize()));
pMet.replaceMetadata(ProductMetKeys.PRODUCT_MIME_TYPES,
r.getMimeType() != null ? r.getMimeType().getName() : "unknown");
}
return pMet;
}
private void loadConfiguration() throws IOException {
// set up the configuration, if there is any
if (System.getProperty("org.apache.oodt.cas.filemgr.properties") != null) {
String configFile = System
.getProperty("org.apache.oodt.cas.filemgr.properties");
LOG.log(Level.INFO,
"Loading File Manager Configuration Properties from: [" + configFile
+ "]");
System.getProperties().load(new FileInputStream(new File(configFile)));
}
String metaFactory, dataFactory, transferFactory;
metaFactory = System.getProperty("filemgr.catalog.factory",
"org.apache.oodt.cas.filemgr.catalog.DataSourceCatalogFactory");
dataFactory = System
.getProperty("filemgr.repository.factory",
"org.apache.oodt.cas.filemgr.repository.DataSourceRepositoryManagerFactory");
transferFactory = System.getProperty("filemgr.datatransfer.factory",
"org.apache.oodt.cas.filemgr.datatransfer.LocalDataTransferFactory");
catalog = GenericFileManagerObjectFactory
.getCatalogServiceFromFactory(metaFactory);
repositoryManager = GenericFileManagerObjectFactory
.getRepositoryManagerServiceFromFactory(dataFactory);
dataTransfer = GenericFileManagerObjectFactory
.getDataTransferServiceFromFactory(transferFactory);
transferStatusTracker = new TransferStatusTracker(catalog);
// got to start the server before setting up the transfer client since
// it
// checks for a live server
dataTransfer
.setFileManagerUrl(new URL("http://localhost:" + webServerPort));
expandProductMet = Boolean
.getBoolean("org.apache.oodt.cas.filemgr.metadata.expandProduct");
}
}
| 37.267219 | 120 | 0.657448 |
ffda27d00d3706cb265d6a178c96cd49362e36cd | 1,992 | package net.TheElm.project.mixins.Server;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import net.TheElm.project.interfaces.WhitelistedPlayer;
import net.TheElm.project.mixins.Interfaces.WhitelistAccessor;
import net.minecraft.server.ServerConfigEntry;
import net.minecraft.server.WhitelistEntry;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.UUID;
@Mixin(WhitelistEntry.class)
public abstract class Whitelist extends ServerConfigEntry<GameProfile> implements WhitelistedPlayer, WhitelistAccessor<GameProfile> {
//private UUID id;
private UUID invitedBy = null;
public Whitelist(GameProfile object) {
super(object);
}
@Inject(at = @At("RETURN"), method = "<init>(Lcom/google/gson/JsonObject;)V")
public void onInitialize(JsonObject json, CallbackInfo callback) {
if (json.has("invitedBy"))
this.invitedBy = UUID.fromString(json.get("invitedBy").getAsString());
}
@Inject(at = @At("TAIL"), method = "fromJson")
public void onSerialize(JsonObject json, CallbackInfo callback) {
if (invitedBy != null)
json.addProperty("invitedBy",this.invitedBy.toString());
}
@Override
public void setInvitedBy(UUID uuid) {
this.invitedBy = uuid;
}
@Override
public @Nullable String getName() {
GameProfile profile = this.getObject();
if (profile == null) return null;
return profile.getName();
}
@Override
public @Nullable UUID getUUID() {
GameProfile profile = this.getObject();
if (profile == null) return null;
return profile.getId();
}
@Override
public @Nullable UUID getInvitedBy() {
return this.invitedBy;
}
}
| 32.129032 | 133 | 0.695281 |
dbe3994bb61b27734564bdbb5c0e1d140a84f22d | 776 | package be.distrinet.spite.iotsear.systemProviders.pbms;
import be.distrinet.spite.iotsear.pbms.ContextStorage;
import be.distrinet.spite.iotsear.pbms.PDP;
import be.distrinet.spite.iotsear.policy.AuthorizationPolicy;
import be.distrinet.spite.iotsear.policy.PolicyConditionEvaluationResult;
import org.json.simple.JSONObject;
import org.pf4j.Extension;
@Extension
public class SocketPDP extends PDP {
@Override
public String getProviderID() {
return "iotsear:pbms:socketPDP";
}
@Override
public void setConfiguration(JSONObject configuration) {
}
@Override
public PolicyConditionEvaluationResult evaluate(final AuthorizationPolicy policy, final ContextStorage storage) {
return policy.evaluateCondition(storage);
}
}
| 27.714286 | 117 | 0.777062 |
80b796c7f2dcba8c5665449a2537d45eef7ab5e1 | 13,593 | /*******************************************************************************
* Copyright 2015-2018 Capgemini SE.
*
* 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.devonfw.devcon.modules.dist;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import org.apache.commons.lang3.SystemUtils;
import com.devonfw.devcon.common.api.annotations.CmdModuleRegistry;
import com.devonfw.devcon.common.api.annotations.Command;
import com.devonfw.devcon.common.api.annotations.InputType;
import com.devonfw.devcon.common.api.annotations.Parameter;
import com.devonfw.devcon.common.api.annotations.Parameters;
import com.devonfw.devcon.common.api.data.ContextType;
import com.devonfw.devcon.common.api.data.DistributionInfo;
import com.devonfw.devcon.common.api.data.DistributionType;
import com.devonfw.devcon.common.api.data.InputTypeNames;
import com.devonfw.devcon.common.exception.InvalidConfigurationStateException;
import com.devonfw.devcon.common.impl.AbstractCommandModule;
import com.devonfw.devcon.common.utils.Constants;
import com.devonfw.devcon.common.utils.Downloader;
import com.devonfw.devcon.common.utils.Extractor;
import com.devonfw.devcon.common.utils.Utils;
import com.google.common.base.Optional;
/**
* Module with general tasks related to the distribution itself
*
* @author pparrado
*/
@CmdModuleRegistry(name = "dist", description = "Module with general tasks related to the distribution itself")
public class Dist extends AbstractCommandModule {
/**
* This command downloads and unzips the Devon distribution
*
* @param path location to download the Devon distribution
* @param type the {@link DistributionType} of the distribution
* @param user a user with permissions to download the Devon distribution
* @param password the password related to the user with permissions to download the Devon distribution
* @throws Exception
*/
@Command(name = "install", description = "This command downloads the last version of a distribution from Teamforge. You can select between Devonfw distribution (by default) and Oasp-ide distribution.", context = ContextType.NONE)
@Parameters(values = {
@Parameter(name = "path", description = "a location for the Devon distribution download", optional = true, inputType = @InputType(name = InputTypeNames.PATH)),
@Parameter(name = "type", description = "the type of the distribution, the options are: \n 'oaspide' to download OASP IDE\n 'devondist' to download Devon IP IDE", optional = true, inputType = @InputType(name = InputTypeNames.LIST, values = {
"devondist"/* ,"oaspide" */ }))/*
* ,
*
* @Parameter(name = "user", description =
* "a user with permissions to download the Devon distribution"),
*
* @Parameter(name = "password", description =
* "the password related to the user with permissions to download the Devon distribution"
* , inputType = @InputType(name = InputTypeNames.PASSWORD))
*/ })
public void install(String path, String type/* , String user, String password */) throws Exception {
Optional<String> teamforgeFileId;
String distType = "";
// Default parameters
path = path.isEmpty() ? getContextPathInfo().getCurrentWorkingDirectory().toString() : path.trim();
type = type.isEmpty() ? DistConstants.DEVON_DIST : type.trim();
this.output.status("installing distribution...");
try {
if (type.toLowerCase().equals(DistConstants.OASP_IDE)) {
} else if (type.toLowerCase().equals(DistConstants.DEVON_DIST) && SystemUtils.IS_OS_WINDOWS) {
distType = DistConstants.DIST_TYPE_WINDOWS;
} else if (type.toLowerCase().equals(DistConstants.DEVON_DIST) && SystemUtils.IS_OS_LINUX) {
distType = DistConstants.DIST_TYPE_LINUX;
} else {
throw new Exception("The parameter 'type' of the install command is unknown");
}
// Optional<String> fileDownloaded = Downloader.downloadFromTeamForge(path, user, password,
// teamforgeFileId.get());
Optional<String> fileDownloaded = Downloader.downloadFromTeamForge(path, distType);
File downloadedfile = new File(path + File.separator + fileDownloaded.get().toString());
if (fileDownloaded.isPresent()) {
Extractor.unZip(path + File.separator + fileDownloaded.get().toString(), path);
this.output
.showMessage("Distribution successfully installed. You can now follow the manual steps as described\n"
+ "in the Devonfw Guide or, alternatively, run 'devon dist init' to initialize the distribution.");
} else {
if (downloadedfile.exists()) {
downloadedfile.delete();
}
throw new Exception("An error occurred while downloading the file.");
}
if (downloadedfile.exists()) {
downloadedfile.delete();
}
} catch (Exception e) {
getOutput().showError(e.getMessage());
throw e;
}
}
/**
* This command initializes the Devon distribution (principally the workspaces and conf directory, so its ready for
* use
*
* @param path location of the Devon distribution
* @throws Exception
*/
@Command(name = "init", description = "This command initializes a newly downloaded distribution", context = ContextType.NONE)
@Parameters(values = {
@Parameter(name = "path", description = "location of the Devon distribution (current dir if not given)", optional = true, inputType = @InputType(name = InputTypeNames.PATH)) })
public void init(String path) throws Exception {
String frsFileId = "";
File updatebat = null;
// Default parameters
path = path.isEmpty() ? getContextPathInfo().getCurrentWorkingDirectory().toString() : path.trim();
Path path_ = getPath(path);
if (SystemUtils.IS_OS_WINDOWS) {
updatebat = path_.resolve(Constants.UPDATE_ALL_WORKSPACES_BAT).toFile();
} else if (SystemUtils.IS_OS_LINUX) {
updatebat = path_.resolve(Constants.UPDATE_ALL_WORKSPACES_SH).toFile();
}
if (!updatebat.exists()) {
this.output.showError("Not a Devon distribution");
return;
}
this.output.showMessage("Initializing distribution...");
try {
// Run file update-all-workspaces.bat which initializes the distro on first run
ProcessBuilder processBuilder = new ProcessBuilder(updatebat.getAbsolutePath());
processBuilder.directory(path_.toFile());
Process process = processBuilder.start();
final InputStream isError = process.getErrorStream();
final InputStream isOutput = process.getInputStream();
Utils.processOutput(isError, isOutput, this.output);
this.output.showMessage("Distribution initialized.");
} catch (Exception e) {
getOutput().showError(e.getMessage());
throw e;
}
}
/**
* This command initializes a Devon distribution for use with Shared Services
*
* @param projectname the name for the new project
* @param artuser the user with permissions in the artifactory repository
* @param artencpass the encrypted password of the user with permissions in the artifactory repository
* @param svnurl the URL of the svn repository to do the checkout
* @param svnuser the user with permissions in the svn repository
* @param svnpass the password of the user with permissions in the svn repository
*/
@Command(name = "s2", description = "This command initializes a Devonfw distribution configuring it for Shared Services use.")
@Parameters(values = {
@Parameter(name = "projectname", description = "the name for the new project", inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "user", description = "the userId for Artifactory provided by S2 for the project", inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "pass", description = "the password for Artifactory", inputType = @InputType(name = InputTypeNames.PASSWORD)),
@Parameter(name = "engagementname", description = "the name of the repository for the engagement", inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "ciaas", description = "if the settings.xml must be configured for CIaaS set this as TRUE. Is an optional parameter with FALSE as default value.", optional = true, inputType = @InputType(name = InputTypeNames.LIST, values = {
"False", "True" })),
@Parameter(name = "svnurl", description = "the url for the SVN provided by S2", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "svnuser", description = "the user for the SVN", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "svnpass", description = "the password for the SVN", optional = true, inputType = @InputType(name = InputTypeNames.PASSWORD)),
@Parameter(name = "plurl", description = "the url for the Production Line Instance provided by S2", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "pluser", description = "the user login for the PL instance", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "plpass", description = "the user passwod for the PL instance", optional = true, inputType = @InputType(name = InputTypeNames.PASSWORD)),
@Parameter(name = "plJenkinsConnectionName", description = "Eclipse Jenkins connection Name", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "plSonarQubeConnectionName", description = "Eclipse SonarQube connection Name", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)),
@Parameter(name = "plGerritConnectionName", description = "Eclipse Gerrit connection Name", optional = true, inputType = @InputType(name = InputTypeNames.GENERIC)) })
public void s2(String projectname, String user, String pass, String engagementname, String ciaas, String svnurl,
String svnuser, String svnpass, String plurl, String pluser, String plpass, String plJenkinsConnectionName,
String plSonarQubeConnectionName, String plGerritConnectionName) {
Optional<DistributionInfo> distInfo = getContextPathInfo().getDistributionRoot();
SharedServices s2 = new SharedServices(this.output);
try {
if (distInfo.isPresent()) {
Path distPath = distInfo.get().getPath();
if (distInfo.get().getDistributionType().equals(DistributionType.DevonDist)) {
boolean configureForCiaas = Boolean.parseBoolean(ciaas);
String ciaas_value = configureForCiaas ? "ciaas" : "";
int initResult = s2.init(distPath, user, pass, engagementname, ciaas_value);
if (initResult > 0)
this.output.showMessage(
"The configuration of the conf/settings.xml file could not be completed successfully. Please verify it");
int createResult = s2.create(distPath, projectname, svnurl, svnuser, svnpass);
if (createResult > 0)
throw new Exception("An error occurred while project creation.");
int initPL = s2.initPL(distPath, plurl, pluser, plpass, plJenkinsConnectionName, plSonarQubeConnectionName,
plGerritConnectionName);
if (initPL > 0)
this.output.showMessage(
"The configuration of the eclipse views could not be completed successfully. Please verify it");
} else {
throw new InvalidConfigurationStateException("The conf/settings.json seems to be invalid");
}
} else {
this.output.showMessage("Seems that you are not in a Devon distribution.");
}
} catch (Exception e) {
this.output.showError(e.getMessage());
}
}
/**
* This command provides the user with basic information about the Devon distribution
*
* @param path location to download the Devon distribution
*
*/
@Command(name = "info", description = "Basic info about the distribution")
@Parameters(values = {
@Parameter(name = "path", description = "a location for the Devon distribution download", optional = true, inputType = @InputType(name = InputTypeNames.PATH)) })
public void info(String path) {
try {
Optional<DistributionInfo> distInfo = getContextPathInfo().getDistributionRoot(path);
if (distInfo.isPresent()) {
DistributionInfo info = distInfo.get();
this.output.showMessage("Distro '%s', version: '%s', present in: %s", info.getDistributionType().name(),
info.getVersion().toString(), info.getPath().toString());
} else {
this.output.showMessage("Seems that you are not in a Devon distribution.");
}
} catch (Exception e) {
this.output.showError(e.getMessage());
}
}
}
| 50.910112 | 245 | 0.68984 |
7e138f2203b9c2f3ac587eb8296110a8c6f84c30 | 3,558 | package uk.gov.ons.ssdc.jobprocessor.schedule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import uk.gov.ons.ssdc.common.model.entity.Job;
import uk.gov.ons.ssdc.common.model.entity.JobRowStatus;
import uk.gov.ons.ssdc.common.model.entity.JobStatus;
import uk.gov.ons.ssdc.jobprocessor.repository.JobRepository;
import uk.gov.ons.ssdc.jobprocessor.repository.JobRowRepository;
@ExtendWith(MockitoExtension.class)
class StagedJobValidatorTest {
@Mock JobRepository jobRepository;
@Mock JobRowRepository jobRowRepository;
@Mock RowChunkValidator rowChunkValidator;
@InjectMocks StagedJobValidator underTest;
@Test
void processStagedJobs() {
// Given
Job job = new Job();
when(jobRepository.findByJobStatus(JobStatus.VALIDATION_IN_PROGRESS)).thenReturn(List.of(job));
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.STAGED))
.thenReturn(true)
.thenReturn(false);
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.VALIDATED_ERROR))
.thenReturn(false);
// When
underTest.processStagedJobs();
// Then
verify(rowChunkValidator).processChunk(job);
ArgumentCaptor<Job> jobArgumentCaptor = ArgumentCaptor.forClass(Job.class);
verify(jobRepository).saveAndFlush(jobArgumentCaptor.capture());
Job actualJob = jobArgumentCaptor.getValue();
assertThat(actualJob.getJobStatus()).isEqualTo(JobStatus.VALIDATED_OK);
}
@Test
void processStagedJobsMultipleChunks() {
// Given
Job job = new Job();
when(jobRepository.findByJobStatus(JobStatus.VALIDATION_IN_PROGRESS)).thenReturn(List.of(job));
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.STAGED))
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(false);
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.VALIDATED_ERROR))
.thenReturn(false);
// When
underTest.processStagedJobs();
// Then
verify(rowChunkValidator, times(3)).processChunk(job);
ArgumentCaptor<Job> jobArgumentCaptor = ArgumentCaptor.forClass(Job.class);
verify(jobRepository).saveAndFlush(jobArgumentCaptor.capture());
Job actualJob = jobArgumentCaptor.getValue();
assertThat(actualJob.getJobStatus()).isEqualTo(JobStatus.VALIDATED_OK);
}
@Test
void processStagedJobsFailedChunk() {
// Given
Job job = new Job();
when(jobRepository.findByJobStatus(JobStatus.VALIDATION_IN_PROGRESS)).thenReturn(List.of(job));
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.STAGED))
.thenReturn(true)
.thenReturn(false);
when(jobRowRepository.existsByJobAndJobRowStatus(job, JobRowStatus.VALIDATED_ERROR))
.thenReturn(true);
// When
underTest.processStagedJobs();
// Then
verify(rowChunkValidator).processChunk(job);
ArgumentCaptor<Job> jobArgumentCaptor = ArgumentCaptor.forClass(Job.class);
verify(jobRepository).saveAndFlush(jobArgumentCaptor.capture());
Job actualJob = jobArgumentCaptor.getValue();
assertThat(actualJob.getJobStatus()).isEqualTo(JobStatus.VALIDATED_WITH_ERRORS);
}
}
| 34.543689 | 99 | 0.760259 |
7d17862e61c9382a21f42741b32e08c8ba61f79b | 1,558 | package com.company;
import java.util.*;
public class BFS {
public static void main(String[] args) {
//Creating the Graph
int noOfVertices = 6;
Graph graph = new Graph(noOfVertices);
graph.addEdge(0,1);
graph.addEdge(0,2);
graph.addEdge(1,0);
graph.addEdge(1,3);
graph.addEdge(1,4);
graph.addEdge(2,0);
graph.addEdge(2,4);
graph.addEdge(3,1);
graph.addEdge(3,4);
graph.addEdge(3,5);
graph.addEdge(4,1);
graph.addEdge(4,2);
graph.addEdge(4,3);
graph.addEdge(4,5);
graph.addEdge(5,3);
graph.addEdge(5,4);
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter a Vertex to start Traversal");
int startVertex = sc.nextInt();
System.out.println(graph);
//Traversing the Graph
breadthFirstSearch(startVertex,graph);
}
public static void breadthFirstSearch(int startVertex,Graph graph){
boolean visited[] = new boolean[graph.getNoOfVertices()];
Queue<Integer> queue = new LinkedList<>() {
};
visited[startVertex] = true;
queue.add(startVertex);
while (queue.size() != 0){
startVertex = queue.poll();
System.out.print(startVertex+" ");
for (int n : graph.getAdjlist()[startVertex]) {
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
}
| 25.129032 | 71 | 0.533376 |
c7a4225944f7bc51199c43475a8e0d6ed34a62ac | 1,820 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
* Important World methods:
* addObject
* getObjects
* setPaintOrder
* showText
*
* Important Greenfoot methods:
* stop
*/
public class TheBeach extends World
{
public static final int W = 1000;
public static final int H = 700;
public static final int NSTARFISH = 5;
public static final int NShrew = 5;
public TheBeach()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(W, H, 1);
setPaintOrder(Fruit.class, Animal.class);
for(int i = 0; i < NSTARFISH; i++){
addObject(new Starfish(), (int)(Math.random() * W), (int)(Math.random() * H));
}
for(int i = 0; i < NShrew; i++){
addObject(new Shrew(), (int)(Math.random() * W), (int)(Math.random() * H));
}
}
public void act(){
if(Math.random() > 0){
int x = (int)(Math.random() * W);
int y = (int)(Math.random() * H);
if(Math.random() > 0.5){
addObject(new Banana(), x, y);
}else{
addObject(new Cherry(), x, y);
}
}
List<Starfish> allStarfish = getObjects(Starfish.class);
if(allStarfish.size() == 0){
showText("All the starfish are dead!", W/2, H/2);
Greenfoot.stop();
} else if (allStarfish.size() == 1){
showText("I'm so lonely!", W/2, H/2);
}
List<Shrew> allShrew = getObjects(Shrew.class);
if(allShrew.size() == 0){
showText("All the Shrew are dead!", W/2, H/2);
Greenfoot.stop();
} else if (allShrew.size() == 1){
showText("I'm so lonely!", W/2, H/2);
}
}
}
| 31.37931 | 90 | 0.521978 |
e246777001add0f6d7a13dea8b6d4937ff0bd002 | 259 | package id.bizdir.list;
import java.util.ArrayList;
import id.bizdir.model.Event;
/**
* Created by Hendry on 29/07/2015.
*/
public class EventList {
public ArrayList<Event> event;
public EventList() {
event = new ArrayList<>();
}
}
| 14.388889 | 35 | 0.648649 |
9b19564cb2f2bd9a4447ce06c6c88a16489a30a9 | 3,176 | /**
* Copyright 2017 Syncleus, Inc.
* with portions copyright 2004-2017 Bo Zimmerman
*
* 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.syncleus.aethermud.game.Commands;
import com.syncleus.aethermud.game.MOBS.interfaces.MOB;
import com.syncleus.aethermud.game.core.CMLib;
import com.syncleus.aethermud.game.core.CMSecurity;
import com.syncleus.aethermud.game.core.Resources;
import java.util.*;
public class ATopics extends StdCommand {
private final String[] access = I(new String[]{"ARCTOPICS", "ATOPICS"});
public ATopics() {
}
public static void doTopics(MOB mob, Properties rHelpFile, String helpName, String resName) {
StringBuffer topicBuffer = (StringBuffer) Resources.getResource(resName);
if (topicBuffer == null) {
topicBuffer = new StringBuffer();
final Vector<String> reverseList = new Vector<String>();
for (final Enumeration<Object> e = rHelpFile.keys(); e.hasMoreElements(); ) {
final String ptop = (String) e.nextElement();
final String thisTag = rHelpFile.getProperty(ptop);
if ((thisTag == null) || (thisTag.length() == 0) || (thisTag.length() >= 35)
|| (rHelpFile.getProperty(thisTag) == null))
reverseList.add(ptop);
}
Collections.sort(reverseList);
topicBuffer = new StringBuffer("Help topics: \n\r\n\r");
topicBuffer.append(CMLib.lister().fourColumns(mob, reverseList, "HELP"));
topicBuffer = new StringBuffer(topicBuffer.toString().replace('_', ' '));
Resources.submitResource(resName, topicBuffer);
}
if ((mob != null) && (!mob.isMonster()))
mob.session().colorOnlyPrintln(CMLib.lang().L("@x1\n\r\n\rEnter @x2 (TOPIC NAME) for more information.", topicBuffer.toString(), helpName), false);
}
@Override
public String[] getAccessWords() {
return access;
}
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException {
final Properties arcHelpFile = CMLib.help().getArcHelpFile();
if (arcHelpFile.size() == 0) {
if (mob != null)
mob.tell(L("No archon help is available."));
return false;
}
doTopics(mob, arcHelpFile, "AHELP", "ARCHON TOPICS");
return false;
}
@Override
public boolean canBeOrdered() {
return true;
}
@Override
public boolean securityCheck(MOB mob) {
return CMSecurity.isAllowed(mob, mob.location(), CMSecurity.SecFlag.AHELP);
}
}
| 36.505747 | 159 | 0.642317 |
22317b325bb6cae342f58225c7c25e222f8fec7b | 8,397 | /*
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package validation;
import static jaxp.library.JAXPTestUtilities.USER_DIR;
import static jaxp.library.JAXPTestUtilities.runWithTmpPermission;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.PropertyPermission;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stax.StAXResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.xml.sax.ErrorHandler;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -DrunSecMngr=true validation.ValidatorTest
* @run testng/othervm validation.ValidatorTest
* @summary Test Validator.validate(Source, Result).
*/
@Listeners({jaxp.library.FilePolicy.class})
public class ValidatorTest {
@Test
public void testValidateStAX() {
File resultFile = null;
try {
resultFile = new File(USER_DIR + "stax.result");
if (resultFile.exists()) {
resultFile.delete();
}
Result xmlResult = new javax.xml.transform.stax.StAXResult(XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(resultFile)));
Source xmlSource = new javax.xml.transform.stax.StAXSource(getXMLEventReader("toys.xml"));
validate("toys.xsd", xmlSource, xmlResult);
((StAXResult) xmlResult).getXMLStreamWriter().close();
Assert.assertTrue(resultFile.exists(), "result file is not created");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Exception : " + ex.getMessage());
} finally {
if (resultFile != null && resultFile.exists()) {
resultFile.delete();
}
}
}
@Test
public void testValidateStream() {
File resultFile = null;
try {
resultFile = new File(USER_DIR + "stax.result");
if (resultFile.exists()) {
resultFile.delete();
}
// Validate this instance document against the
// Instance document supplied
File resultAlias = resultFile;
Result xmlResult = runWithTmpPermission(() -> new javax.xml.transform.stream.StreamResult(
resultAlias), new PropertyPermission("user.dir", "read"));
Source xmlSource = new javax.xml.transform.stream.StreamSource(new File(ValidatorTest.class.getResource("toys.xml").toURI()));
validate("toys.xsd", xmlSource, xmlResult);
Assert.assertTrue(resultFile.exists(), "result file is not created");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Exception : " + ex.getMessage());
} finally {
if (resultFile != null && resultFile.exists()) {
resultFile.delete();
}
}
}
@Test
public void testValidateGMonth() {
// test valid gMonths
File resultFile = null;
try {
resultFile = new File(USER_DIR + "gMonths.result.xml");
if (resultFile.exists()) {
resultFile.delete();
}
// Validate this instance document against the
// Instance document supplied
File resultAlias = resultFile;
Result xmlResult = runWithTmpPermission(() -> new javax.xml.transform.stream.StreamResult(
resultAlias), new PropertyPermission("user.dir", "read"));
Source xmlSource = new javax.xml.transform.stream.StreamSource(new File(ValidatorTest.class.getResource("gMonths.xml").toURI()));
validate("gMonths.xsd", xmlSource, xmlResult);
Assert.assertTrue(resultFile.exists(), "result file is not created");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Exception : " + ex.getMessage());
} finally {
if (resultFile != null && resultFile.exists()) {
resultFile.delete();
}
}
// test invalid gMonths
File invalidResultFile = null;
try {
invalidResultFile = new File(USER_DIR + "gMonths-invalid.result.xml");
if (invalidResultFile.exists()) {
invalidResultFile.delete();
}
// Validate this instance document against the
// Instance document supplied
Result xmlResult = new javax.xml.transform.stream.StreamResult(resultFile);
Source xmlSource = new javax.xml.transform.stream.StreamSource(new File(ValidatorTest.class.getResource("gMonths-invalid.xml").toURI()));
validate("gMonths.xsd", xmlSource, xmlResult);
// should have failed with an Exception due to invalid gMonths
Assert.fail("invalid gMonths were accepted as valid in " + ValidatorTest.class.getResource("gMonths-invalid.xml").toURI());
} catch (Exception ex) {
// expected failure
System.out.println("Expected failure: " + ex.toString());
} finally {
if (invalidResultFile != null && invalidResultFile.exists()) {
invalidResultFile.delete();
}
}
}
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));
// Get a Validator which can be used to validate instance document
// against this grammar.
Validator validator = schema.newValidator();
ErrorHandler eh = new ErrorHandlerImpl();
validator.setErrorHandler(eh);
// Validate this instance document against the
// Instance document supplied
validator.validate(src, result);
} catch (Exception ex) {
throw ex;
}
}
private XMLEventReader getXMLEventReader(final String filename) {
XMLInputFactory xmlif = null;
XMLEventReader xmlr = null;
try {
xmlif = XMLInputFactory.newInstance();
xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
// FileInputStream fis = new FileInputStream(filename);
FileInputStream fis = new FileInputStream(new File(ValidatorTest.class.getResource(filename).toURI()));
xmlr = xmlif.createXMLEventReader(filename, fis);
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Exception : " + ex.getMessage());
}
return xmlr;
}
}
| 39.608491 | 153 | 0.643801 |
ee07790a95a2f47e19986d470e05ec967eb2dd08 | 1,454 | package com.github.hailouwang.demosforapi;
import com.android.build.gradle.AppExtension;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
/**
* AndroidStudio 插件: https://www.jianshu.com/p/da5920905380
* Groovy 脚本:https://blog.csdn.net/yanbober/article/details/49047515
*/
public class GradlePluginDemo implements Plugin<Project> {
@Override
public void apply(Project project) {
System.out.println("GradlePluginDemo apply -----------> project : " + project);
RepositoryHandler repositories = project.getRepositories();
repositories.maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository mavenArtifactRepository) {
System.out.println("GradlePluginDemo apply -----------> MavenArtifactRepository : " + mavenArtifactRepository);
}
});
AppExtension appExtension = (AppExtension) project.getProperties().get("android");
try {
if (appExtension != null) {
System.out.println("GradlePluginDemo apply -----------> appExtension : " + appExtension);
appExtension.registerTransform(new CodeInsertTransform(project, appExtension));
}
} catch (Exception e) {
}
}
}
| 38.263158 | 127 | 0.676066 |
d5c38bdf596832ae8d2b6bbdd94e7b3dcfb6ab08 | 1,186 | package io.quarkus.hibernate.validator.test.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.arc.Unremovable;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
public class ConfigMappingValidatorTest {
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("validator.server.host=localhost\n"), "application.properties"));
@Inject
@Valid
Server server;
@Test
void valid() {
assertEquals("localhost", server.host());
}
@Unremovable
@ConfigMapping(prefix = "validator.server")
public interface Server {
@Size(min = 2, max = 10)
String host();
}
}
| 28.926829 | 116 | 0.732715 |
9d4d5a6bdfde0e0766bf5a127f79b6494d8101f6 | 458 | package com.liveramp.captain.example.internals;
/*
* code so that the ExampleCaptainWorkflow can run, but not actually useful in learning about captain.
*/
public class MockDataScience {
public static class Service1 extends DataScienceService {
}
public static class Service2 extends DataScienceService {
}
private static class DataScienceService {
@SuppressWarnings("unused")
public void submitData(String pathToData) {
}
}
}
| 21.809524 | 102 | 0.751092 |
6791f91ac7096acda65212cfc347c5f0f8ab309b | 5,631 | /*
* Copyright (c) 2021-present, Kiwis2-mockserver Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing roles and limitations under the License.
*/
package io.github.kiwis2.mockserver.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.kiwis2.mockserver.persistance.db.dao.PermissionDao;
import io.github.kiwis2.mockserver.persistance.db.dao.RoleDao;
import io.github.kiwis2.mockserver.persistance.db.dao.RolePermissionDao;
import io.github.kiwis2.mockserver.persistance.db.entity.PermissionEntity;
import io.github.kiwis2.mockserver.persistance.db.entity.RoleEntity;
import io.github.kiwis2.mockserver.persistance.db.entity.RolePermissionEntity;
import io.github.kiwis2.mockserver.persistance.db.entity.custom.CustomRolePermissionEntity;
import io.github.kiwis2.mockserver.service.dto.admin.RoleDeleteRequestDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleDeleteResponseDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleLoadPermissionRequestDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleLoadPermissionResponseDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleLoadListRequestDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleLoadListResponseDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleSaveRequestDto;
import io.github.kiwis2.mockserver.service.dto.admin.RoleSaveRequestDtoPermission;
import io.github.kiwis2.mockserver.service.dto.admin.RoleSaveResponseDto;
/**
* Home business class
*
* @author Kiwis2
*
*/
@Service
@Transactional
public class AdminRoleBusiness {
@Autowired
private RoleDao roleDao;
@Autowired
private RolePermissionDao rolePermissionDao;
@Autowired
private PermissionDao permissionDao;
/**
* request role delete
*
* @param requestDto request dto
* @param responseDto response dto
*/
public void requestRoleDelete(RoleDeleteRequestDto requestDto,
RoleDeleteResponseDto responseDto) {
roleDao.delete(requestDto.id);
rolePermissionDao.deleteByRole(Integer.parseInt(requestDto.id));
}
/**
* request role list
*
* @param requestDto request dto
* @param responseDto response dto
*/
public void requestRoleList(RoleLoadListRequestDto requestDto,
RoleLoadListResponseDto responseDto) {
List<RoleEntity> roleList = roleDao.selectAll();
List<CustomRolePermissionEntity> rolePermissionList = rolePermissionDao.selectAll();
Map<String, String> roleDetailMap = new HashMap<>();
Map<String, List<CustomRolePermissionEntity>> roleDetailListMap = new HashMap<>();
for(CustomRolePermissionEntity entity:rolePermissionList) {
String detail = roleDetailMap.get(entity.role_id.toString());
if(detail == null) {
roleDetailMap.put(entity.role_id.toString(),entity.permission_name);
}else {
roleDetailMap.put(entity.role_id.toString(),detail+"/"+entity.permission_name);
}
List<CustomRolePermissionEntity> detailList = roleDetailListMap.get(entity.role_id.toString());
if(detailList == null) {
detailList = new ArrayList<CustomRolePermissionEntity>();
}
detailList.add(entity);
roleDetailListMap.put(entity.role_id.toString(), detailList);
}
responseDto.roleList.addAll(roleList);
responseDto.roleDetailMap = roleDetailMap;
responseDto.roleDetailListMap = roleDetailListMap;
}
/**
* request category list
*
* @param requestDto request dto
* @param responseDto response dto
*/
public void requestPermissionList(RoleLoadPermissionRequestDto requestDto,
RoleLoadPermissionResponseDto responseDto) {
List<PermissionEntity> rootPermissionList = permissionDao.selectAll();
responseDto.permissionList.addAll(rootPermissionList);
}
/**
* save role
*
* @param requestDto request dto
* @param responseDto response dto
*/
public void saveRole(RoleSaveRequestDto requestDto, RoleSaveResponseDto responseDto) {
RoleEntity roleEntity = null;
if(requestDto.roleId != null && !requestDto.roleId.equals("") && !requestDto.roleId.equals("null")) {
roleEntity = roleDao.get(requestDto.roleId);
roleEntity.role_name = requestDto.roleName;
roleEntity.remarks = requestDto.roleRemarks;
roleDao.update(roleEntity);
}else {
roleEntity = new RoleEntity();
roleEntity.role_name = requestDto.roleName;
roleEntity.remarks = requestDto.roleRemarks;
roleDao.save(roleEntity);
}
rolePermissionDao.deleteByRole(roleEntity.role_id);
if(requestDto.rolePermissionList != null) {
List<RolePermissionEntity> entityList = new ArrayList<>();
for(RoleSaveRequestDtoPermission requestInfo:requestDto.rolePermissionList) {
RolePermissionEntity entity = new RolePermissionEntity();
entity.role_id = roleEntity.role_id;
entity.permission_id = Integer.valueOf(requestInfo.permissionId);
entityList.add(entity);
}
if(entityList.size() > 0) {
rolePermissionDao.saveList(entityList);
}
}
}
}
| 32.929825 | 112 | 0.772865 |
9ef5de2869479c4f95d2cb244298c1447618b8e1 | 453 | /**
*
*/
package com.kancolle.server.model.po.common.handler.immutableList;
import com.google.common.collect.ImmutableList;
import java.util.function.Function;
/**
* @author J.K.SAGE
* @Date 2015年5月30日
*/
public class IntegerImmutableListHandler extends ImmutableListHandler<Integer> {
@Override
protected Function<String, ImmutableList<Integer>> toImmutableList() {
return toImmutableListFunction.apply(Integer.class);
}
}
| 21.571429 | 80 | 0.746137 |
0d82590ef16466de30e7cb1e5f055a945acc22ee | 2,804 | /*
+--------------------------------------------------------------------------
| Mblog [#RELEASE_VERSION#]
| ========================================
| Copyright (c) 2014, 2015 mtons. All Rights Reserved
| http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package mblog.web.formatter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author langhsu
*
*/
@Component
public class JsonUtils {
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private static final ObjectMapper mapper;
public ObjectMapper getMapper() {
return mapper;
}
static {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
private static final long serialVersionUID = -5854941510519564900L;
@Override
public Object findSerializer(Annotated a) {
if (a instanceof AnnotatedMethod) {
AnnotatedElement m = a.getAnnotated();
DateTimeFormat an = m.getAnnotation(DateTimeFormat.class);
if (an != null) {
if (!DEFAULT_DATE_FORMAT.equals(an.pattern())) {
return new JsonDateSerializer(an.pattern());
}
}
}
return super.findSerializer(a);
}
});
}
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException("转换json字符失败!");
}
}
public <T> T toObject(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
throw new RuntimeException("将json字符转换为对象时失败!");
}
}
public static class JsonDateSerializer extends JsonSerializer<Date> {
private SimpleDateFormat dateFormat;
public JsonDateSerializer(String format) {
dateFormat = new SimpleDateFormat(format);
}
@Override
public void serialize(Date date, JsonGenerator gen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
String value = dateFormat.format(date);
gen.writeString(value);
}
}
}
| 28.907216 | 79 | 0.700428 |
a0698d2dcf6e7dda54dc86a6c5abe3f1d4c209a8 | 21,712 | package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class register_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList(4);
_jspx_dependants.add("/WEB-INF/tld/c.tld");
_jspx_dependants.add("/WEB-INF/tld/fmt.tld");
_jspx_dependants.add("/WEB-INF/tld/spring.tld");
_jspx_dependants.add("/WEB-INF/tld/spring-form.tld");
}
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fspring_005fhasBindErrors_0026_005fname;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fspring_005fhasBindErrors_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath.release();
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.release();
_005fjspx_005ftagPool_005fspring_005fhasBindErrors_0026_005fname.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<head>\n");
out.write(" <title>Red5 Admin</title>\n");
out.write(" <meta content=\"text/html; charset=iso-8859-1\" http-equiv=\"Content-Type\" />\n");
out.write(" <style type=\"text/css\" media=\"screen\">\n");
out.write("html, body, #containerA, #containerB { height: 100%;\n");
out.write("}\n");
out.write(".formbg { background-color: rgb(238, 238, 238);\n");
out.write("}\n");
out.write(".formtable { border: 2px solid rgb(183, 186, 188);\n");
out.write("}\n");
out.write("\n");
out.write(".formtext { font-family: Arial,Helvetica,sans-serif;\n");
out.write(" font-size: 12px;\n");
out.write(" color: rgb(11, 51, 73);\n");
out.write("}\n");
out.write("\n");
out.write("body { margin: 0pt;\n");
out.write("padding: 0pt;\n");
out.write("overflow: hidden;\n");
out.write("background-color: rgb(250, 250, 250);\n");
out.write("}\n");
out.write(".error { \n");
out.write("\tfont-family: Arial,Helvetica,sans-serif;\n");
out.write("\tfont-size: 12px;\n");
out.write("\tcolor: red; \n");
out.write("}\n");
out.write(" </style>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("<table style=\"text-align: left; width: 100%; height: 100%;\" border=\"0\" cellpadding=\"0\" cellspacing=\"10\">\n");
out.write(" <tbody>\n");
out.write(" <tr>\n");
out.write(" <td height=\"54\"><img style=\"width: 136px; height: 54px;\" alt=\"\" src=\"assets/logo.png\" /></td>\n");
out.write(" </tr>\n");
out.write(" <tr class=\"formbg\">\n");
out.write(" <td align=\"center\" valign=\"middle\">\n");
out.write(" <table style=\"width: 400px;\" class=\"formtable\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\">\n");
out.write(" <tr>\n");
out.write(" \t<td class=\"formtext\"> <b>Register Admin User</b></td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td>\n");
out.write(" <form method=\"post\" action=\"register.html\">\n");
out.write(" <table style=\"width: 400px;\" border=\"0\" cellpadding=\"0\" cellspacing=\"5\">\n");
out.write(" <tbody>\n");
out.write(" <tr>\n");
out.write(" <td align=\"right\" width=\"20%\" class=\"formtext\">Username:</td>\n");
out.write("\t\t ");
// spring:bind
org.springframework.web.servlet.tags.BindTag _jspx_th_spring_005fbind_005f0 = (org.springframework.web.servlet.tags.BindTag) _005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath.get(org.springframework.web.servlet.tags.BindTag.class);
_jspx_th_spring_005fbind_005f0.setPageContext(_jspx_page_context);
_jspx_th_spring_005fbind_005f0.setParent(null);
// /WEB-INF/jsp/register.jsp(54,8) name = path type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_spring_005fbind_005f0.setPath("userDetails.username");
int[] _jspx_push_body_count_spring_005fbind_005f0 = new int[] { 0 };
try {
int _jspx_eval_spring_005fbind_005f0 = _jspx_th_spring_005fbind_005f0.doStartTag();
if (_jspx_eval_spring_005fbind_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
org.springframework.web.servlet.support.BindStatus status = null;
status = (org.springframework.web.servlet.support.BindStatus) _jspx_page_context.findAttribute("status");
do {
out.write("\n");
out.write("\t\t <td width=\"20%\">\n");
out.write("\t\t <input name=\"username\" value=\"");
if (_jspx_meth_c_005fout_005f0(_jspx_th_spring_005fbind_005f0, _jspx_page_context, _jspx_push_body_count_spring_005fbind_005f0))
return;
out.write("\" />\n");
out.write("\t\t </td>\n");
out.write("\t\t <td width=\"60%\" class=\"error\">\n");
out.write("\t\t ");
if (_jspx_meth_c_005fout_005f1(_jspx_th_spring_005fbind_005f0, _jspx_page_context, _jspx_push_body_count_spring_005fbind_005f0))
return;
out.write("\n");
out.write("\t\t </td>\n");
out.write("\t\t ");
int evalDoAfterBody = _jspx_th_spring_005fbind_005f0.doAfterBody();
status = (org.springframework.web.servlet.support.BindStatus) _jspx_page_context.findAttribute("status");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_spring_005fbind_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_spring_005fbind_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_spring_005fbind_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_spring_005fbind_005f0.doFinally();
_005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath.reuse(_jspx_th_spring_005fbind_005f0);
}
out.write("\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write("\t\t\t <td align=\"right\" width=\"20%\" class=\"formtext\">Password:</td>\n");
out.write("\t\t ");
// spring:bind
org.springframework.web.servlet.tags.BindTag _jspx_th_spring_005fbind_005f1 = (org.springframework.web.servlet.tags.BindTag) _005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath.get(org.springframework.web.servlet.tags.BindTag.class);
_jspx_th_spring_005fbind_005f1.setPageContext(_jspx_page_context);
_jspx_th_spring_005fbind_005f1.setParent(null);
// /WEB-INF/jsp/register.jsp(65,8) name = path type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_spring_005fbind_005f1.setPath("userDetails.password");
int[] _jspx_push_body_count_spring_005fbind_005f1 = new int[] { 0 };
try {
int _jspx_eval_spring_005fbind_005f1 = _jspx_th_spring_005fbind_005f1.doStartTag();
if (_jspx_eval_spring_005fbind_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
org.springframework.web.servlet.support.BindStatus status = null;
status = (org.springframework.web.servlet.support.BindStatus) _jspx_page_context.findAttribute("status");
do {
out.write("\n");
out.write("\t\t <td width=\"20%\">\n");
out.write("\t\t <input type=\"password\" name=\"password\" value=\"");
if (_jspx_meth_c_005fout_005f2(_jspx_th_spring_005fbind_005f1, _jspx_page_context, _jspx_push_body_count_spring_005fbind_005f1))
return;
out.write("\" />\n");
out.write("\t\t </td>\n");
out.write("\t\t <td width=\"60%\" class=\"error\">\n");
out.write("\t\t ");
if (_jspx_meth_c_005fout_005f3(_jspx_th_spring_005fbind_005f1, _jspx_page_context, _jspx_push_body_count_spring_005fbind_005f1))
return;
out.write("\n");
out.write("\t\t </td>\n");
out.write("\t\t ");
int evalDoAfterBody = _jspx_th_spring_005fbind_005f1.doAfterBody();
status = (org.springframework.web.servlet.support.BindStatus) _jspx_page_context.findAttribute("status");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_spring_005fbind_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_spring_005fbind_005f1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_spring_005fbind_005f1.doCatch(_jspx_exception);
} finally {
_jspx_th_spring_005fbind_005f1.doFinally();
_005fjspx_005ftagPool_005fspring_005fbind_0026_005fpath.reuse(_jspx_th_spring_005fbind_005f1);
}
out.write("\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td><input type=\"submit\" value=\"Submit\" /></td>\n");
out.write(" <td></td>\n");
out.write(" <td class=\"error\">\n");
out.write(" ");
// spring:hasBindErrors
org.springframework.web.servlet.tags.BindErrorsTag _jspx_th_spring_005fhasBindErrors_005f0 = (org.springframework.web.servlet.tags.BindErrorsTag) _005fjspx_005ftagPool_005fspring_005fhasBindErrors_0026_005fname.get(org.springframework.web.servlet.tags.BindErrorsTag.class);
_jspx_th_spring_005fhasBindErrors_005f0.setPageContext(_jspx_page_context);
_jspx_th_spring_005fhasBindErrors_005f0.setParent(null);
// /WEB-INF/jsp/register.jsp(78,15) name = name type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_spring_005fhasBindErrors_005f0.setName("userDetails");
int[] _jspx_push_body_count_spring_005fhasBindErrors_005f0 = new int[] { 0 };
try {
int _jspx_eval_spring_005fhasBindErrors_005f0 = _jspx_th_spring_005fhasBindErrors_005f0.doStartTag();
if (_jspx_eval_spring_005fhasBindErrors_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
org.springframework.validation.Errors errors = null;
errors = (org.springframework.validation.Errors) _jspx_page_context.findAttribute("errors");
do {
out.write("\n");
out.write("\t\t\t <b>Please fix all errors!</b>\n");
out.write("\t\t\t ");
int evalDoAfterBody = _jspx_th_spring_005fhasBindErrors_005f0.doAfterBody();
errors = (org.springframework.validation.Errors) _jspx_page_context.findAttribute("errors");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_spring_005fhasBindErrors_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_spring_005fhasBindErrors_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_spring_005fhasBindErrors_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_spring_005fhasBindErrors_005f0.doFinally();
_005fjspx_005ftagPool_005fspring_005fhasBindErrors_0026_005fname.reuse(_jspx_th_spring_005fhasBindErrors_005f0);
}
out.write(" \n");
out.write(" </td>\n");
out.write("\n");
out.write(" </tr>\n");
out.write(" </tbody>\n");
out.write(" </table>\n");
out.write(" </form>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write("\n");
out.write(" </tbody>\n");
out.write("</table>\n");
out.write("<br />\n");
out.write("</body>\n");
out.write("</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_005fout_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_spring_005fbind_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_spring_005fbind_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_005fout_005f0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_005fout_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fout_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_spring_005fbind_005f0);
// /WEB-INF/jsp/register.jsp(56,44) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_c_005fout_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${status.value}", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fout_005f0 = _jspx_th_c_005fout_005f0.doStartTag();
if (_jspx_th_c_005fout_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f0);
return true;
}
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f0);
return false;
}
private boolean _jspx_meth_c_005fout_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_spring_005fbind_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_spring_005fbind_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_005fout_005f1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_005fout_005f1.setPageContext(_jspx_page_context);
_jspx_th_c_005fout_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_spring_005fbind_005f0);
// /WEB-INF/jsp/register.jsp(59,14) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_c_005fout_005f1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${status.errorMessage}", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fout_005f1 = _jspx_th_c_005fout_005f1.doStartTag();
if (_jspx_th_c_005fout_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f1);
return true;
}
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f1);
return false;
}
private boolean _jspx_meth_c_005fout_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_spring_005fbind_005f1, PageContext _jspx_page_context, int[] _jspx_push_body_count_spring_005fbind_005f1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_005fout_005f2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_005fout_005f2.setPageContext(_jspx_page_context);
_jspx_th_c_005fout_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_spring_005fbind_005f1);
// /WEB-INF/jsp/register.jsp(67,58) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_c_005fout_005f2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${status.value}", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fout_005f2 = _jspx_th_c_005fout_005f2.doStartTag();
if (_jspx_th_c_005fout_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f2);
return true;
}
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f2);
return false;
}
private boolean _jspx_meth_c_005fout_005f3(javax.servlet.jsp.tagext.JspTag _jspx_th_spring_005fbind_005f1, PageContext _jspx_page_context, int[] _jspx_push_body_count_spring_005fbind_005f1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_005fout_005f3 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_005fout_005f3.setPageContext(_jspx_page_context);
_jspx_th_c_005fout_005f3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_spring_005fbind_005f1);
// /WEB-INF/jsp/register.jsp(70,12) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null
_jspx_th_c_005fout_005f3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${status.errorMessage}", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fout_005f3 = _jspx_th_c_005fout_005f3.doStartTag();
if (_jspx_th_c_005fout_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f3);
return true;
}
_005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f3);
return false;
}
}
| 59.484932 | 279 | 0.693626 |
3d4610013920beaf08d65a38bc4589d2a25df604 | 643 | package com.example.bottomnav;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName;
import java.util.HashMap;
public class ConstContents {
String value;
String name;
String typeQualifer;
String type;
public ConstContents(CPPASTName iName, CPPASTLiteralExpression iValue, IToken iTQ, CPPASTName iType) throws Exception {
value = iValue.getRawSignature();
typeQualifer = iTQ.toString();
name = iName.getRawSignature();
type = iType.getRawSignature();
}
}
| 30.619048 | 123 | 0.735614 |
36100f61cbf1fbed2e265b86e11bcc5feba944a5 | 1,606 | /*
* Copyright (c) 2017. Phasmid Software
*/
package edu.neu.coe.info6205.randomwalk;
import org.junit.Test;
import static org.junit.Assert.*;
public class RandomWalkTest {
/**
*/
@Test
public void testMove1() {
RandomWalk rw = new RandomWalk();
rw.move(1, 0);
assertEquals(rw.distance(), 1.0, 1.0E-7);
rw.move(1, 0);
assertEquals(rw.distance(), 2.0, 1.0E-7);
rw.move(-1, 0);
assertEquals(rw.distance(), 1.0, 1.0E-7);
rw.move(-1, 0);
assertEquals(rw.distance(), 0.0, 1.0E-7);
}
/**
*/
@Test
public void testMove2() {
RandomWalk rw = new RandomWalk();
rw.move(0, 1);
assertEquals(rw.distance(), 1.0, 1.0E-7);
rw.move(0, 1);
assertEquals(rw.distance(), 2.0, 1.0E-7);
rw.move(0, -1);
assertEquals(rw.distance(), 1.0, 1.0E-7);
rw.move(0, -1);
assertEquals(rw.distance(), 0.0, 1.0E-7);
}
/**
*/
@Test
public void testMove3() {
RandomWalk rw = new RandomWalk();
double root2 = Math.sqrt(2);
rw.move(1, 1);
assertEquals(rw.distance(), root2, 1.0E-7);
rw.move(1, 1);
assertEquals(rw.distance(), 2 * root2, 1.0E-7);
rw.move(0, -2);
assertEquals(rw.distance(), 2.0, 1.0E-7);
rw.move(-2, 0);
assertEquals(rw.distance(), 0.0, 1.0E-7);
}
/**
*/
@Test
public void testRandomWalk() {
RandomWalk rw = new RandomWalk();
rw.move(1, 0);
assertEquals(rw.distance(), 1.0, 1.0E-7);
}
} | 23.617647 | 55 | 0.513076 |
936a110990c7b1ffce47e66b4bb3b549f19c4555 | 10,452 | /*
* The MIT License
*
* Copyright 2018 Luis Pichio.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.luispichio.ajmodbus;
import java.util.Arrays;
/**
*
* @author Luis Pichio | [email protected] | https://sites.google.com/site/luispichio/ | https://github.com/luispichio
*/
public class ModbusSlaveParser {
static byte[] readCoils(int slaveAddress, int address, int quantity, int value[]){
byte[] parse = new byte[256];
byte byteCount = (byte)((quantity % 8) == 0 ? quantity / 8 : quantity / 8 + 1);
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_READ_COILS;
parse[size++] = byteCount;
for (int i = 0 ; i < quantity ; i++)
if (value[i] != 0)
parse[size + i / 8] |= 1 << (i & 0x7);
size += byteCount;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] readHoldingRegisters(int slaveAddress, int address, int quantity, int values[]){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_READ_HOLDING_REGISTERS;
parse[size++] = (byte)(2 * quantity);
for (int i = 0 ; i < quantity ; i++){
ModbusUtils.putWord(parse, values[i], size); size += 2;
}
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] readInputRegisters(int slaveAddress, int address, int quantity, int values[]){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_READ_INPUT_REGISTERS;
parse[size++] = (byte)(2 * quantity);
for (int i = 0 ; i < quantity ; i++){
ModbusUtils.putWord(parse, values[i], size); size += 2;
}
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] writeSingleCoil(int slaveAddress, int address, int value){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_COIL;
ModbusUtils.putWord(parse, address, size); size += 2;
ModbusUtils.putWord(parse, value, size); size += 2;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] writeSingleRegister(int slaveAddress, int address, int value){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_REGISTER;
ModbusUtils.putWord(parse, address, size); size += 2;
ModbusUtils.putWord(parse, value, size); size += 2;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] writeMultipleCoils(int slaveAddress, int address, int quantity){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_COILS;
ModbusUtils.putWord(parse, address, size); size += 2;
ModbusUtils.putWord(parse, quantity, size); size += 2;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] writeMultipleRegisters(int slaveAddress, int address, int quantity){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) (slaveAddress & 0xff);
parse[size++] = ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_REGISTERS;
ModbusUtils.putWord(parse, address, size); size += 2;
ModbusUtils.putWord(parse, quantity, size); size += 2;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static byte[] exception(int slaveAddress, int function, int code){
byte[] parse = new byte[256];
int size = 0;
parse[size++] = (byte) slaveAddress;
parse[size++] = (byte) (0x80 | function);
parse[size++] = (byte) code;
ModbusUtils.putWordFlip(parse, ModbusUtils.crc16(0xFFFF, parse, size), size); size += 2;
return Arrays.copyOf(parse, size);
}
static boolean validAddressSlave(int address){
return address < 247;
}
static boolean validFunction(int function){
switch (function){
case ModbusTypes.MODBUS_FUNCTION_READ_COILS:
case ModbusTypes.MODBUS_FUNCTION_READ_HOLDING_REGISTERS:
case ModbusTypes.MODBUS_FUNCTION_READ_INPUT_REGISTERS:
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_COIL:
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_REGISTER:
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_COILS:
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_REGISTERS:
return true;
}
return false;
}
static int findValidADU(byte[] frame, int frameSize){
int offset_begin = 0;
int offset_end;
while (offset_begin <= frameSize - 8){
offset_end = offset_begin;
if (validAddressSlave(frame[offset_end++] & 0xFF)){
if (validFunction(frame[offset_end] & 0xFF)){
switch (frame[offset_end++]){
case ModbusTypes.MODBUS_FUNCTION_READ_COILS:
case ModbusTypes.MODBUS_FUNCTION_READ_HOLDING_REGISTERS:
case ModbusTypes.MODBUS_FUNCTION_READ_INPUT_REGISTERS:
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_COIL:
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_REGISTER:
offset_end += 4;
break;
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_COILS:
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_REGISTERS:
offset_end += 4;
int byteCount = frame[offset_end++] & 0xFF;
if (frame.length - offset_end < byteCount + 2){
offset_begin++;
continue;
}
offset_end += byteCount;
break;
}
if (ModbusUtils.getWordFlip(frame, offset_end) == ModbusUtils.crc16(0xFFFF, frame, offset_end))
return offset_begin;
}
}
offset_begin++;
}
return -1;
}
static ModbusRequest takeRequestFromADU(byte[] adu, int offset){
ModbusRequest request = new ModbusRequest();
request.slaveAddress = adu[offset++] & 0xFF;
request.function = adu[offset++] & 0xFF;
switch (request.function){
case ModbusTypes.MODBUS_FUNCTION_READ_COILS:
case ModbusTypes.MODBUS_FUNCTION_READ_HOLDING_REGISTERS:
case ModbusTypes.MODBUS_FUNCTION_READ_INPUT_REGISTERS:
request.address = ModbusUtils.getWord(adu, offset);
offset += 2;
request.quantity = ModbusUtils.getWord(adu, offset);
offset += 2;
break;
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_COIL:
case ModbusTypes.MODBUS_FUNCTION_WRITE_SINGLE_REGISTER:
request.address = ModbusUtils.getWord(adu, offset);
offset += 2;
request.value = new int[1];
request.value[0] = ModbusUtils.getWord(adu, offset);
offset += 2;
break;
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_COILS:
request.address = ModbusUtils.getWord(adu, offset);
offset += 2;
request.quantity = ModbusUtils.getWord(adu, offset);
offset += 2;
offset++;
request.value = new int[request.quantity];
for (int i = 0 ; i < request.quantity ; i++)
request.value[i] = (adu[offset + i / 8] & (1 << (i % 8))) != 0 ? 0xFF00 : 0x0000;
break;
case ModbusTypes.MODBUS_FUNCTION_WRITE_MULTIPLE_REGISTERS:
request.address = ModbusUtils.getWord(adu, offset);
offset += 2;
request.quantity = ModbusUtils.getWord(adu, offset);
offset += 2;
offset++;
request.value = new int[request.quantity];
for (int i = 0 ; i < request.quantity ; i++){
request.value[i] = ModbusUtils.getWord(adu, offset);
offset += 2;
}
break;
default:
return null;
}
return request;
}
} | 45.443478 | 121 | 0.596824 |
4cce50f371a5c0bf22c89243e43f25a537bdb1a2 | 1,049 | package com.h5190066.sumeyye_cakir_final.adaptor;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.h5190066.sumeyye_cakir_final.R;
public class MakyajViewHolder extends RecyclerView.ViewHolder {
ImageView MakyajLogoimg;
TextView txtMakyajAdi,txtRenkSecenegi2,txtKullanimAlani2;
public MakyajViewHolder(@NonNull View cardView, MakyajAdaptor.OnItemClickListener listener) {
super(cardView);
MakyajLogoimg =cardView.findViewById(R.id.MakyajLogoimg);
txtMakyajAdi =cardView.findViewById(R.id.txtMakyajAdi);
txtRenkSecenegi2 =cardView.findViewById(R.id.txtRenkSecenegi2);
txtKullanimAlani2 =cardView.findViewById(R.id.txtKullanimAlani2);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onClik(getAdapterPosition());
}
});
}
} | 36.172414 | 97 | 0.741659 |
56bd4701c74a4c231760efa29fb8820fd8951319 | 2,706 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.executor.test;
import com.alibaba.polardbx.executor.cursor.AbstractCursor;
import com.alibaba.polardbx.optimizer.config.table.ColumnMeta;
import com.alibaba.polardbx.optimizer.config.table.Field;
import com.alibaba.polardbx.optimizer.core.CursorMeta;
import com.alibaba.polardbx.optimizer.core.datatype.DataType;
import com.alibaba.polardbx.optimizer.core.row.ArrayRow;
import com.alibaba.polardbx.optimizer.core.row.Row;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MockArrayCursor extends AbstractCursor {
private List<Row> rows = new ArrayList<>();
private Iterator<Row> iter = null;
private CursorMeta meta;
private final String tableName;
private List<ColumnMeta> columns = new ArrayList<>();
private Row current;
private boolean closed = false;
public MockArrayCursor(String tableName) {
super(false);
this.tableName = tableName;
}
public void addColumn(String columnName, DataType type) {
Field field = new Field(tableName, columnName, type);
ColumnMeta c = new ColumnMeta(this.tableName, columnName, null, field);
columns.add(c);
}
public void addRow(Object[] values) {
ArrayRow row = new ArrayRow(this.meta, values);
rows.add(row);
}
@Override
public void doInit() {
iter = rows.iterator();
}
@Override
public Row doNext() {
if (iter.hasNext()) {
current = iter.next();
return current;
}
current = null;
return null;
}
@Override
public List<Throwable> doClose(List<Throwable> exceptions) {
this.closed = true;
if (exceptions == null) {
exceptions = new ArrayList<>();
}
return exceptions;
}
@Override
public List<ColumnMeta> getReturnColumns() {
return columns;
}
public void initMeta() {
this.meta = CursorMeta.build(columns);
}
public boolean isClosed() {
return this.closed;
}
}
| 28.1875 | 79 | 0.675166 |
3521ce9e5132266755ee4013c889c640d7d5cede | 3,698 | package com.signalDoc_patient.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class QuestionListData implements Parcelable {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("category_id")
@Expose
private Integer categoryId;
@SerializedName("state_id")
@Expose
private Integer stateId;
@SerializedName("created_on")
@Expose
private String createdOn;
@SerializedName("created_by_id")
@Expose
private Integer createdById;
@SerializedName("type_id")
@Expose
private Integer typeId;
private String ansTitle;
public final static Parcelable.Creator<QuestionListData> CREATOR = new Creator<QuestionListData>() {
@SuppressWarnings({
"unchecked"
})
public QuestionListData createFromParcel(Parcel in) {
return new QuestionListData(in);
}
public QuestionListData[] newArray(int size) {
return (new QuestionListData[size]);
}
};
protected QuestionListData(Parcel in) {
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.title = ((String) in.readValue((String.class.getClassLoader())));
this.ansTitle = ((String) in.readValue((String.class.getClassLoader())));
this.categoryId = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.stateId = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.createdOn = ((String) in.readValue((String.class.getClassLoader())));
this.createdById = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.typeId = ((Integer) in.readValue((Integer.class.getClassLoader())));
}
public QuestionListData() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnsTitle() {
return ansTitle;
}
public void setAnsTitle(String ansTitle) {
this.ansTitle = ansTitle;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public Integer getStateId() {
return stateId;
}
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public Integer getCreatedById() {
return createdById;
}
public void setCreatedById(Integer createdById) {
this.createdById = createdById;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(title);
dest.writeValue(categoryId);
dest.writeValue(stateId);
dest.writeValue(createdOn);
dest.writeValue(createdById);
dest.writeValue(typeId);
}
public int describeContents() {
return 0;
}
} | 26.042254 | 105 | 0.613575 |
759d63de76de5d1741db5262be2b7240bb025531 | 3,122 | /*
* 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.felix.scr.impl.logger;
import org.apache.felix.scr.impl.manager.ScrConfiguration;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* Implements an extension to the SCR log manager that uses logger names to
* create a hierarchy of loggers. All messages will be logged via the SCR
* logger's bundle unlike the classic scr log manager that used the bundle's logger.
*
* <ul>
* <li>An ScrLogger will log with the name {@value #SCR_LOGGER_NAME}
* <li>A BundleLogger will log with the name {@value #SCR_LOGGER_PREFIX} + the
* bundle symbolic name
* <li>A ComponentLogger will log with the name {@value #SCR_LOGGER_PREFIX} +
* the bundle symbolic name + "." + component name
* </ul>
*/
class ExtLogManager extends ScrLogManager
{
public static String SCR_LOGGER_NAME = "org.apache.felix.scr.impl";
public static String SCR_LOGGER_PREFIX = "org.apache.felix.scr.";
private final Bundle bundle;
ExtLogManager(BundleContext context, ScrConfiguration config)
{
super(context, config);
this.bundle = context.getBundle();
}
@Override
public ScrLogger scr()
{
return getLogger(bundle, SCR_LOGGER_NAME, ScrLoggerFacade.class);
}
@Override
public BundleLogger bundle(Bundle bundle)
{
return getLogger(bundle, SCR_LOGGER_PREFIX.concat(bundle.getSymbolicName()),
ScrLoggerFacade.class);
}
@Override
public ComponentLogger component(Bundle bundle, String implementationClass,
String componentName)
{
assert bundle != null;
assert bundle.getSymbolicName() != null : "scr requires recent bundles";
assert implementationClass != null;
assert componentName != null;
String loggerName = SCR_LOGGER_PREFIX.concat(bundle.getSymbolicName()).concat(
".").concat(componentName);
ScrLoggerFacade logger = getLogger(bundle, loggerName, ScrLoggerFacade.class);
logger.setPrefix("[" + componentName + "]");
return logger;
}
String componentPrefix(ScrLoggerFacade slf, long id)
{
assert slf.prefix != null;
if (slf.prefix.indexOf(')') < 0)
return slf.prefix.replace("]", "(" + id + ")]");
else
return slf.prefix;
}
}
| 35.078652 | 86 | 0.695708 |
c8541212c577e69f16ed8e8747b019b4f26a6e8b | 2,966 | /*
* Copyright (c) 2014.
* Apex Expert Solutions
* http://www.apexxs.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.
*
* ====================================================================
*
* RegexDetector.java
* This class uses components from the Open Sextant project which is
* also licensed under the Apache License, Version 2.0
* http://www.opensextant.org
* ====================================================================
*/
package com.apexxs.neonblack.detection;
import com.apexxs.neonblack.dao.DetectedLocation;
import com.apexxs.neonblack.setup.Configuration;
import org.opensextant.extraction.TextMatch;
import org.opensextant.extractors.flexpat.TextMatchResult;
import org.opensextant.extractors.xcoord.GeocoordMatch;
import org.opensextant.extractors.xcoord.XCoord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RegexDetector implements NERDetector
{
// protected static String DEFAULT_XCOORD_CFG = "/geocoord_patterns.cfg";
protected static String DEFAULT_XCOORD_CFG = "geocoord_patterns.cfg";
public final static Logger logger = LoggerFactory.getLogger(RegexDetector.class);
private Configuration config = Configuration.getInstance();
public RegexDetector() {}
public List<DetectedLocation> extractLocationNames(String text)
{
List<DetectedLocation> locs = new ArrayList<>();
try
{
// URL url = RegexDetector.class.getResource(DEFAULT_XCOORD_CFG);
URL url = new File(config.getResourceDirectory() + DEFAULT_XCOORD_CFG).toURI().toURL();
XCoord xc = new XCoord(false);
xc.configure(url);
TextMatchResult results = xc.extract_coordinates(text, "id");
if (!results.matches.isEmpty())
{
for (TextMatch textMatch : results.matches)
{
GeocoordMatch geocoordMatch = (GeocoordMatch) textMatch;
DetectedLocation detectedLocation = new DetectedLocation(geocoordMatch);
locs.add(detectedLocation);
}
}
}
catch (Exception ex)
{
logger.error("Error in RegexDetector: " + ex.getMessage());
}
return locs;
}
}
| 34.894118 | 99 | 0.635199 |
c285c7cfe76153c6c9b1bad3bac21aac562cad8e | 2,959 | /*******************************************************************************
* Copyright (c) 2015, 2016 Ecliptical Software Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ecliptical Software Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.ds.internal.annotations;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant;
import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
import org.eclipse.ltk.core.refactoring.participants.MoveParticipant;
import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
public class ComponentMoveParticipant extends MoveParticipant implements ISharableParticipant, ComponentRefactoringParticipant {
private final ComponentRefactoringHelper helper = new ComponentRefactoringHelper(this);
@Override
protected boolean initialize(Object element) {
return helper.initialize(element);
}
@Override
public String getName() {
return Messages.ComponentMoveParticipant_name;
}
public void addElement(Object element, RefactoringArguments arguments) {
helper.addElement(element, arguments);
}
@Override
public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) throws OperationCanceledException {
return helper.checkConditions(pm, context);
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
return helper.createChange(pm);
}
public String getComponentNameRoot(IJavaElement element, RefactoringArguments args) {
IType type = (IType) element;
String compName = type.getFullyQualifiedName();
Object destination = ((MoveArguments) args).getDestination();
if (destination instanceof IPackageFragment) {
//$NON-NLS-1$
compName = String.format("%s.%s", ((IPackageFragment) destination).getElementName(), type.getElementName());
} else if (destination instanceof IType) {
compName = ((IType) destination).getType(type.getElementName()).getFullyQualifiedName();
}
return compName;
}
}
| 43.514706 | 133 | 0.720852 |
0d128bc7d2ab2a170416e8250536fcdfc087b794 | 2,845 | package seedu.address.logic.commands.cookbook;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_RECIPES_LISTED_OVERVIEW;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import seedu.address.logic.commands.CommandResult;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.recipe.Recipe;
import seedu.address.model.recipe.RecipeDescription;
import seedu.address.model.recipe.RecipeName;
import seedu.address.model.recipe.RecipeNameContainsKeywordsPredicate;
public class CookbookSearchByKeywordCommandTest {
private static final List<String> VALID_KEYWORDS_ONE = Arrays.asList("key", "words");
private static final List<String> VALID_KEYWORDS_TWO = Collections.singletonList("keywords");
private static final Recipe VALID_RECIPE = new Recipe(new RecipeName("key words"),
new RecipeDescription("Description"));
private static final RecipeNameContainsKeywordsPredicate VALID_PREDICATE_ONE =
new RecipeNameContainsKeywordsPredicate(VALID_KEYWORDS_ONE);
private static final RecipeNameContainsKeywordsPredicate VALID_PREDICATE_TWO =
new RecipeNameContainsKeywordsPredicate(VALID_KEYWORDS_TWO);
@Test
public void execute_validInput() {
CookbookSearchByKeywordCommand c = new CookbookSearchByKeywordCommand(VALID_PREDICATE_ONE);
Model model = new ModelManager();
model.addCookbookRecipe(VALID_RECIPE);
assertEquals(c.execute(model), new CommandResult(String.format(MESSAGE_RECIPES_LISTED_OVERVIEW,
model.getFilteredCookbookRecipeList().size())));
assertTrue(!model.getFilteredCookbookRecipeList().isEmpty());
CookbookSearchByKeywordCommand d = new CookbookSearchByKeywordCommand(VALID_PREDICATE_TWO);
assertEquals(d.execute(model), new CommandResult(String.format(MESSAGE_RECIPES_LISTED_OVERVIEW,
model.getFilteredCookbookRecipeList().size())));
assertTrue(model.getFilteredCookbookRecipeList().isEmpty());
}
@Test
public void execute_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () ->
new CookbookSearchByKeywordCommand(VALID_PREDICATE_ONE).execute(null));
}
@Test
public void equalsMethod() {
CookbookSearchByKeywordCommand c = new CookbookSearchByKeywordCommand(VALID_PREDICATE_ONE);
assertEquals(c, c);
assertNotEquals(c, new CookbookSearchByKeywordCommand(VALID_PREDICATE_TWO));
assertNotEquals(c, null);
}
}
| 45.887097 | 103 | 0.778207 |
77651912d81676795d37230ab1e23b6b2e8017d1 | 1,034 | package com.didichuxing.doraemonkit.aop.bigimg.glide;
import android.support.annotation.Nullable;
import com.bumptech.glide.request.RequestListener;
import java.util.ArrayList;
import java.util.List;
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/3/20-18:19
* 描 述:注入到com.bumptech.glide.request.SingleRequest#init(方法中)
* 修订历史:
* ================================================
*/
public class GlideHook {
public static List<RequestListener> proxy(@Nullable List<RequestListener> requestListeners) {
try {
//可能存在用户没有引入okhttp的情况
if (requestListeners == null) {
requestListeners = new ArrayList<>();
requestListeners.add(new DokitGlideRequestListener());
} else {
requestListeners.add(new DokitGlideRequestListener());
}
return requestListeners;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 27.945946 | 97 | 0.560928 |
0888b9431a239906b263dced94aa16e145e12fca | 2,072 | package bio.knowledge.server.controller;
import bio.knowledge.aggregator.KnowledgeBeacon;
import bio.knowledge.database.repository.aggregator.QueryTrackerRepository;
import bio.knowledge.model.aggregator.neo4j.Neo4jQuery;
import bio.knowledge.model.aggregator.neo4j.Neo4jQueryTracker;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class ControllerUtil {
public static List<KnowledgeBeacon> filter(List<KnowledgeBeacon> beacons, List<Integer> filter) {
if (filter != null) {
return beacons.stream().filter(b -> filter.contains(b.getId())).collect(toList());
} else {
return beacons;
}
}
public static void createQuery(QueryTrackerRepository repo, String queryId, List<KnowledgeBeacon> beacons) {
List<Integer> beaconIds = beacons.stream().map(KnowledgeBeacon::getId).collect(toList());
beaconIds.forEach(Objects::requireNonNull);
Set<Neo4jQuery> queries = beaconIds.stream()
.map(i -> new Neo4jQuery() {{ setBeaconId(i); }})
.collect(Collectors.toSet());
Neo4jQueryTracker queryTracker = new Neo4jQueryTracker();
queryTracker.setQueryString(queryId);
queryTracker.setBeaconsHarvested(beaconIds);
queryTracker.setQueries(queries);
repo.save(queryTracker, 5);
}
private static <T> T last(List<T> list) {
return list.get(list.size() - 1);
}
public static <T> List<List<T>> partition(List<T> list, int maxPartitionSize) {
if (list.isEmpty()) {
return new ArrayList<>();
}
List<List<T>> partitions = new ArrayList<>();
partitions.add(new ArrayList<>());
for (T t : list) {
if (last(partitions).size() >= maxPartitionSize) {
partitions.add(new ArrayList<>());
}
last(partitions).add(t);
}
return partitions;
}
}
| 30.925373 | 112 | 0.651062 |
9dbfbf2fabba3513e5c9bf02f7a26e6e57b48787 | 626 | package guru.learningjournal.examples.kafka.kafkaproducer.services;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
@Log4j2
public class KafkaProducerService {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String key, String value) {
log.info(String.format("Producing Message- Key: %s, Value: %s to topic: %s", key, value, topic));
kafkaTemplate.send(topic, key, value);
}
}
| 31.3 | 105 | 0.761981 |
7225725a0637d1fab8c9e29d1b7987264ca317a1 | 1,088 | package org.nypl.simplified.app;
import com.io7m.jfunctional.OptionType;
import org.nypl.drm.core.AdobeAdeptExecutorType;
import org.nypl.simplified.books.core.BooksType;
import org.nypl.simplified.books.core.DocumentStoreType;
import org.nypl.simplified.books.core.FeedLoaderType;
/**
* Services provided to the main Simplified app.
*/
public interface SimplifiedCatalogAppServicesType extends
ScreenSizeControllerType,
NetworkConnectivityType,
SimplifiedAppInitialSyncType
{
/**
* @return A reference to the document store.
*/
DocumentStoreType getDocumentStore();
/**
* @return A book management interface
*/
BooksType getBooks();
/**
* @return A cover provider
*/
BookCoverProviderType getCoverProvider();
/**
* @return An asynchronous feed loader
*/
FeedLoaderType getFeedLoader();
/**
* @return Adobe DRM services, if any are available
*/
OptionType<AdobeAdeptExecutorType> getAdobeDRMExecutor();
/**
* @return HelpStack services, if any are available
*/
OptionType<HelpstackType> getHelpStack();
}
| 19.781818 | 59 | 0.734375 |
abdcb2bead2580ce2f243e9f3df2150b15f0a2ca | 4,826 | package Swift;
//
// SwiftRange.java
// Swift for Java
//
//
// Last modified on 28/11/18 10:01 AM.
//
// Copyright © 2018 Noah Wilder. All rights reserved.
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
//
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class SwiftRange implements Iterable<Integer> {
// Internal variables
private final SwiftRangeIterator swiftRangeIterator;
private int upperBound;
private int lowerBound;
// Constructors
public SwiftRange(int lowerBound, int upperBound) {
assert lowerBound <= upperBound: "Cannot form range with upperBound > lowerBound";
this.swiftRangeIterator = new SwiftRangeIterator(lowerBound);
this.lowerBound = (int) lowerBound;
this.upperBound = (int) upperBound;
}
// Iterable methods
@Override
public Iterator<Integer> iterator() {
return swiftRangeIterator;
}
// Methods
public boolean contains(Integer n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
public boolean contains(Long n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
public boolean contains(Double n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
public boolean contains(int n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
public boolean contains(long n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
public boolean contains(double n) {
if (n >= lowerBound && n <= upperBound) return true;
return false;
}
// Count
public int count() {
return upperBound - lowerBound + 1;
}
// Stream
public Stream<Integer> stream() {
return this.toSwiftArray().stream();
}
public Stream<Integer> parallelStream() {
return this.toSwiftArray().parallelStream();
}
// Bounds
public int lowerBound() { return lowerBound; }
public int upperBound() { return upperBound; }
// Conversion methods
public SwiftArray<Integer> toSwiftArray() {
return SwiftArray.fromRange(lowerBound, upperBound);
}
public ArrayList<Integer> toArrayList() {
var arrayList = new ArrayList<Integer>();
arrayList.ensureCapacity(upperBound - lowerBound + 1);
for (int i = lowerBound; i <= upperBound; i++) {
arrayList.add(i);
}
return arrayList;
}
public List<Integer> toList() {
List<Integer> list = List.of();
for (int i = lowerBound; i <= upperBound; i++) {
list.add(i);
}
return list;
}
public int[] toArray() {
var arr = new int[upperBound - lowerBound + 1];
var fillCount = 0;
for (int i = lowerBound; fillCount < count(); i++) {
arr[fillCount] = i;
fillCount++;
}
return arr;
}
// Iterator
public class SwiftRangeIterator implements Iterator<Integer> {
private int index;
public SwiftRangeIterator(int lowerBound) {
index = lowerBound;
}
@Override
public boolean hasNext() {
return index <= upperBound;
}
@Override
public Integer next() {
return index++;
}
}
// Enumerated
public final List<EnumeratedPair<Integer>> enumerated() {
return IntStream.range(0, this.count())
.mapToObj(i -> EnumeratedPair.of(i, Integer.valueOf(this.lowerBound + i)))
.collect(Collectors.toList());
}
// Equality
public final boolean equals(SwiftRange range) {
return this.lowerBound == range.lowerBound && this.upperBound == range.upperBound;
}
// To String
@Override
public String toString() {
var stringBuilder = new StringBuilder();
for (int i = lowerBound; i <= upperBound; i++) {
stringBuilder.append(i).append(", ");
}
return stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length()).toString();
}
public String toString(String withSeparator) {
var stringBuilder = new StringBuilder();
for (int i = lowerBound; i <= upperBound; i++) {
stringBuilder.append(i).append(withSeparator);
}
return stringBuilder.delete(stringBuilder.length() - withSeparator.length(), stringBuilder.length()).toString();
}
}
| 28.05814 | 120 | 0.59656 |
4e14bd222bb70b5f5ce7dbd85fdfc89e9a9c35bf | 3,937 |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen;
import com.google.common.base.Converter;
import com.google.common.base.Preconditions;
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import io.permazen.change.ListFieldAdd;
import io.permazen.change.ListFieldClear;
import io.permazen.change.ListFieldRemove;
import io.permazen.change.ListFieldReplace;
import io.permazen.core.ObjId;
import io.permazen.core.Transaction;
import io.permazen.schema.ListSchemaField;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a list field in a {@link JClass}.
*/
public class JListField extends JCollectionField {
JListField(Permazen jdb, String name, int storageId,
io.permazen.annotation.JListField annotation, JSimpleField elementField, String description, Method getter) {
super(jdb, name, storageId, annotation, elementField, description, getter);
}
@Override
public io.permazen.annotation.JListField getDeclaringAnnotation() {
return (io.permazen.annotation.JListField)super.getDeclaringAnnotation();
}
@Override
public List<?> getValue(JObject jobj) {
Preconditions.checkArgument(jobj != null, "null jobj");
return jobj.getTransaction().readListField(jobj.getObjId(), this.storageId, false);
}
@Override
public <R> R visit(JFieldSwitch<R> target) {
return target.caseJListField(this);
}
@Override
ListSchemaField toSchemaItem(Permazen jdb) {
final ListSchemaField schemaField = new ListSchemaField();
super.initialize(jdb, schemaField);
return schemaField;
}
@Override
ListElementIndexInfo toIndexInfo(JSimpleField subField) {
assert subField == this.elementField;
return new ListElementIndexInfo(this);
}
@Override
@SuppressWarnings("serial")
<E> TypeToken<List<E>> buildTypeToken(TypeToken<E> elementType) {
return new TypeToken<List<E>>() { }.where(new TypeParameter<E>() { }, elementType);
}
// This method exists solely to bind the generic type parameters
@Override
@SuppressWarnings("serial")
<T, E> void addChangeParameterTypes(List<TypeToken<?>> types, Class<T> targetType, TypeToken<E> elementType) {
types.add(new TypeToken<ListFieldAdd<T, E>>() { }
.where(new TypeParameter<T>() { }, targetType)
.where(new TypeParameter<E>() { }, elementType.wrap()));
types.add(new TypeToken<ListFieldClear<T>>() { }
.where(new TypeParameter<T>() { }, targetType));
types.add(new TypeToken<ListFieldRemove<T, E>>() { }
.where(new TypeParameter<T>() { }, targetType)
.where(new TypeParameter<E>() { }, elementType.wrap()));
types.add(new TypeToken<ListFieldReplace<T, E>>() { }
.where(new TypeParameter<T>() { }, targetType)
.where(new TypeParameter<E>() { }, elementType.wrap()));
}
@Override
public ListConverter<?, ?> getConverter(JTransaction jtx) {
final Converter<?, ?> elementConverter = this.elementField.getConverter(jtx);
return elementConverter != null ? this.createConverter(elementConverter) : null;
}
// This method exists solely to bind the generic type parameters
private <X, Y> ListConverter<X, Y> createConverter(Converter<X, Y> elementConverter) {
return new ListConverter<>(elementConverter);
}
// POJO import/export
@Override
List<Object> createPojoCollection(Class<?> collectionType) {
return new ArrayList<>();
}
@Override
List<?> readCoreCollection(Transaction tx, ObjId id) {
return tx.readListField(id, this.storageId, true);
}
// Bytecode generation
@Override
Method getFieldReaderMethod() {
return ClassGenerator.JTRANSACTION_READ_LIST_FIELD_METHOD;
}
}
| 33.364407 | 115 | 0.687325 |
60cb8bd41207e0f2efdfd21193826785ecc9c5be | 2,151 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
/**
*
* 플로이드 알고리즘으로는 어떻게 풀 수 있을까?
* 플로이드를 돌리고 간선 간의 최댓값이 정답이 된다.
*
* 이분탐색과 BFS를 활용할 수 있을 거 같은데 나는 안된다 ㅠㅠ
*
* @author leedongjun
*
*/
public class MainARCTIC_dbfldkfdbgml2 {
private static Point[] list;
private static int N;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
for (int test = 0; test < T; test++) {
N = Integer.parseInt(br.readLine());
list = new Point[N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
list[i] = new Point(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
}
// 최소 무전기의 출력을 하기 위해 소숫점 밑 셋째 자리에서 반올림해 출력합니다.
double[][] graph = new double[N][N];
boolean[][] visited = new boolean[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
graph[i][j] = distance(list[i], list[j]);
visited[i][j] = true;
visited[j][i] = true;
}
}
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
graph[i][j] = Math.min(graph[i][k] + graph[k][j], graph[i][j]);
}
}
}
double answer = Integer.MAX_VALUE;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) {
continue;
}
answer = Math.min(answer, graph[i][j]);
}
}
bw.write(String.format("%.2f", ((double) Math.round(answer * 100)) / 100) + "\n");
}
bw.flush();
bw.close();
br.close();
}
private static double distance(Point p1, Point p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
private static class Point {
double x, y;
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
}
} | 23.9 | 96 | 0.585309 |
163bdbe8c3197ef7180812c0bfb585dafcef4017 | 4,536 | package uk.co.hillion.jake.proxmox;
import com.fasterxml.jackson.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public interface AppendKeyMaps {
@JsonAnyGetter
default Map<String, Object> getProperties() {
Map<String, Object> out = new HashMap<>();
Properties p = Properties.of(this.getClass());
for (Field field : p.getFields()) {
String fieldName = p.getFieldName(field);
try {
Map<?, ?> fieldVal = (Map<?, ?>) field.get(this);
if (fieldVal == null) continue;
for (Object obj : fieldVal.entrySet()) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) obj;
out.put(String.format("%s%s", fieldName, entry.getKey()), entry.getValue());
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return out;
}
@JsonAnySetter
default void setProperty(String key, String value) {
Properties p = Properties.of(this.getClass());
Map.Entry<Field, String> match = p.getFieldMatch(key);
if (match != null) {
Field field = match.getKey();
Type genericFieldType = field.getGenericType();
ParameterizedType fieldType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = fieldType.getActualTypeArguments();
Object mapKey = match.getValue();
if (fieldArgTypes[0] == Integer.class) {
mapKey = Integer.parseInt(match.getValue());
}
try {
Map map = (Map) field.get(this);
if (map == null) {
map = new HashMap();
field.set(this, map);
}
map.put(mapKey, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonIgnore
@interface AppendKeyMap {}
class Properties {
private final Map<Field, Pattern> patternFieldMap;
private final Map<Field, String> fieldNames;
private Properties(Map<Field, Pattern> patternFieldMap, Map<Field, String> fieldNames) {
this.patternFieldMap = Map.copyOf(patternFieldMap);
this.fieldNames = fieldNames;
}
private static <T> Properties of(Class<T> clazz) {
Map<Field, String> fieldNames = new HashMap<>();
Map<Field, Pattern> patternFieldMap = new HashMap<>();
for (Field field : clazz.getFields()) {
if (field.isAnnotationPresent(AppendKeyMap.class)) {
String fieldName;
if (field.isAnnotationPresent(JsonProperty.class)) {
JsonProperty prop = field.getAnnotation(JsonProperty.class);
if (prop.value().equals(JsonProperty.USE_DEFAULT_NAME)) {
fieldName = field.getName();
} else {
fieldName = prop.value();
}
} else {
fieldName = field.getName();
}
fieldNames.put(field, fieldName);
if (!field.getType().isAssignableFrom(Map.class)) {
throw new RuntimeException("field not a map");
}
Type genericFieldType = field.getGenericType();
ParameterizedType fieldType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = fieldType.getActualTypeArguments();
Pattern pattern;
if (fieldArgTypes[0] == Integer.class) {
pattern = Pattern.compile(String.format("%s(\\d+)", fieldName));
} else {
pattern = Pattern.compile(String.format("%s(.+)", fieldName));
}
patternFieldMap.put(field, pattern);
}
}
return new Properties(patternFieldMap, fieldNames);
}
private Map.Entry<Field, String> getFieldMatch(String key) {
for (Map.Entry<Field, Pattern> entry : patternFieldMap.entrySet()) {
Matcher result = entry.getValue().matcher(key);
if (result.find()) {
return Map.entry(entry.getKey(), result.group(1));
}
}
return null;
}
private String getFieldName(Field field) {
return fieldNames.get(field);
}
private Collection<Field> getFields() {
return patternFieldMap.keySet();
}
}
}
| 31.068493 | 92 | 0.628527 |
f238483ecd058ea810470d031aa46d64c92a27b7 | 191 |
public class TestSwingLibrary extends org.robotframework.swing.SwingLibrary {
public TestSwingLibrary() {
super("org/robotframework/swing/testkeyword/**/*.class");
}
}
| 21.222222 | 77 | 0.696335 |
61433648a5bfec904bb2d3ed7ffc35afed9cca4d | 844 | package com.github.sarxos.abberwoult.deployment.item;
import java.util.Map;
import com.github.sarxos.abberwoult.deployment.util.ReceiveInvokerGenerator;
import com.github.sarxos.abberwoult.jandex.Reflector.ClassRef;
import io.quarkus.builder.item.MultiBuildItem;
/**
* @author Bartosz Firyn (sarxos)
*/
public final class SyntheticReceiveInvokerBuildItem extends MultiBuildItem {
private static final ReceiveInvokerGenerator GENERATOR = new ReceiveInvokerGenerator();
private final ClassRef actorClass;
private final Map<String, byte[]> invokers;
public SyntheticReceiveInvokerBuildItem(final ClassRef actorClass) {
this.actorClass = actorClass;
this.invokers = GENERATOR.generate(actorClass);
}
public Map<String, byte[]> getInvokers() {
return invokers;
}
public ClassRef getActorClass() {
return actorClass;
}
}
| 24.823529 | 88 | 0.791469 |
fe1194482623cfb232756f04dd6c8e97e6fabccb | 775 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
package com.microsoft.embeddedsocial.server.model.discover;
import com.microsoft.embeddedsocial.autorest.models.IdentityProvider;
import com.microsoft.embeddedsocial.server.model.UserRequest;
import java.util.List;
public class FindUsersWithThirdPartyAccountsRequest extends UserRequest {
private final IdentityProvider identityProvider;
private final List<String> accountHandles;
public FindUsersWithThirdPartyAccountsRequest(IdentityProvider identityProvider, List<String> accountHandles) {
this.identityProvider = identityProvider;
this.accountHandles = accountHandles;
}
}
| 33.695652 | 115 | 0.80129 |
de7fcd46a5b1d5c9f786008dfc7bd8c0b1322f74 | 128 | /**
* Max
* @author Vladimir Yamnikov ([email protected]).
* @version $2$.
* @since 13.03.2018.
*/
package ru.job4j.max;
| 16 | 51 | 0.625 |
27ba3c5125dfec07b7c30240e50ee0dec4b1ac0e | 10,019 | /*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho.sections.common;
import static com.facebook.litho.widget.RecyclerBinderUpdateCallback.acquire;
import static com.facebook.litho.widget.RecyclerBinderUpdateCallback.release;
import android.support.annotation.Nullable;
import android.support.v4.util.Pools.Pool;
import android.support.v4.util.Pools.SynchronizedPool;
import android.support.v7.util.DiffUtil;
import com.facebook.litho.Component;
import com.facebook.litho.Diff;
import com.facebook.litho.EventHandler;
import com.facebook.litho.annotations.OnEvent;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.sections.ChangeSet;
import com.facebook.litho.sections.Section;
import com.facebook.litho.sections.SectionContext;
import com.facebook.litho.sections.annotations.DiffSectionSpec;
import com.facebook.litho.sections.annotations.OnDiff;
import com.facebook.litho.widget.RecyclerBinderUpdateCallback;
import com.facebook.litho.widget.RecyclerBinderUpdateCallback.ComponentContainer;
import com.facebook.litho.widget.RecyclerBinderUpdateCallback.Operation;
import com.facebook.litho.widget.RenderInfo;
import java.util.ArrayList;
import java.util.List;
/**
* A {@link DiffSectionSpec} that creates a changeSet diffing a generic {@link List<T>} of data.
* This {@link Section} emits the following events:
*
* {@link RenderEvent} whenever it needs a {@link Component} to render a model T from the list of
* data. Providing an handler for this {@link OnEvent} is mandatory.
*
* {@link OnCheckIsSameItemEvent} whenever during a diffing it wants to check whether two items
* represent the same piece of data.
*
* {@link OnCheckIsSameContentEvent} whenever during a diffing it wants to check whether two items
* that represent the same piece of data have exactly the same content.
*
* <p> For example:
* <pre>
* {@code
*
* @GroupSectionSpec
* public class MyGroupSectionSpec {
*
* @OnCreateChildren
* protected Children onCreateChildren(
* SectionContext c,
* @Prop List<Model> modelList) {
*
* Children.create().child(DataDiffSection.create(c)
* .data(modelList)
* .renderEventHandler(MyGroupSection.onRender(c))
* .onCheckIsSameItemEventHandler(MyGroupSection.onCheckIsSameItem(c))
* .onCheckIsSameContentEventHandler(...)
* .build());
* }
*
* @OnEvent(OnCheckIsSameItemEvent.class)
* protected boolean onCheckIsSameItem(@FromEvent Model previousItem, @FromEvent Model nextItem) {
* return previousItem.getId() == nextItem.getId();
* }
*
* @OnEvent(RenderEvent.class)
* protected RenderInfo onRender(ComponentContext c, @FromEvent Object model) {
* return ComponentRenderInfo.create()
* .component(MyComponent.create(c).model(model).build())
* .build();
* }
* </pre>
*
*/
@DiffSectionSpec(events = {
OnCheckIsSameContentEvent.class,
OnCheckIsSameItemEvent.class,
RenderEvent.class})
public class DataDiffSectionSpec<T> {
@OnDiff
public static <T> void onCreateChangeSet(
SectionContext c,
ChangeSet changeSet,
@Prop Diff<List<T>> data,
@Prop(optional = true) @Nullable Diff<Boolean> detectMoves) {
final Callback<T> callback = Callback.acquire(c, data.getPrevious(), data.getNext());
DiffUtil.DiffResult result =
DiffUtil.calculateDiff(callback, isDetectMovesEnabled(detectMoves));
final RecyclerBinderUpdateCallback<T> updatesCallback = acquire(
data.getPrevious() != null ? data.getPrevious().size() : 0,
data.getNext(),
new ComponentRenderer(DataDiffSection.getRenderEventHandler(c)),
new DiffSectionOperationExecutor(changeSet));
result.dispatchUpdatesTo(updatesCallback);
updatesCallback.applyChangeset();
Callback.release(callback);
release(updatesCallback);
}
/**
* @return true if detect moves should be enabled when performing the Diff. Detect moves is
* enabled by default
*/
private static boolean isDetectMovesEnabled(@Nullable Diff<Boolean> detectMoves) {
return detectMoves == null || detectMoves.getNext() == null || detectMoves.getNext();
}
private static class DiffSectionOperationExecutor implements
RecyclerBinderUpdateCallback.OperationExecutor {
private final ChangeSet mChangeSet;
private DiffSectionOperationExecutor(ChangeSet changeSet) {
mChangeSet = changeSet;
}
@Override
public void executeOperations(List<Operation> operations) {
for (int i = 0, size = operations.size(); i < size; i++) {
final Operation operation = operations.get(i);
final List<ComponentContainer> components = operation.getComponentContainers();
final int opSize = components == null ? 1 : components.size();
switch (operation.getType()) {
case Operation.INSERT:
if (opSize == 1) {
mChangeSet.insert(operation.getIndex(), components.get(0).getRenderInfo());
} else {
final List<RenderInfo> renderInfos = extractComponentInfos(opSize, components);
mChangeSet.insertRange(operation.getIndex(), opSize, renderInfos);
}
break;
case Operation.DELETE:
// RecyclerBinderUpdateCallback uses the toIndex field of the operation to store count.
final int count = operation.getToIndex();
if (count == 1) {
mChangeSet.delete(operation.getIndex());
} else {
mChangeSet.deleteRange(operation.getIndex(), count);
}
break;
case Operation.MOVE:
mChangeSet.move(operation.getIndex(), operation.getToIndex());
break;
case Operation.UPDATE:
if (opSize == 1) {
mChangeSet.update(operation.getIndex(), components.get(0).getRenderInfo());
} else {
final List<RenderInfo> renderInfos = extractComponentInfos(opSize, components);
mChangeSet.updateRange(operation.getIndex(), opSize, renderInfos);
}
break;
}
}
}
private static List<RenderInfo> extractComponentInfos(
int opSize,
List<ComponentContainer> components) {
final List<RenderInfo> renderInfos = new ArrayList<>(opSize);
for (int i = 0; i < opSize; i++) {
renderInfos.add(components.get(i).getRenderInfo());
}
return renderInfos;
}
}
private static class ComponentRenderer implements RecyclerBinderUpdateCallback.ComponentRenderer {
private final EventHandler<RenderEvent> mRenderEventEventHandler;
private ComponentRenderer(EventHandler<RenderEvent> renderEventEventHandler) {
mRenderEventEventHandler = renderEventEventHandler;
}
@Override
public RenderInfo render(Object o, int index) {
return DataDiffSection.dispatchRenderEvent(mRenderEventEventHandler, index, o, null);
}
}
private static class Callback<T> extends DiffUtil.Callback {
private static final Pool<Callback> sCallbackPool = new SynchronizedPool<>(2);
private List<T> mPreviousData;
private List<T> mNextData;
private SectionContext mSectionContext;
private EventHandler<OnCheckIsSameItemEvent> mIsSameItemEventHandler;
private EventHandler<OnCheckIsSameContentEvent> mIsSameContentEventHandler;
void init(
SectionContext sectionContext,
List<T> previousData,
List<T> nextData) {
mPreviousData = previousData;
mNextData = nextData;
mSectionContext = sectionContext;
mIsSameItemEventHandler =
DataDiffSection.getOnCheckIsSameItemEventHandler(mSectionContext);
mIsSameContentEventHandler =
DataDiffSection.getOnCheckIsSameContentEventHandler(mSectionContext);
}
@Override
public int getOldListSize() {
return mPreviousData == null ? 0 : mPreviousData.size();
}
@Override
public int getNewListSize() {
return mNextData == null ? 0 : mNextData.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
final T previous = mPreviousData.get(oldItemPosition);
final T next = mNextData.get(newItemPosition);
if (previous == next) {
return true;
}
if (mIsSameItemEventHandler != null) {
return DataDiffSection.dispatchOnCheckIsSameItemEvent(
mIsSameItemEventHandler,
previous,
next);
}
return previous.equals(next);
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
final T previous = mPreviousData.get(oldItemPosition);
final T next = mNextData.get(newItemPosition);
if (previous == next) {
return true;
}
if (mIsSameContentEventHandler != null) {
return DataDiffSection.dispatchOnCheckIsSameContentEvent(
mIsSameContentEventHandler,
previous,
next);
}
return previous.equals(next);
}
private static<T> Callback<T> acquire(
SectionContext sectionContext,
List<T> previousData,
List<T> nextData) {
Callback callback = sCallbackPool.acquire();
if (callback == null) {
callback = new Callback();
}
callback.init(sectionContext, previousData, nextData);
return callback;
}
private static void release(Callback callback) {
callback.mNextData = null;
callback.mPreviousData = null;
callback.mSectionContext = null;
callback.mIsSameItemEventHandler = null;
callback.mIsSameContentEventHandler = null;
sCallbackPool.release(callback);
}
}
}
| 34.548276 | 100 | 0.692484 |
25a9ecf368d5aa7af3438b644c58f04cfec033e4 | 5,480 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.formatter;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.StaticSymbolWhiteSpaceDefinitionStrategy;
import com.jetbrains.python.editor.PythonEnterHandler;
import gnu.trove.TIntIntHashMap;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.atomic.AtomicBoolean;
public class PyWhiteSpaceFormattingStrategy extends StaticSymbolWhiteSpaceDefinitionStrategy {
public PyWhiteSpaceFormattingStrategy() {
super('\\');
}
@Override
public CharSequence adjustWhiteSpaceIfNecessary(@NotNull CharSequence whiteSpaceText,
@NotNull PsiElement startElement,
int startOffset,
int endOffset,
CodeStyleSettings codeStyleSettings) {
CharSequence whiteSpace = super.adjustWhiteSpaceIfNecessary(whiteSpaceText, startElement, startOffset, endOffset, codeStyleSettings);
if (whiteSpace.length() > 0 && whiteSpace.charAt(0) == '\n' && !StringUtil.contains(whiteSpace, 0, whiteSpace.length(), '\\') &&
PythonEnterHandler.needInsertBackslash(startElement.getContainingFile(), startOffset, false)) {
return addBackslashPrefix(whiteSpace, codeStyleSettings);
}
return whiteSpace;
}
private static String addBackslashPrefix(CharSequence whiteSpace, CodeStyleSettings settings) {
PyCodeStyleSettings pySettings = settings.getCustomSettings(PyCodeStyleSettings.class);
return (pySettings.SPACE_BEFORE_BACKSLASH ? " \\" : "\\") + whiteSpace.toString();
}
/**
* Python uses backslashes at the end of the line as indication that next line is an extension of the current one.
* <p/>
* Hence, we need to preserve them during white space manipulation.
*
*
* @param whiteSpaceText white space text to use by default for replacing sub-sequence of the given text
* @param text target text which region is to be replaced by the given white space symbols
* @param startOffset start offset to use with the given text (inclusive)
* @param endOffset end offset to use with the given text (exclusive)
* @param codeStyleSettings the code style settings
* @param nodeAfter
* @return symbols to use for replacing {@code [startOffset; endOffset)} sub-sequence of the given text
*/
@NotNull
@Override
public CharSequence adjustWhiteSpaceIfNecessary(@NotNull CharSequence whiteSpaceText,
@NotNull CharSequence text,
int startOffset,
int endOffset,
CodeStyleSettings codeStyleSettings, ASTNode nodeAfter)
{
// The general idea is that '\' symbol before line feed should be preserved.
TIntIntHashMap initialBackSlashes = countBackSlashes(text, startOffset, endOffset);
if (initialBackSlashes.isEmpty()) {
if (nodeAfter != null && whiteSpaceText.length() > 0 && whiteSpaceText.charAt(0) == '\n' &&
PythonEnterHandler.needInsertBackslash(nodeAfter, false)) {
return addBackslashPrefix(whiteSpaceText, codeStyleSettings);
}
return whiteSpaceText;
}
final TIntIntHashMap newBackSlashes = countBackSlashes(whiteSpaceText, 0, whiteSpaceText.length());
final AtomicBoolean continueProcessing = new AtomicBoolean();
initialBackSlashes.forEachKey(key -> {
if (!newBackSlashes.containsKey(key)) {
continueProcessing.set(true);
return false;
}
return true;
});
if (!continueProcessing.get()) {
return whiteSpaceText;
}
PyCodeStyleSettings settings = codeStyleSettings.getCustomSettings(PyCodeStyleSettings.class);
StringBuilder result = new StringBuilder();
int line = 0;
for (int i = 0; i < whiteSpaceText.length(); i++) {
char c = whiteSpaceText.charAt(i);
if (c != '\n') {
result.append(c);
continue;
}
if (!newBackSlashes.contains(line++)) {
if ((i == 0 || (i > 0 && whiteSpaceText.charAt(i - 1) != ' ')) && settings.SPACE_BEFORE_BACKSLASH) {
result.append(' ');
}
result.append('\\');
}
result.append(c);
}
return result;
}
/**
* Counts number of back slashes per-line.
*
* @param text target text
* @param start start offset to use with the given text (inclusive)
* @param end end offset to use with the given text (exclusive)
* @return map that holds '{@code line number -> number of back slashes}' mapping for the target text
*/
static TIntIntHashMap countBackSlashes(CharSequence text, int start, int end) {
TIntIntHashMap result = new TIntIntHashMap();
int line = 0;
if (end > text.length()) {
end = text.length();
}
for (int i = start; i < end; i++) {
char c = text.charAt(i);
switch (c) {
case '\n': line++; break;
case '\\': result.put(line, 1); break;
}
}
return result;
}
}
| 42.8125 | 140 | 0.645803 |
047fe1d45fd621f05eee4784eb971ebbd9613822 | 3,614 | package com.example.mapsapp.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mapsapp.R;
import com.example.mapsapp.adapters.MapTypeRecyclerViewAdapter;
import com.example.mapsapp.databinding.ActivityMainBinding;
import com.example.mapsapp.models.EMaps;
import com.example.mapsapp.models.MapType;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding mBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
initListOfMaps();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_menu_about:
startActivity(new Intent(MainActivity.this, AboutActivity.class));
break;
case R.id.item_menu_exit:
finish();
}
return true;
}
private void initListOfMaps() {
RecyclerView recyclerView = mBinding.recyclerViewTypeMap;
MapTypeRecyclerViewAdapter adapter =
new MapTypeRecyclerViewAdapter(MainActivity.this);
adapter.addMap(new MapType(
EMaps.NORMAL_LIGHT.getType(),
R.drawable.ic_map_type_normal_light,
"Normal Light"));
adapter.addMap(new MapType(
EMaps.NORMAL_SILVER.getType(),
R.drawable.ic_map_type_normal_silver,
"Normal Silver"));
adapter.addMap(new MapType(
EMaps.NORMAL_RETRO.getType(),
R.drawable.ic_map_type_normal_retro,
"Normal Retro"));
adapter.addMap(new MapType(
EMaps.NORMAL_AUBERGINE.getType(),
R.drawable.ic_map_type_normal_aubergine,
"Normal Aubergine"));
adapter.addMap(new MapType(
EMaps.NORMAL_DARK.getType(),
R.drawable.ic_map_type_normal_dark,
"Normal Dark"));
adapter.addMap(new MapType(
EMaps.SATELLITE.getType(),
R.drawable.ic_map_type_satellite,
"Satellite"));
adapter.addMap(new MapType(
EMaps.HYBRID.getType(),
R.drawable.ic_map_type_hybrid,
"Hybrid"));
adapter.addMap(new MapType(
EMaps.TERRAIN.getType(),
R.drawable.ic_map_type_terrain,
"Terrain"));
recyclerView.setLayoutManager(new LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL,
false));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new MapTypeRecyclerViewAdapter.OnItemClickListener() {
@Override
public void onItemClickListener(MapType mapType) {
Intent intent = new Intent(MainActivity.this, MapActivity.class);
intent.putExtra("map_type", mapType.getType());
startActivity(intent);
}
});
}
}
| 34.09434 | 93 | 0.625346 |
f232bcd066526e6b5f80df61a7dc1cbed4c1ebd0 | 325 | package com.sxquan.manage.generator.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sxquan.core.pojo.generator.GeneratorConfig;
/**
* <p>
* 代码生成配置表 Mapper 接口
* </p>
*
* @author sxquan
* @since 2020-05-21
*/
public interface GeneratorConfigMapper extends BaseMapper<GeneratorConfig> {
}
| 17.105263 | 76 | 0.744615 |
195e7af98bd21b1ff9fdfa4af2f029de1c8c3c39 | 2,839 | package com.example.ftclibexamples;
import com.arcrobotics.ftclib.command.CommandOpMode;
import com.arcrobotics.ftclib.command.OdometrySubsystem;
import com.arcrobotics.ftclib.command.PurePursuitCommand;
import com.arcrobotics.ftclib.drivebase.MecanumDrive;
import com.arcrobotics.ftclib.hardware.motors.Motor;
import com.arcrobotics.ftclib.hardware.motors.MotorEx;
import com.arcrobotics.ftclib.kinematics.HolonomicOdometry;
import com.arcrobotics.ftclib.purepursuit.waypoints.EndWaypoint;
import com.arcrobotics.ftclib.purepursuit.waypoints.GeneralWaypoint;
import com.arcrobotics.ftclib.purepursuit.waypoints.StartWaypoint;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
@Autonomous
@Disabled
public class PurePursuitSample extends CommandOpMode {
// define our constants
static final double TRACKWIDTH = 13.7;
static final double WHEEL_DIAMETER = 4.0; // inches
static double TICKS_TO_INCHES;
static final double CENTER_WHEEL_OFFSET = 2.4;
private HolonomicOdometry m_robotOdometry;
private OdometrySubsystem m_odometry;
private PurePursuitCommand ppCommand;
private MecanumDrive m_robotDrive;
private Motor fL, fR, bL, bR;
private MotorEx leftEncoder, rightEncoder, centerEncoder;
@Override
public void initialize() {
fL = new Motor(hardwareMap, "frontLeft");
fR = new Motor(hardwareMap, "frontRight");
bL = new Motor(hardwareMap, "backLeft");
bR = new Motor(hardwareMap, "backRight");
// create our drive object
m_robotDrive = new MecanumDrive(fL, fR, bL, bR);
leftEncoder = new MotorEx(hardwareMap, "leftEncoder");
rightEncoder = new MotorEx(hardwareMap, "rightEncoder");
centerEncoder = new MotorEx(hardwareMap, "centerEncoder");
// calculate multiplier
TICKS_TO_INCHES = WHEEL_DIAMETER * Math.PI / leftEncoder.getCPR();
// create our odometry object and subsystem
m_robotOdometry = new HolonomicOdometry(
() -> leftEncoder.getCurrentPosition() * TICKS_TO_INCHES,
() -> rightEncoder.getCurrentPosition() * TICKS_TO_INCHES,
() -> centerEncoder.getCurrentPosition() * TICKS_TO_INCHES,
TRACKWIDTH, CENTER_WHEEL_OFFSET
);
m_odometry = new OdometrySubsystem(m_robotOdometry);
// create our pure pursuit command
ppCommand = new PurePursuitCommand(
m_robotDrive, m_odometry,
new StartWaypoint(0, 0),
new GeneralWaypoint(200, 0, 0.8, 0.8, 30),
new EndWaypoint(
400, 0, 0, 0.5,
0.5, 30, 0.8, 1
)
);
// schedule the command
schedule(ppCommand);
}
}
| 37.853333 | 75 | 0.686509 |
2d970050f1ce01ead853e48c47585bb3860613d9 | 927 | package top.xiaohuashifu.share.manager;
import com.github.pagehelper.PageInfo;
import top.xiaohuashifu.share.constant.Operator;
import top.xiaohuashifu.share.pojo.do0.ShareCommentCommentDO;
import top.xiaohuashifu.share.pojo.query.ShareCommentCommentQuery;
import top.xiaohuashifu.share.pojo.vo.ShareCommentCommentVO;
import top.xiaohuashifu.share.result.Result;
/**
* 描述:
*
* @author xhsf
* @email [email protected]
*/
public interface ShareCommentCommentManager {
Result<ShareCommentCommentVO> saveShareCommentComment(ShareCommentCommentDO shareCommentCommentDO);
Result<ShareCommentCommentVO> getShareCommentComment(Integer id, Integer userId);
Result<PageInfo<ShareCommentCommentVO>> listShareCommentComments(ShareCommentCommentQuery query, Integer userId);
Result<ShareCommentCommentVO> updateShareCommentComment(Integer id, String parameterName, Operator operator);
}
| 34.333333 | 118 | 0.803668 |
7c91380216efa75658e339cd2cad3a836c1038ca | 1,778 | /*
* Copyright (c) 2002 and later by MH Software-Entwicklung. All Rights Reserved.
*
* JTattoo is multiple licensed. If your are an open source developer you can use
* it under the terms and conditions of the GNU General Public License version 2.0
* or later as published by the Free Software Foundation.
*
* see: gpl-2.0.txt
*
* If you pay for a license you will become a registered user who could use the
* software under the terms and conditions of the GNU Lesser General Public License
* version 2.0 or later with classpath exception as published by the Free Software
* Foundation.
*
* see: lgpl-2.0.txt
* see: classpath-exception.txt
*
* Registered users could also use JTattoo under the terms and conditions of the
* Apache License, Version 2.0 as published by the Apache Software Foundation.
*
* see: APACHE-LICENSE-2.0.txt
*/
package com.jtattoo.plaf.aluminium;
import com.jtattoo.plaf.AbstractLookAndFeel;
import com.jtattoo.plaf.BaseSplitPaneDivider;
import com.jtattoo.plaf.JTattooUtilities;
import java.awt.*;
/**
* @author Michael Hagen
*/
public class AluminiumSplitPaneDivider extends BaseSplitPaneDivider {
public AluminiumSplitPaneDivider(AluminiumSplitPaneUI ui) {
super(ui);
}
public void paint(Graphics g) {
if (JTattooUtilities.isMac() || !AbstractLookAndFeel.getTheme().isBackgroundPatternOn()) {
super.paint(g);
} else {
AluminiumUtils.fillComponent(g, this);
Graphics2D g2D = (Graphics2D) g;
Composite composite = g2D.getComposite();
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
g2D.setComposite(alpha);
super.paint(g);
g2D.setComposite(composite);
}
}
}
| 32.925926 | 98 | 0.707537 |
26fcf11465444558d4c81a0e71c5516854ef0c03 | 11,065 | package com.cango.palmcartreasure.baseAdapter;
import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cango on 2017/3/20.
* 上拉加载框架和holder处理更加优化,处理无数据和错误的UI
*/
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseHolder> {
public static final int TYPE_COMMON_VIEW = 100001;
public static final int TYPE_FOOTER_VIEW = 100002;
public static final int TYPE_EMPTY_VIEW = 100003;
public static final int TYPE_DEFAULT_VIEW = 100004;
private OnLoadMoreListener mLoadMoreListener;
private OnBaseItemClickListener<T> mItemClickListener;
protected Context mContext;
protected List<T> mDatas;
private boolean mOpenLoadMore;
private boolean isAutoLoadMore = true;
private View mLoadingView;
private View mLoadFailedView;
private View mLoadEndView;
private View mEmptyView;
private RelativeLayout mFooterLayout;
public BaseAdapter(Context context, List<T> datas, boolean isOpenLoadMore){
mContext = context;
mDatas = datas == null ? new ArrayList<T>() : datas;
mOpenLoadMore = isOpenLoadMore;
}
protected abstract int getItemLayoutId();
protected abstract void convert(BaseHolder holder, T data);
@Override
public BaseHolder onCreateViewHolder(ViewGroup parent, int viewType) {
BaseHolder baseHolder=null;
switch (viewType) {
case TYPE_COMMON_VIEW:
baseHolder=BaseHolder.create(mContext,getItemLayoutId(),parent);
break;
case TYPE_FOOTER_VIEW:
if (mFooterLayout == null) {
mFooterLayout = new RelativeLayout(mContext);
}
baseHolder = BaseHolder.create(mFooterLayout);
break;
case TYPE_EMPTY_VIEW:
baseHolder = BaseHolder.create(mEmptyView);
break;
case TYPE_DEFAULT_VIEW:
baseHolder = BaseHolder.create(new View(mContext));
break;
}
return baseHolder;
}
@Override
public void onBindViewHolder(BaseHolder holder, int position) {
switch (holder.getItemViewType()) {
case TYPE_COMMON_VIEW:
bindCommonItem(holder, position);
break;
}
}
private void bindCommonItem(BaseHolder holder, final int position) {
final BaseHolder viewHolder = holder;
convert(viewHolder,mDatas.get(position));
viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mItemClickListener.onItemClick(viewHolder, mDatas.get(position), position);
}
});
}
@Override
public int getItemCount() {return mDatas.size() + getFooterViewCount();}
@Override
public int getItemViewType(int position) {
if (mDatas.isEmpty() && mEmptyView != null) {
return TYPE_EMPTY_VIEW;
}
if (isFooterView(position)) {
return TYPE_FOOTER_VIEW;
}
if (mDatas.isEmpty()) {
return TYPE_DEFAULT_VIEW;
}
return TYPE_COMMON_VIEW;
}
/**
* 是否是FooterView
*
* @param position
* @return
*/
private boolean isFooterView(int position) {
return mOpenLoadMore && getItemCount() > 1 && position >= getItemCount() - 1;
}
/**
* StaggeredGridLayoutManager模式时,FooterView可占据一行
*
* @param holder
*/
@Override
public void onViewAttachedToWindow(BaseHolder holder) {
super.onViewAttachedToWindow(holder);
if (isFooterView(holder.getLayoutPosition())) {
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
p.setFullSpan(true);
}
}
}
/**
* GridLayoutManager模式时, FooterView可占据一行,判断RecyclerView是否到达底部
*
* @param recyclerView
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) layoutManager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (isFooterView(position)) {
return gridManager.getSpanCount();
}
return 1;
}
});
}
startLoadMore(recyclerView, layoutManager);
}
/**
* 判断列表是否滑动到底部
*
* @param recyclerView
* @param layoutManager
*/
private void startLoadMore(RecyclerView recyclerView, final RecyclerView.LayoutManager layoutManager) {
if (!mOpenLoadMore || mLoadMoreListener == null) {
return;
}
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
// Logger.d("onScrollStateChanged isAutoLoadMore= "+isAutoLoadMore+"-------"+findLastVisibleItemPosition(layoutManager));
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (!isAutoLoadMore && findLastVisibleItemPosition(layoutManager) + 1 == getItemCount()) {
scrollLoadMore();
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Logger.d("onScrolled isAutoLoadMore= "+isAutoLoadMore+"-------"+findLastVisibleItemPosition(layoutManager));
if (isAutoLoadMore && findLastVisibleItemPosition(layoutManager) + 1 == getItemCount()) {
scrollLoadMore();
}
// else if (getItemCount()==1){
//// scrollLoadMore();
// }
else if (isAutoLoadMore) {
isAutoLoadMore = false;
}
}
});
}
/**
* 到达底部开始刷新
*/
private void scrollLoadMore() {
if (mFooterLayout.getChildAt(0) == mLoadingView) {
mLoadMoreListener.onLoadMore(false);
}
}
private int findLastVisibleItemPosition(RecyclerView.LayoutManager layoutManager) {
if (layoutManager instanceof LinearLayoutManager) {
return ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(null);
return findMax(lastVisibleItemPositions);
}
return -1;
}
private int findMax(int[] lastVisiblePositions) {
int max = lastVisiblePositions[0];
for (int value : lastVisiblePositions) {
if (value > max) {
max = value;
}
}
return max;
}
private void removeFooterView() {
mFooterLayout.removeAllViews();
}
private void addFooterView(View footerView) {
if (footerView == null) {
return;
}
if (mFooterLayout == null) {
mFooterLayout = new RelativeLayout(mContext);
}
removeFooterView();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mFooterLayout.addView(footerView, params);
}
public void setLoadMoreData(List<T> datas) {
int size = mDatas.size();
mDatas.addAll(datas);
notifyItemInserted(size);
}
public void setData(List<T> datas) {
mDatas.addAll(0, datas);
notifyDataSetChanged();
}
public void setNewData(List<T> datas) {
mDatas.clear();
mDatas.addAll(datas);
notifyDataSetChanged();
}
public void setNewDataNoError(List<T> datas) {
int size = mDatas.size();
mDatas.clear();
notifyItemRangeRemoved(0,size);
mDatas.addAll(datas);
notifyDataSetChanged();
}
/**
* 初始化加载中布局
*
* @param loadingView
*/
public void setLoadingView(View loadingView) {
mLoadingView = loadingView;
addFooterView(mLoadingView);
}
public void setLoadingView(int loadingId) {
setLoadingView(inflate(loadingId));
}
/**
* 初始加载失败布局
*
* @param loadFailedView
*/
public void setLoadFailedView(View loadFailedView) {
if (loadFailedView == null) {
return;
}
mLoadFailedView = loadFailedView;
addFooterView(mLoadFailedView);
mLoadFailedView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addFooterView(mLoadingView);
mLoadMoreListener.onLoadMore(true);
}
});
}
public void setLoadFailedView(int loadFailedId) {
setLoadFailedView(inflate(loadFailedId));
}
/**
* 初始化全部加载完成布局
*
* @param loadEndView
*/
public void setLoadEndView(View loadEndView) {
mLoadEndView = loadEndView;
addFooterView(mLoadEndView);
}
public void setLoadEndView(int loadEndId) {
setLoadEndView(inflate(loadEndId));
}
public void setEmptyView(View emptyView) {
mEmptyView = emptyView;
}
public int getFooterViewCount() {
return mOpenLoadMore ? 1 : 0;
}
public void setOnLoadMoreListener(OnLoadMoreListener loadMoreListener) {
mLoadMoreListener = loadMoreListener;
}
public void setOnItemClickListener(OnBaseItemClickListener<T> itemClickListener) {
mItemClickListener = itemClickListener;
}
private View inflate(int layoutId) {
if (layoutId <= 0) {
return null;
}
return LayoutInflater.from(mContext).inflate(layoutId, null);
}
}
| 31.257062 | 136 | 0.617623 |
9759a2447979f519fa630cff77e1231d030b7ec9 | 737 | package org.narrative.network.core.search;
import org.narrative.common.persistence.OID;
import org.narrative.network.core.composition.base.CompositionConsumer;
import org.narrative.network.core.composition.base.CompositionType;
import org.narrative.network.core.user.User;
import java.sql.Timestamp;
/**
* Date: Nov 2, 2009
* Time: 3:01:50 PM
*
* @author Steven Benitez
*/
public interface MessageSearchResult extends SearchResult {
public User getAuthor();
public OID getCompositionConsumerOid();
public void setCompositionConsumer(CompositionConsumer consumer);
public CompositionConsumer getCompositionConsumer();
public CompositionType getCompositionType();
public Timestamp getLiveDatetime();
}
| 25.413793 | 71 | 0.784261 |
9c3521f3951719c430fd2aa9a88f5b7443ff4e5f | 1,451 | package io.github.nandandesai.tests;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.github.nandandesai.twitterscraper4j.TwitterScraper;
import io.github.nandandesai.twitterscraper4j.exceptions.TwitterException;
import io.github.nandandesai.twitterscraper4j.models.Profile;
import java.io.IOException;
public class ProfileTest {
public static void main(String[] args){
testProfileFetch("nandankdesai"); //protected
testProfileFetch("fs0c131y"); //unverified
testProfileFetch("realDonaldTrump"); //verified
testProfileFetch("asdfasdfasdfasd121212"); //doesn't exists
testProfileFetch("kashmirintel"); //suspended
testProfileFetch("Gurmeetramrahim"); //withheld
}
private static void testProfileFetch(String username){
try {
TwitterScraper scraper = TwitterScraper.getInstance();
Profile profile = scraper.getProfile(username);//fs0c131y
displayProfile(profile);
}catch (IOException io){
io.printStackTrace();
} catch (TwitterException e) {
System.out.println("Http Status Code: "+e.getHttpStatusCode());
e.printStackTrace();
}
}
private static void displayProfile(Profile profile){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(gson.toJson(profile));
System.out.println(profile);
}
}
| 35.390244 | 75 | 0.689869 |
86a390f93349825a891a609ad3586705695f0db9 | 1,107 | package io.toolisticon.cute;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.lang.model.element.Element;
/**
* Interface that is used during unit test creation. It allows setting up a unit test without the need to create a valid annotation processor.
* In comparision to {@link UnitTest} an instance of the processor under test will be created and it's init method will be called.
*
* @param <PROCESSOR> the processor to use
* @param <ELEMENT_TYPE> the expected element type to be found
*/
public interface UnitTestForTestingAnnotationProcessors<PROCESSOR extends Processor, ELEMENT_TYPE extends Element> {
/**
* The unit test method.
*
* @param unit the initialized processor under test (initialized via init method)
* @param processingEnvironment the processingEnvironment
* @param element the element the underlying annotation processor is applied on
*/
public void unitTest(PROCESSOR unit, ProcessingEnvironment processingEnvironment, ELEMENT_TYPE element);
}
| 44.28 | 142 | 0.756098 |
78c19d5720ae8fb9fb98241a03fcb6538c2a1054 | 6,772 | package com.template.apiservice.util;
import java.util.Collections;
import java.util.Map;
import com.template.apiservice.exception.CallServiceException;
import com.template.apiservice.exception.NoDataFoundException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
public class RestClient {
RestTemplate restTemplate;
RestClientExceptionHandler errorHandler;
public RestClient() {
this.restTemplate = new RestTemplate();
this.errorHandler = new RestClientExceptionHandler();
this.restTemplate.setErrorHandler(errorHandler);
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(1000000);
requestFactory.setReadTimeout(1000000);
BufferingClientHttpRequestFactory bufferingClientHttpRequestFactory =
new BufferingClientHttpRequestFactory(requestFactory);
this.restTemplate.setRequestFactory(bufferingClientHttpRequestFactory);
}
public <T> T get(String url, Class<T> responseType) {
try {
return restTemplate.getForObject(url, responseType);
} catch (NoDataFoundException e) {
return null;
}
}
public <T> T get(String url, Class<T> responseType, Map<String, String> queryParams) {
try {
return restTemplate.getForObject(url, responseType, queryParams);
} catch (NoDataFoundException e) {
return null;
}
}
public <K> K get(
String url,
Class<K> responseType,
Map<String, String> queryParams,
Map<String, String> headerParams) {
HttpMethod httpMethod = HttpMethod.GET;
HttpHeaders httpHeaders = setHeaders(headerParams);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(httpHeaders);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
if (!CollectionUtils.isEmpty(queryParams)) {
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
}
ResponseEntity<K> response = exchange(responseType, httpEntity, builder, httpMethod);
if (response.getStatusCode().is4xxClientError()) {
throw new CallServiceException("Service is not working properly!");
}
return response.getBody();
}
public <T, K> K patch(String url, T body, Class<K> responseType) {
try {
return restTemplate.patchForObject(url, body, responseType);
} catch (Exception e) {
// log.error("Unsuccessful service call. URL: " + url, e);
throw new CallServiceException("Can not call " + url + " -- \nError Detail:" + e.toString());
}
}
public void delete(String url) {
try {
restTemplate.delete(url);
;
} catch (Exception e) {
throw new CallServiceException("Can not call " + url + " -- \nError Detail:" + e.toString());
}
}
public <T, K> K post(String url, T body, Class<K> responseType) {
try {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
HttpEntity<T> httpEntity = new HttpEntity<>(body);
ResponseEntity<K> response = exchange(responseType, httpEntity, builder, HttpMethod.POST);
return response.getBody();
} catch (Exception e) {
// log.error("Unsuccessful service call. URL: " + url, e);
throw new CallServiceException("Can not call " + url + " -- \nError Detail:" + e.toString());
}
}
public <T, K> K post(
String url, Class<K> responseType, T body, Map<String, String> headerParams) {
HttpMethod httpMethod = HttpMethod.POST;
try {
HttpHeaders httpHeaders = setHeaders(headerParams);
HttpEntity<T> httpEntity = new HttpEntity<>(body, httpHeaders);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
ResponseEntity<K> response = exchange(responseType, httpEntity, builder, httpMethod);
return response.getBody();
} catch (Exception e) {
throw new CallServiceException("Can not call " + url + " -- \nError Detail:" + e.toString());
}
}
public <T, K> K put(String url, Class<K> responseType, T body, Map<String, String> headerParams) {
HttpMethod httpMethod = HttpMethod.PUT;
try {
HttpHeaders httpHeaders = setHeaders(headerParams);
HttpEntity<T> httpEntity = new HttpEntity<>(body, httpHeaders);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
ResponseEntity<K> response = exchange(responseType, httpEntity, builder, httpMethod);
return response.getBody();
} catch (Exception e) {
throw new CallServiceException("Can not call " + url + " -- \nError Detail:" + e.toString());
}
}
protected HttpHeaders setHeaders(Map<String, String> headerParams) {
HttpHeaders httpHeaders = new HttpHeaders();
if (!CollectionUtils.isEmpty(headerParams)) {
for (Map.Entry<String, String> entry : headerParams.entrySet()) {
httpHeaders.set(entry.getKey(), entry.getValue());
}
}
return httpHeaders;
}
protected <K> ResponseEntity<K> exchange(
Class<K> responseType,
HttpEntity httpEntity,
UriComponentsBuilder builder,
HttpMethod httpMethod) {
try {
ResponseEntity<K> response =
restTemplate.exchange(
builder.build().toUriString(), httpMethod, httpEntity, responseType);
return response;
} catch (NoDataFoundException e) {
if (httpMethod.equals(HttpMethod.GET)) {
return null;
} else {
throw e;
}
}
}
protected <K> ResponseEntity<K> exchange(
ParameterizedTypeReference<K> responseType,
HttpEntity httpEntity,
UriComponentsBuilder builder,
HttpMethod httpMethod) {
try {
ResponseEntity<K> response =
restTemplate.exchange(
builder.build().toUriString(), httpMethod, httpEntity, responseType);
return response;
} catch (NoDataFoundException e) {
if (httpMethod.equals(HttpMethod.GET)) {
return null;
} else {
throw e;
}
}
}
public void setInterceptor(ClientHttpRequestInterceptor logInterceptor) {
restTemplate.setInterceptors(Collections.singletonList(logInterceptor));
}
}
| 34.20202 | 100 | 0.700236 |
2e435eaff0d5037a07a6fb05215d3d108b416d0d | 10,169 | package pro.taskana.monitor.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pro.taskana.monitor.api.reports.Report;
import pro.taskana.monitor.api.reports.header.TimeIntervalColumnHeader;
import pro.taskana.monitor.api.reports.item.MonitorQueryItem;
import pro.taskana.monitor.api.reports.item.QueryItemPreprocessor;
import pro.taskana.monitor.api.reports.row.FoldableRow;
import pro.taskana.monitor.api.reports.row.Row;
import pro.taskana.monitor.api.reports.row.SingleRow;
/** Tests for {@link Report}. */
class ReportTest {
private static final List<TimeIntervalColumnHeader> HEADERS =
IntStream.range(0, 4).mapToObj(TimeIntervalColumnHeader::new).collect(Collectors.toList());
private Report<MonitorQueryItem, TimeIntervalColumnHeader> report;
private MonitorQueryItem item;
@BeforeEach
void before() {
this.report =
new MonitorQueryItemTimeIntervalColumnHeaderReport(HEADERS, new String[] {"rowDesc"});
item = new MonitorQueryItem();
item.setKey("key");
item.setAgeInDays(0);
item.setNumberOfTasks(3);
}
@Test
void should_HaveSumRowTotalKey_When_ReportExists() {
assertThat(report.getSumRow().getKey()).isEqualTo("Total");
}
@Test
void should_HaveEmptySumRow_When_ReportIsEmpty() {
// then
assertThat(report.getRows()).isEmpty();
Row<MonitorQueryItem> sumRow = report.getSumRow();
assertThat(sumRow.getCells()).isEqualTo(new int[] {0, 0, 0, 0});
assertThat(sumRow.getTotalValue()).isEqualTo(0);
}
@Test
void should_CreateRowAndSetKey_When_InsertingItemWithUnknownKey() {
// when
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getKey()).isEqualTo("key");
}
@Test
void should_CreateFoldableRowAndSetKey_When_InsertingItemWithUnknownKey() {
// when
ReportWithFoldableRow report =
new ReportWithFoldableRow(HEADERS, new String[] {"rowDesc", "foldableRowDesc"});
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
FoldableTestRow row = report.getRow("key");
assertThat(row.getKey()).isEqualTo("key");
assertThat(row.getFoldableRowCount()).isOne();
Row<MonitorQueryItem> foldableRow = row.getFoldableRow("KEY");
assertThat(foldableRow.getKey()).isEqualTo("KEY");
}
@Test
void should_AppendItemValueInFoldableRow_When_ItemIsInserted() {
// when
ReportWithFoldableRow report =
new ReportWithFoldableRow(HEADERS, new String[] {"rowDesc", "foldableRowDesc"});
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
FoldableTestRow row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {item.getValue(), 0, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(item.getValue());
assertThat(row.getFoldableRowCount()).isOne();
Row<MonitorQueryItem> foldableRow = row.getFoldableRow("KEY");
assertThat(foldableRow.getCells()).isEqualTo(new int[] {item.getValue(), 0, 0, 0});
assertThat(foldableRow.getTotalValue()).isEqualTo(item.getValue());
}
@Test
void should_AppendItemValue_When_ItemIsInserted() {
// when
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {item.getValue(), 0, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(item.getValue());
}
@Test
void should_AppendItemValue_When_CellAlreadyContainsValue() {
// when
report.addItem(item);
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {2 * item.getValue(), 0, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(2 * item.getValue());
}
@Test
void should_AppendItemValue_When_UsingBulkOperationToInsertItems() {
// when
report.addItems(List.of(item, item));
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {2 * item.getValue(), 0, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(2 * item.getValue());
}
@Test
void should_PreProcessItem_When_PreprocessorIsDefined() {
// given
int overrideValue = 5;
QueryItemPreprocessor<MonitorQueryItem> preprocessor =
item -> {
item.setNumberOfTasks(overrideValue);
return item;
};
item.setAgeInDays(1);
// when
report.addItem(item, preprocessor);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow(item.getKey());
assertThat(row.getCells()).isEqualTo(new int[] {0, overrideValue, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(overrideValue);
Row<MonitorQueryItem> sumRow = report.getSumRow();
assertThat(sumRow.getCells()).isEqualTo(new int[] {0, overrideValue, 0, 0});
assertThat(sumRow.getTotalValue()).isEqualTo(overrideValue);
}
@Test
void should_PreProcessItem_When_PreprocessorIsDefinedForBulkInsert() {
// given
int overrideValue = 5;
QueryItemPreprocessor<MonitorQueryItem> preprocessor =
(item) -> {
item.setNumberOfTasks(overrideValue);
return item;
};
// when
report.addItems(List.of(item, item), preprocessor);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {2 * overrideValue, 0, 0, 0});
assertThat(row.getTotalValue()).isEqualTo(2 * overrideValue);
}
@Test
void should_OnlyContainTotalRows_When_ReportContainsNoHeaders() {
// given
List<TimeIntervalColumnHeader> headerList = List.of();
report =
new MonitorQueryItemTimeIntervalColumnHeaderReport(headerList, new String[] {"rowDesc"});
// when
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
assertThat(report.getRow("key").getCells()).isEqualTo(new int[0]);
assertThat(report.getRow("key").getTotalValue()).isEqualTo(item.getValue());
}
@Test
void should_NotInsertItem_When_ItemIsOutOfHeaderScope() {
// given
item.setAgeInDays(-2);
// when
report.addItem(item);
// then
assertThat(report.getRows()).isEmpty();
Row<MonitorQueryItem> sumRow = report.getSumRow();
assertThat(sumRow.getCells()).isEqualTo(new int[] {0, 0, 0, 0});
assertThat(sumRow.getTotalValue()).isEqualTo(0);
}
@Test
void should_InsertItemMultipleTimes_When_HeaderFitsMultipleTimes() {
// given
List<TimeIntervalColumnHeader> headers = new ArrayList<>(HEADERS);
headers.add(new TimeIntervalColumnHeader(0, 3));
report = new MonitorQueryItemTimeIntervalColumnHeaderReport(headers, new String[] {"rowDesc"});
item.setAgeInDays(2);
// when
report.addItem(item);
// then
assertThat(report.getRows()).hasSize(1);
Row<MonitorQueryItem> row = report.getRow("key");
assertThat(row.getCells()).isEqualTo(new int[] {0, 0, item.getValue(), 0, item.getValue()});
assertThat(row.getTotalValue()).isEqualTo(2 * item.getValue());
Row<MonitorQueryItem> sumRow = report.getSumRow();
assertThat(sumRow.getCells()).isEqualTo(new int[] {0, 0, item.getValue(), 0, item.getValue()});
assertThat(sumRow.getTotalValue()).isEqualTo(2 * item.getValue());
}
@Test
void should_FallBackToKey_When_DisplayMapDoesNotContainName() {
report.augmentDisplayNames(new HashMap<>());
assertThat(report.getSumRow().getDisplayName()).isEqualTo(report.getSumRow().getKey());
}
@Test
void should_SetDisplayName_When_DisplayMapContainsName() {
HashMap<String, String> displayMap = new HashMap<>();
displayMap.put(report.getSumRow().getKey(), "BLA BLA");
report.augmentDisplayNames(displayMap);
assertThat(report.getSumRow().getDisplayName()).isEqualTo("BLA BLA");
}
@Test
void should_SetDisplayNameForFoldableRows_When_DisplayMapContainsNames() {
ReportWithFoldableRow report =
new ReportWithFoldableRow(HEADERS, new String[] {"totalDesc", "foldalbeRowDesc"});
report.addItem(item);
HashMap<String, String> displayMap = new HashMap<>();
displayMap.put("key", "displayname for key");
displayMap.put("KEY", "displayname for KEY");
report.augmentDisplayNames(displayMap);
FoldableTestRow row = report.getRow("key");
assertThat(row.getDisplayName()).isEqualTo("displayname for key");
assertThat(row.getFoldableRow("KEY").getDisplayName()).isEqualTo("displayname for KEY");
}
private static class MonitorQueryItemTimeIntervalColumnHeaderReport
extends Report<MonitorQueryItem, TimeIntervalColumnHeader> {
public MonitorQueryItemTimeIntervalColumnHeaderReport(
List<TimeIntervalColumnHeader> headerList, String[] rowDesc) {
super(headerList, rowDesc);
}
}
private static class ReportWithFoldableRow
extends Report<MonitorQueryItem, TimeIntervalColumnHeader> {
protected ReportWithFoldableRow(
List<TimeIntervalColumnHeader> columnHeaders, String[] rowDesc) {
super(columnHeaders, rowDesc);
}
@Override
public FoldableTestRow getRow(String key) {
return (FoldableTestRow) super.getRow(key);
}
@Override
protected Row<MonitorQueryItem> createRow(String key, int columnSize) {
return new FoldableTestRow(key, columnSize);
}
}
private static class FoldableTestRow extends FoldableRow<MonitorQueryItem> {
protected FoldableTestRow(String key, int columnSize) {
super(key, columnSize, (item) -> item.getKey().toUpperCase());
}
@Override
protected Row<MonitorQueryItem> buildRow(String key, int columnSize) {
return new SingleRow<>(key, columnSize);
}
}
}
| 32.909385 | 99 | 0.706756 |
4d53be283ba1d223e06ca58bfaa85060493f513c | 7,386 | /*
* 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.wicket.proxy.bytebuddy;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Function;
import org.apache.wicket.Application;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.proxy.ILazyInitProxy;
import org.apache.wicket.proxy.IProxyFactory;
import org.apache.wicket.proxy.IProxyTargetLocator;
import org.apache.wicket.proxy.LazyInitProxyFactory.IWriteReplace;
import org.apache.wicket.proxy.objenesis.IInstantiator;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.NamingStrategy;
import net.bytebuddy.TypeCache;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FieldAccessor;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Pipe;
import net.bytebuddy.matcher.ElementMatchers;
/**
* A factory class that creates bytebuddy proxies.
*/
public class ByteBuddyProxyFactory implements IProxyFactory
{
/**
* A cache used to store the dynamically generated classes by ByteBuddy.
* Without this cache a new class will be generated for each proxy creation
* and this will fill up the metaspace
*/
private static final TypeCache<TypeCache.SimpleKey> DYNAMIC_CLASS_CACHE = new TypeCache.WithInlineExpunction<>(TypeCache.Sort.SOFT);
private static final ByteBuddy BYTE_BUDDY = new ByteBuddy().with(WicketNamingStrategy.INSTANCE);
private static final String INTERCEPTOR_FIELD_NAME = "interceptor";
private static final IInstantiator INSTANTIATOR = IInstantiator.getInstantiator();
/**
* Create a lazy init proxy for the specified type. The target object will be located using the
* provided locator upon first method invocation.
*
* @param type
* type that proxy will represent
*
* @param locator
* object locator that will locate the object the proxy represents
*
* @return lazily initializable proxy
*/
@Override
public <T> T createProxy(final Class<T> type, final IProxyTargetLocator locator)
{
Class<T> proxyClass = createOrGetProxyClass(type);
T instance;
if (!hasNoArgConstructor(type))
{
instance = INSTANTIATOR.newInstance(proxyClass);
}
else
{
try
{
instance = proxyClass.getDeclaredConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e)
{
throw new WicketRuntimeException(e);
}
}
ByteBuddyInterceptor interceptor = new ByteBuddyInterceptor(type, locator);
((InterceptorMutator) instance).setInterceptor(interceptor);
return instance;
}
@SuppressWarnings("unchecked")
public static <T> Class<T> createOrGetProxyClass(Class<T> type)
{
ClassLoader classLoader = resolveClassLoader();
return (Class<T>) DYNAMIC_CLASS_CACHE.findOrInsert(classLoader,
new TypeCache.SimpleKey(type),
() -> BYTE_BUDDY
.subclass(type)
.method(ElementMatchers.isPublic())
.intercept(
MethodDelegation
.withDefaultConfiguration()
.withBinders(Pipe.Binder.install(Function.class))
.toField(INTERCEPTOR_FIELD_NAME))
.defineField(INTERCEPTOR_FIELD_NAME, ByteBuddyInterceptor.class, Visibility.PRIVATE)
.implement(InterceptorMutator.class).intercept(FieldAccessor.ofBeanProperty())
.implement(Serializable.class, IWriteReplace.class, ILazyInitProxy.class).intercept(MethodDelegation.toField(INTERCEPTOR_FIELD_NAME))
.make()
.load(classLoader, ClassLoadingStrategy.Default.INJECTION)
.getLoaded());
}
private static ClassLoader resolveClassLoader()
{
ClassLoader classLoader = null;
if (Application.exists())
{
classLoader = Application.get().getApplicationSettings()
.getClassResolver().getClassLoader();
}
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
return classLoader;
}
/**
* An interface used to set the Byte Buddy interceptor after creating an
* instance of the dynamically created proxy class.
* We need to set the interceptor as a field in the proxy class so that
* we could use different interceptors for proxied classes with generics.
* For example: a {@link org.apache.wicket.Component} may need to inject
* two beans with the same raw type but different generic type(s) (<em>
* ArrayList<String></em> and <em>ArrayList<Integer></em>).
* Since the generic types are erased at runtime, and we use caching for the
* dynamic proxy classes we need to be able to set different interceptors
* after instantiating the proxy class.
*/
public interface InterceptorMutator
{
void setInterceptor(ByteBuddyInterceptor interceptor);
}
/**
* A strategy that decides what should be the fully qualified name of the generated
* classes. Since it is not possible to create new classes in the <em>java.**</em>
* package we modify the package name by prefixing it with <em>bytebuddy_generated_wicket_proxy.</em>.
* For classes in any other packages we modify just the class name by prefixing
* it with <em>WicketProxy_</em>. This way the generated proxy class could still
* access package-private members of sibling classes.
*/
private static final class WicketNamingStrategy extends NamingStrategy.AbstractBase
{
public static final WicketNamingStrategy INSTANCE = new WicketNamingStrategy();
private WicketNamingStrategy()
{
super();
}
@Override
protected String name(TypeDescription superClass) {
String prefix = superClass.getName();
int lastIdxOfDot = prefix.lastIndexOf('.');
String packageName = prefix.substring(0, lastIdxOfDot);
String className = prefix.substring(lastIdxOfDot + 1);
String name = packageName + ".";
if (prefix.startsWith("java."))
{
name = "bytebuddy_generated_wicket_proxy." + name + className;
}
else
{
name += "WicketProxy_" + className;
}
return name;
}
@Override
public String redefine(TypeDescription typeDescription) {
return typeDescription.getName();
}
@Override
public String rebase(TypeDescription typeDescription) {
return typeDescription.getName();
}
}
private static boolean hasNoArgConstructor(Class<?> type)
{
for (Constructor<?> constructor : type.getDeclaredConstructors())
{
if (constructor.getParameterTypes().length == 0)
return true;
}
return false;
}
}
| 34.514019 | 139 | 0.752234 |
32b8a226c7f7a9f6d0f8ae488851a47032776b7e | 9,632 | package com.tencent.cos.xml;
import android.net.Uri;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* <p>
* </p>
* Created by wjielai on 2018/11/21.
* Copyright 2010-2017 Tencent Cloud. All Rights Reserved.
*/
@RunWith(AndroidJUnit4.class)
public class CosXmlConfigTest {
@Test
public void testIpPortHost() {
CosXmlServiceConfig config = new CosXmlServiceConfig.Builder()
.setHost(Uri.parse("https://127.0.0.1:8080"))
.builder();
Assert.assertEquals(config.getRequestHost("", false),
"127.0.0.1");
Assert.assertEquals(config.getPort(),
8080);
config = new CosXmlServiceConfig.Builder()
.setHost(Uri.parse("https://127.0.0.1"))
.builder();
Assert.assertEquals(config.getRequestHost("", false),
"127.0.0.1");
}
@Test
public void testCSPHostCompat() {
CosXmlServiceConfig config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.builder();
String host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion(null, "region")
.setBucketInPath(false)
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("bucket.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion(null, "region")
.setBucketInPath(false)
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setEndpointSuffix("cos.region.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("bucket-1250000000.cos.region.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(true)
.setEndpointSuffix("cos.region.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("cos.region.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(true)
.setEndpointSuffix("cos.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("cos.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setEndpointSuffix("cos.${region}.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",true);
Assert.assertEquals("bucket-1250000000.cos.accelerate.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "ap-guangzhou")
.setBucketInPath(false)
.setEndpointSuffix("cos.${region}.myqcloud.com")
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.ap-guangzhou.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "ap-guangzhou")
.builder();
Assert.assertEquals("cos.accelerate.myqcloud.com",
config.getEndpointSuffix(config.getRegion(),true));
}
@Test
public void testCSPHost() {
CosXmlServiceConfig config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.builder();
String host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion(null, "region")
.setBucketInPath(false)
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion(null, "region")
.setBucketInPath(false)
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
// .setEndpointSuffix("cos.region.yun.tce.com")
.setHostFormat("${bucket}.cos.region.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("bucket-1250000000.cos.region.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(true)
//.setEndpointSuffix("cos.region.yun.tce.com")
.setHostFormat("cos.region.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("cos.region.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(true)
//.setEndpointSuffix("cos.yun.tce.com")
.setHostFormat("cos.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",false);
Assert.assertEquals("cos.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
//.setEndpointSuffix("cos.${region}.yun.tce.com")
.setHostFormat("${bucket}.cos.accelerate.yun.tce.com")
.builder();
host = config.getRequestHost("bucket",true);
Assert.assertEquals("bucket-1250000000.cos.accelerate.yun.tce.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "ap-guangzhou")
.setBucketInPath(false)
//.setEndpointSuffix("cos.${region}.myqcloud.com")
.setHostFormat("${bucket}.cos.${region}.myqcloud.com")
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.ap-guangzhou.myqcloud.com", host);
// config = new CosXmlServiceConfig.Builder()
// .setAppidAndRegion("1250000000", "ap-guangzhou")
// .builder();
// Assert.assertEquals("cos.accelerate.myqcloud.com",
// config.getEndpointSuffix(config.getRegion(),true));
}
@Test public void testAccelerateHost() {
CosXmlServiceConfig config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setAccelerate(true)
.builder();
String host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.accelerate.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(true)
.setAccelerate(true)
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.accelerate.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setAccelerate(false)
.builder();
host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.cos.region.myqcloud.com", host);
config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setAccelerate(false)
.builder();
host = config.getRequestHost("bucket-1250000000",true);
Assert.assertEquals("bucket-1250000000.cos.accelerate.myqcloud.com", host);
}
@Test public void testCustomFormatHost() {
CosXmlServiceConfig config = new CosXmlServiceConfig.Builder()
.setAppidAndRegion("1250000000", "region")
.setBucketInPath(false)
.setAccelerate(true)
.setHostFormat("${bucket}.${region}.tencent.com")
.builder();
String host = config.getRequestHost("bucket-1250000000",false);
Assert.assertEquals("bucket-1250000000.region.tencent.com", host);
}
}
| 42.245614 | 85 | 0.59728 |
9df77f4f886a41fdf096e9a218efff8d86f92e78 | 479 | package com.appleframework.data.hbase.hql.node.unary;
import org.w3c.dom.Node;
import com.appleframework.data.hbase.hql.node.PrependNodeHandler;
import com.appleframework.data.hbase.util.XmlUtil;
/**
* @author xinzhi
*/
abstract public class UnaryNodeHandler extends PrependNodeHandler {
public void handle(UnaryNode unaryNode, Node node) {
unaryNode.setProperty(XmlUtil.getAttr(node, "property"));
super.handle(unaryNode, node);
}
}
| 28.176471 | 68 | 0.726514 |
6d7ae74297e60c07ceaf32e8419c87db593310ab | 3,077 | public class ExecuteVM {
public static final int CODESIZE = 10000;
public static final int MEMSIZE = 10000;
private int[] code;
private int[] memory = new int[MEMSIZE];
private int ip = 0;
private int sp = MEMSIZE;
private int hp = 0;
private int fp = MEMSIZE;
private int ra;
private int rv;
public ExecuteVM(int[] code) {
this.code = code;
}
public void cpu() {
while ( true ) {
int bytecode = code[ip++]; // fetch
int v1,v2;
int address;
switch ( bytecode ) {
case SVMParser.PUSH:
push( code[ip++] );
break;
case SVMParser.POP:
pop();
break;
case SVMParser.ADD :
v1=pop();
v2=pop();
push(v2 + v1);
break;
case SVMParser.MULT :
v1=pop();
v2=pop();
push(v2 * v1);
break;
case SVMParser.DIV :
v1=pop();
v2=pop();
push(v2 / v1);
break;
case SVMParser.SUB :
v1=pop();
v2=pop();
push(v2 - v1);
break;
case SVMParser.STOREW : //
address = pop();
memory[address] = pop();
break;
case SVMParser.LOADW : //
push(memory[pop()]);
break;
case SVMParser.BRANCH :
address = code[ip];
ip = address;
break;
case SVMParser.BRANCHEQ : //
address = code[ip++];
v1=pop();
v2=pop();
if (v2 == v1) ip = address;
break;
case SVMParser.BRANCHLESSEQ :
address = code[ip++];
v1=pop();
v2=pop();
if (v2 <= v1) ip = address;
break;
case SVMParser.JS : //
address = pop();
ra = ip;
ip = address;
break;
case SVMParser.STORERA : //
ra=pop();
break;
case SVMParser.LOADRA : //
push(ra);
break;
case SVMParser.STORERV : //
rv=pop();
break;
case SVMParser.LOADRV : //
push(rv);
break;
case SVMParser.LOADFP : //
push(fp);
break;
case SVMParser.STOREFP : //
fp=pop();
break;
case SVMParser.COPYFP : //
fp=sp;
break;
case SVMParser.STOREHP : //
hp=pop();
break;
case SVMParser.LOADHP : //
push(hp);
break;
case SVMParser.PRINT :
System.out.println((sp<MEMSIZE)?memory[sp]:"Empty stack!");
break;
case SVMParser.HALT :
return;
}
}
}
private int pop() {
return memory[sp++];
}
private void push(int v) {
memory[--sp] = v;
}
} | 24.616 | 71 | 0.408515 |
e4570b7810583bc2ce9142be1031d081b68293d9 | 1,060 | package com.lesserhydra.secondchance;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.jetbrains.annotations.Nullable;
public class Util {
@Nullable
public static Location entityLocationIsSafe(Entity entity) {
//Use vehicle location, if exists
Entity vehicle = entity.getVehicle();
if (vehicle != null) return entityLocationIsSafe(vehicle);
//Must be on the ground
if (!entity.isOnGround()) return null;
//Feet block must be nonsolid and nonliquid
Block feetBlock = entity.getLocation().getBlock();
if (feetBlock.getType().isOccluding() || feetBlock.isLiquid()) return null;
//Head block must be nonsolid and nonliquid
Block headBlock = feetBlock.getRelative(BlockFace.UP);
if (headBlock.getType().isOccluding() || headBlock.isLiquid()) return null;
//Ground block must be solid
Block groundBlock = feetBlock.getRelative(BlockFace.DOWN);
if (!groundBlock.getType().isSolid()) return null;
return entity.getLocation();
}
}
| 30.285714 | 77 | 0.74717 |
45d26ced06cd915eb6659a25650f9227634d560b | 3,642 | package org.smslib.camel;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spi.UriEndpoint;
import org.smslib.Service;
import org.smslib.gateway.AbstractGateway;
/**
* Represents a SMSLib endpoint.
* The endpoint does not contain any logic but defines all the existing header IDs.
* @author derjust
*/
@ManagedResource(description = "Managed SMSLibEndpoint")
@UriEndpoint(scheme = "smslib", consumerClass = SMSLibConsumer.class)
public abstract class SMSLibEndpoint extends DefaultEndpoint {
/** Header ID of the body type itself (Text, binary)
* @see org.smslib.message.Payload.Type */
public static final String HEADER_BODY_TYPE = "BodyType";
/** Header ID defining the source port of the SMS */
public static final String HEADER_SOURCE_PORT = "SourcePort";
/** Header ID defining the signature */
public static final String HEADER_SIGNATURE = "Signature";
/** Header ID defining the sent date of the message */
public static final String HEADER_SENT_DATE = "SentDate";
/** Header ID defining the recipient number of the message */
public static final String HEADER_RECIPIENT_NUMBER = "RecipientNumber";
/** Header ID defining the lexical representation of the recipient */
public static final String HEADER_RECIPIENT = "Recipient";
/** Header ID defining the originator number of the message */
public static final String HEADER_ORIGINATOR_NUMBER = "OriginatorNumber";
/** Header ID defining the lexical representation of the originator */
public static final String HEADER_ORIGINATOR = "Originator";
/** Header ID of the operator message ID of each message */
public static final String HEADER_OPERATOR_MESSAGE_ID = "OperatorMessageId";
/** Header ID of the technical ID of each message */
public static final String HEADER_ID = "Id";
/** Header ID defining the gateway id */
public static final String HEADER_GATEWAY_ID = "GatewayId";
/** Header ID defining message's encoding
* @see org.smslib.message.AbstractMessage.Encoding */
public static final String HEADER_ENCODING = "Encoding";
/** Header ID defining the destination port of the SMS */
public static final String HEADER_DESTINATION_PORT = "DestinationPort";
/** Header ID defining the type of the message itself (Inbound, Outbound, StatusReport)
* @see org.smslib.message.AbstractMessage.Type */
public static final String HEADER_TYPE = "Type";
private Service service = Service.getInstance();
public SMSLibEndpoint(String uri, SMSLibComponent component) {
super(uri, component);
}
public SMSLibEndpoint(String endpointUri) {
super(endpointUri);
}
public Producer createProducer() throws Exception {
return new SMSLibProducer(this, getGateway());
}
public Consumer createConsumer(Processor processor) throws Exception {
return new SMSLibConsumer(this, processor, getGateway());
}
protected abstract AbstractGateway getGateway();
public boolean isSingleton() {
return true;
}
protected Service getService() {
return service;
}
@Override
protected void doSuspend() throws Exception {
super.doSuspend();
}
@Override
protected void doResume() throws Exception {
super.doResume();
}
@Override
protected void doStart() throws Exception {
super.doStart();
service.start();
}
@Override
protected void doStop() throws Exception {
super.doStop();
service.stop();
}
}
| 35.705882 | 89 | 0.733114 |
4467a33f763eb3d4a5614731b97e88a9dde21252 | 4,831 | /*
* The MIT License
*
* Copyright: Copyright (C) 2014 T2Ti.COM
*
* 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.
*
* The author may be contacted at: [email protected]
*
* @author Claudio de Barros (T2Ti.com)
* @version 2.0
*/
package com.t2tierp.patrimonio.cliente;
import com.t2tierp.ged.java.ArquivoVO;
import com.t2tierp.padrao.java.Constantes;
import com.t2tierp.patrimonio.java.PatrimApoliceSeguroVO;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import org.openswing.swing.form.client.FormController;
import org.openswing.swing.mdi.client.MDIFrame;
import org.openswing.swing.message.receive.java.Response;
import org.openswing.swing.message.receive.java.ValueObject;
import org.openswing.swing.util.client.ClientUtils;
import org.openswing.swing.util.java.Consts;
public class PatrimApoliceSeguroDetalheController extends FormController {
private PatrimApoliceSeguroDetalhe patrimApoliceSeguroDetalhe = null;
private String pk = null;
private PatrimApoliceSeguroGrid patrimApoliceSeguroGrid = null;
private String acaoServidor;
public PatrimApoliceSeguroDetalheController(PatrimApoliceSeguroGrid patrimApoliceSeguroGrid, String pk) {
this.patrimApoliceSeguroGrid = patrimApoliceSeguroGrid;
this.pk = pk;
this.acaoServidor = "patrimApoliceSeguroDetalheAction";
patrimApoliceSeguroDetalhe = new PatrimApoliceSeguroDetalhe(this);
patrimApoliceSeguroDetalhe.setParentFrame(this.patrimApoliceSeguroGrid);
this.patrimApoliceSeguroGrid.pushFrame(patrimApoliceSeguroDetalhe);
MDIFrame.add(patrimApoliceSeguroDetalhe);
if (pk != null) {
patrimApoliceSeguroDetalhe.getForm1().setMode(Consts.READONLY);
patrimApoliceSeguroDetalhe.getForm1().reload();
} else {
patrimApoliceSeguroDetalhe.getForm1().setMode(Consts.INSERT);
}
}
@Override
public Response loadData(Class valueObjectClass) {
return ClientUtils.getData(acaoServidor, new Object[]{Constantes.LOAD, pk});
}
@Override
public Response insertRecord(ValueObject newPersistentObject) throws Exception {
return ClientUtils.getData(acaoServidor, new Object[]{Constantes.INSERT, newPersistentObject});
}
@Override
public void afterInsertData() {
patrimApoliceSeguroGrid.getGrid1().reloadData();
JOptionPane.showMessageDialog(patrimApoliceSeguroDetalhe, "Dados salvos com sucesso!", "Informacao do Sistema", JOptionPane.INFORMATION_MESSAGE);
}
@Override
public Response updateRecord(ValueObject oldPersistentObject, ValueObject persistentObject) throws Exception {
return ClientUtils.getData(acaoServidor, new Object[]{Constantes.UPDATE, oldPersistentObject, persistentObject});
}
@Override
public void afterEditData() {
patrimApoliceSeguroGrid.getGrid1().reloadData();
JOptionPane.showMessageDialog(patrimApoliceSeguroDetalhe, "Dados alterados com sucesso!", "Informacao do Sistema", JOptionPane.INFORMATION_MESSAGE);
}
public void acionaGed() throws ClassNotFoundException, Exception {
if (patrimApoliceSeguroDetalhe.getForm1().push()) {
PatrimApoliceSeguroVO apolice = (PatrimApoliceSeguroVO) patrimApoliceSeguroDetalhe.getForm1().getVOModel().getValueObject();
Object classe = Class.forName("com.t2tierp.ged.cliente.GedDocumentoGridController").newInstance();
Method metodo = classe.getClass().getDeclaredMethod("integracaoModulosErp", String.class, ArquivoVO.class);
String nomeDocumentoGed = "PATRIMONIO_APOLICE_" + apolice.getNumero();
apolice.setImagem(nomeDocumentoGed);
ArquivoVO arquivo = new ArquivoVO();
metodo.invoke(classe, nomeDocumentoGed, arquivo);
}
}
}
| 43.918182 | 156 | 0.753674 |
bfe0abb95b3a013ccf495ee5944d5e6e26a60ad3 | 963 | package com.example.catalogservice.entity;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.ColumnDefault;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public class Catalog implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 120, unique = true)
private String productId;
@Column(nullable = false)
private String productName;
@Column(nullable = false)
private Integer stock;
@Column(nullable = false)
private Integer unitPrice;
@Column(nullable = false, updatable = false, insertable = false)
@ColumnDefault(value = "CURRENT_TIMESTAMP")
private LocalDateTime createdAt;
public void minusStock(Integer qty) {
this.stock -= qty;
}
}
| 26.75 | 68 | 0.740395 |
bd036d9f1c304ed2df90502ed916c970d0c0a873 | 4,035 | /*
* Copyright 2021 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.google.android.exoplayer2.source.rtsp;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.source.rtsp.RtspMessageChannel.InterleavedBinaryDataListener;
import com.google.android.exoplayer2.upstream.BaseDataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.util.Util;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;
/** An {@link RtpDataChannel} that transfers received data in-memory. */
/* package */ final class TransferRtpDataChannel extends BaseDataSource
implements RtpDataChannel, RtspMessageChannel.InterleavedBinaryDataListener {
private static final String DEFAULT_TCP_TRANSPORT_FORMAT =
"RTP/AVP/TCP;unicast;interleaved=%d-%d";
private final LinkedBlockingQueue<byte[]> packetQueue;
private final long pollTimeoutMs;
private byte[] unreadData;
private int channelNumber;
/**
* Creates a new instance.
*
* @param pollTimeoutMs The number of milliseconds which {@link #read} waits for a packet to be
* available. After the time has expired, {@link C#RESULT_END_OF_INPUT} is returned.
*/
public TransferRtpDataChannel(long pollTimeoutMs) {
super(/* isNetwork= */ true);
this.pollTimeoutMs = pollTimeoutMs;
packetQueue = new LinkedBlockingQueue<>();
unreadData = new byte[0];
channelNumber = C.INDEX_UNSET;
}
@Override
public String getTransport() {
checkState(channelNumber != C.INDEX_UNSET); // Assert open() is called.
return Util.formatInvariant(DEFAULT_TCP_TRANSPORT_FORMAT, channelNumber, channelNumber + 1);
}
@Override
public int getLocalPort() {
return channelNumber;
}
@Override
public InterleavedBinaryDataListener getInterleavedBinaryDataListener() {
return this;
}
@Override
public long open(DataSpec dataSpec) {
this.channelNumber = dataSpec.uri.getPort();
return C.LENGTH_UNSET;
}
@Override
public void close() {}
@Nullable
@Override
public Uri getUri() {
return null;
}
@Override
public int read(byte[] target, int offset, int length) {
if (length == 0) {
return 0;
}
int bytesRead = 0;
int bytesToRead = min(length, unreadData.length);
System.arraycopy(unreadData, /* srcPos= */ 0, target, offset, bytesToRead);
bytesRead += bytesToRead;
unreadData = Arrays.copyOfRange(unreadData, bytesToRead, unreadData.length);
if (bytesRead == length) {
return bytesRead;
}
@Nullable byte[] data;
try {
data = packetQueue.poll(pollTimeoutMs, MILLISECONDS);
if (data == null) {
return C.RESULT_END_OF_INPUT;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return C.RESULT_END_OF_INPUT;
}
bytesToRead = min(length - bytesRead, data.length);
System.arraycopy(data, /* srcPos= */ 0, target, offset + bytesRead, bytesToRead);
if (bytesToRead < data.length) {
unreadData = Arrays.copyOfRange(data, bytesToRead, data.length);
}
return bytesRead + bytesToRead;
}
@Override
public void onInterleavedBinaryDataReceived(byte[] data) {
packetQueue.add(data);
}
}
| 31.038462 | 98 | 0.723668 |
801e0e99a80636562e910f99780aec3f055ff209 | 2,008 | /* Copyright Airship and Contributors */
package com.urbanairship.iam.custom;
import com.urbanairship.iam.DisplayContent;
import com.urbanairship.json.JsonException;
import com.urbanairship.json.JsonMap;
import com.urbanairship.json.JsonValue;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Display content for a {@link com.urbanairship.iam.InAppMessage#TYPE_CUSTOM} in-app message.
*/
public class CustomDisplayContent implements DisplayContent {
private static final String CUSTOM_KEY = "custom";
private final JsonValue value;
/**
* Default constructor.
*
* @param value The json payload.
*/
public CustomDisplayContent(@NonNull JsonValue value) {
this.value = value;
}
@NonNull
@Override
public JsonValue toJsonValue() {
return JsonMap.newBuilder()
.put(CUSTOM_KEY, value)
.build()
.toJsonValue();
}
/**
* Parses a json value.
*
* @param value The json value.
* @return A custom display content instance.
*/
@NonNull
public static CustomDisplayContent fromJson(@NonNull JsonValue value) throws JsonException {
if (!value.isJsonMap()) {
throw new JsonException("Invalid custom display content: " + value);
}
return new CustomDisplayContent(value.optMap().opt(CUSTOM_KEY));
}
/**
* Gets the custom value.
*
* @return The custom value.
*/
@NonNull
public JsonValue getValue() {
return value;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CustomDisplayContent that = (CustomDisplayContent) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 23.904762 | 96 | 0.614542 |
62122afc665803a1812ceedaa2b5bac49fa3ac13 | 4,270 | package org.elasticsearch.hadoop.serialization.dto.mapping;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.elasticsearch.hadoop.EsHadoopIllegalArgumentException;
import org.elasticsearch.hadoop.serialization.FieldType;
/**
* All logic pertaining to parsing Elasticsearch schemas and rendering Mapping and Field objects.
*/
public final class FieldParser {
private FieldParser() {
// No instances allowed
}
/**
* Convert the deserialized mapping request body into an object
* @param content entire mapping request body for all indices and types
* @return MappingSet for that response.
*/
public static MappingSet parseMapping(Map<String, Object> content) {
Iterator<Map.Entry<String, Object>> iterator = content.entrySet().iterator();
List<Field> fields = new ArrayList<Field>();
while(iterator.hasNext()) {
Field field = parseField(iterator.next(), null);
fields.add(field);
}
return new MappingSet(fields);
}
private static Field skipHeaders(Field field) {
Field[] props = field.properties();
// handle the common case of mapping by removing the first field (mapping.)
if (props.length > 0 && props[0] != null && "mappings".equals(props[0].name()) && FieldType.OBJECT.equals(props[0].type())) {
// can't return the type as it is an object of properties
return props[0].properties()[0];
}
return field;
}
private static Field parseField(Map.Entry<String, Object> entry, String previousKey) {
// can be "type" or field name
String key = entry.getKey();
Object value = entry.getValue();
// nested object
if (value instanceof Map) {
Map<String, Object> content = (Map<String, Object>) value;
// default field type for a map
FieldType fieldType = FieldType.OBJECT;
// see whether the field was declared
Object type = content.get("type");
if (type instanceof String) {
fieldType = FieldType.parse(type.toString());
if (FieldType.isRelevant(fieldType)) {
// primitive types are handled on the spot
// while compound ones are not
if (!FieldType.isCompound(fieldType)) {
return new Field(key, fieldType);
}
}
else {
return null;
}
}
// check if it's a join field since these are special
if (FieldType.JOIN == fieldType) {
return new Field(key, fieldType, new Field[]{new Field("name", FieldType.KEYWORD), new Field("parent", FieldType.KEYWORD)});
}
// compound type - iterate through types
List<Field> fields = new ArrayList<Field>(content.size());
for (Map.Entry<String, Object> e : content.entrySet()) {
if (e.getValue() instanceof Map) {
Field fl = parseField(e, key);
if (fl != null && fl.type() == FieldType.OBJECT && "properties".equals(fl.name()) && !isFieldNamedProperties(e.getValue())) {
// use the enclosing field (as it might be nested)
return new Field(key, fieldType, fl.properties());
}
if (fl != null) {
fields.add(fl);
}
}
}
return new Field(key, fieldType, fields);
}
throw new EsHadoopIllegalArgumentException("invalid map received " + entry);
}
private static boolean isFieldNamedProperties(Object fieldValue){
if(fieldValue instanceof Map){
Map<String,Object> fieldValueAsMap = ((Map<String, Object>)fieldValue);
if((fieldValueAsMap.containsKey("type") && fieldValueAsMap.get("type") instanceof String)
|| (fieldValueAsMap.containsKey("properties") && !isFieldNamedProperties(fieldValueAsMap.get("properties")))) return true;
}
return false;
}
}
| 38.818182 | 145 | 0.579859 |
56192894d56eb8baa7e4cae2bb0146dd2ae140e5 | 439 | package com.wixsite.vilsurmurtazin.cfg.repository;
import com.wixsite.vilsurmurtazin.cfg.repository.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* {@link Repository} for {@link Post} entity.
*/
@Repository
public interface PostRepository extends JpaRepository<Post, Integer> {
Optional<Post> findByHref(String href);
}
| 27.4375 | 70 | 0.797267 |
cc18499af18f22576b5a7c419c8fde65bfd899a1 | 3,921 | /**
* Copyright (C) 2011 Brian Ferris <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onebusaway.gtfs.model.calendar;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.onebusaway.gtfs.model.AgencyAndId;
public class CalendarServiceData implements Serializable {
private static final long serialVersionUID = 1L;
private Map<String, TimeZone> _timeZonesByAgencyId = new HashMap<String, TimeZone>();
private Map<AgencyAndId, List<ServiceDate>> _serviceDatesByServiceId = new HashMap<AgencyAndId, List<ServiceDate>>();
private Map<LocalizedServiceId, List<Date>> _datesByLocalizedServiceId = new HashMap<LocalizedServiceId, List<Date>>();
private Map<ServiceDate, Set<AgencyAndId>> _serviceIdsByDate = new HashMap<ServiceDate, Set<AgencyAndId>>();
/**
* @param agencyId
* @return the time zone for the specified agencyId, or null if the agency was
* not found
*/
public TimeZone getTimeZoneForAgencyId(String agencyId) {
return _timeZonesByAgencyId.get(agencyId);
}
public void putTimeZoneForAgencyId(String agencyId, TimeZone timeZone) {
_timeZonesByAgencyId.put(agencyId, timeZone);
}
public Set<AgencyAndId> getServiceIds() {
return Collections.unmodifiableSet(_serviceDatesByServiceId.keySet());
}
public Set<LocalizedServiceId> getLocalizedServiceIds() {
return Collections.unmodifiableSet(_datesByLocalizedServiceId.keySet());
}
public List<ServiceDate> getServiceDatesForServiceId(AgencyAndId serviceId) {
return _serviceDatesByServiceId.get(serviceId);
}
public Set<AgencyAndId> getServiceIdsForDate(ServiceDate date) {
Set<AgencyAndId> serviceIds = _serviceIdsByDate.get(date);
if (serviceIds == null)
serviceIds = new HashSet<AgencyAndId>();
return serviceIds;
}
public void putServiceDatesForServiceId(AgencyAndId serviceId,
List<ServiceDate> serviceDates) {
serviceDates = new ArrayList<ServiceDate>(serviceDates);
Collections.sort(serviceDates);
serviceDates = Collections.unmodifiableList(serviceDates);
_serviceDatesByServiceId.put(serviceId, serviceDates);
for (ServiceDate serviceDate : serviceDates) {
Set<AgencyAndId> serviceIds = _serviceIdsByDate.get(serviceDate);
if (serviceIds == null) {
serviceIds = new HashSet<AgencyAndId>();
_serviceIdsByDate.put(serviceDate, serviceIds);
}
serviceIds.add(serviceId);
}
}
public List<Date> getDatesForLocalizedServiceId(LocalizedServiceId serviceId) {
return _datesByLocalizedServiceId.get(serviceId);
}
public void putDatesForLocalizedServiceId(LocalizedServiceId serviceId,
List<Date> dates) {
dates = Collections.unmodifiableList(new ArrayList<Date>(dates));
_datesByLocalizedServiceId.put(serviceId, dates);
}
public void makeReadOnly() {
_timeZonesByAgencyId = Collections.unmodifiableMap(_timeZonesByAgencyId);
_serviceDatesByServiceId = Collections.unmodifiableMap(_serviceDatesByServiceId);
_datesByLocalizedServiceId = Collections.unmodifiableMap(_datesByLocalizedServiceId);
_serviceIdsByDate = Collections.unmodifiableMap(_serviceIdsByDate);
}
}
| 36.305556 | 121 | 0.76154 |
c64cfad8af340f7e735784a707bf4ecdf3cb10ad | 2,577 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.transpiler.passes;
import com.google.j2cl.transpiler.ast.AbstractRewriter;
import com.google.j2cl.transpiler.ast.CompilationUnit;
import com.google.j2cl.transpiler.ast.Expression;
import com.google.j2cl.transpiler.ast.NumberLiteral;
import com.google.j2cl.transpiler.ast.RuntimeMethods;
import com.google.j2cl.transpiler.ast.StringLiteral;
import com.google.j2cl.transpiler.ast.TypeDescriptors;
/** Replaces literals that are required to be emulated. */
public class NormalizeLiterals extends NormalizationPass {
@Override
public void applyTo(CompilationUnit compilationUnit) {
compilationUnit.accept(
new AbstractRewriter() {
@Override
public Expression rewriteNumberLiteral(NumberLiteral numberLiteral) {
if (TypeDescriptors.isPrimitiveLong(numberLiteral.getTypeDescriptor())) {
long longValue = numberLiteral.getValue().longValue();
int intValue = numberLiteral.getValue().intValue();
if (longValue == intValue) {
return RuntimeMethods.createNativeLongMethodCall(
"fromInt", NumberLiteral.fromInt(intValue));
} else {
long lowOrderBits = longValue << 32 >> 32;
long highOrderBits = longValue >> 32;
return RuntimeMethods.createNativeLongMethodCall(
"fromBits",
NumberLiteral.fromInt((int) lowOrderBits),
NumberLiteral.fromInt((int) highOrderBits))
.withComment(String.valueOf(longValue));
}
} else if (TypeDescriptors.isPrimitiveChar(numberLiteral.getTypeDescriptor())) {
return numberLiteral.withComment(
new StringLiteral("" + ((char) numberLiteral.getValue().intValue()))
.getSourceText());
} else {
return numberLiteral;
}
}
});
}
}
| 41.564516 | 92 | 0.659294 |
6c56a97e00524ed74118d12be316dc81376e2f6b | 6,975 | /**
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, [email protected]
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.xm.similarity.text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xm.tokenizer.Word;
import java.math.BigInteger;
import java.util.List;
/**
* 文本相似度计算
* 判定方式:SimHash + 汉明距离(Hamming Distance)
* 先使用SimHash把不同长度的文本映射为等长文本,然后再计算等长文本的汉明距离
* <p>
* simhash和普通hash最大的不同在于:
* 普通hash对 仅有一个字节不同的文本 会映射成 两个完全不同的哈希结果
* simhash对 相似的文本 会映射成 相似的哈希结果
* <p>
* 汉明距离是以美国数学家Richard Wesley Hamming的名字命名的
* 两个等长字符串之间的汉明距离是两个字符串相应位置的不同字符的个数
* 换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数
* <p>
* 比如:
* 1011101 与 1001001 之间的汉明距离是 2
* 2143896 与 2233796 之间的汉明距离是 3
* toned 与 roses 之间的汉明距离是 3
*
* @author 杨尚川
*/
public class SimHashPlusHammingDistanceTextSimilarity extends TextSimilarity {
private static final Logger LOGGER = LoggerFactory.getLogger(SimHashPlusHammingDistanceTextSimilarity.class);
private int hashBitCount = 128;
public SimHashPlusHammingDistanceTextSimilarity() {
}
public SimHashPlusHammingDistanceTextSimilarity(int hashBitCount) {
this.hashBitCount = hashBitCount;
}
public int getHashBitCount() {
return hashBitCount;
}
public void setHashBitCount(int hashBitCount) {
this.hashBitCount = hashBitCount;
}
/**
* 计算相似度分值
*
* @param words1 词列表1
* @param words2 词列表2
* @return 相似度分值
*/
@Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
//用词频来标注词的权重
taggingWeightByFrequency(words1, words2);
//计算SimHash
String simHash1 = simHash(words1);
String simHash2 = simHash(words2);
//计算SimHash值之间的汉明距离
int hammingDistance = hammingDistance(simHash1, simHash2);
if (hammingDistance == -1) {
LOGGER.error("文本1:" + words1.toString());
LOGGER.error("文本2:" + words2.toString());
LOGGER.error("文本1SimHash值:" + simHash1);
LOGGER.error("文本2SimHash值:" + simHash2);
LOGGER.error("文本1和文本2的SimHash值长度不相等,不能计算汉明距离");
return 0.0;
}
int maxDistance = simHash1.length();
double score = (1 - hammingDistance / (double) maxDistance);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("文本1:" + words1.toString());
LOGGER.debug("文本2:" + words2.toString());
LOGGER.debug("文本1SimHash值:" + simHash1);
LOGGER.debug("文本2SimHash值:" + simHash2);
LOGGER.debug("hashBitCount:" + hashBitCount);
LOGGER.debug("SimHash值之间的汉明距离:" + hammingDistance);
LOGGER.debug("文本1和文本2的相似度分值:1 - " + hammingDistance + " / (double)" + maxDistance + "=" + score);
}
return score;
}
/**
* 计算词列表的SimHash值
*
* @param words 词列表
* @return SimHash值
*/
private String simHash(List<Word> words) {
float[] hashBit = new float[hashBitCount];
words.forEach(word -> {
float weight = word.getWeight() == null ? 1 : word.getWeight();
BigInteger hash = hash(word.getName());
for (int i = 0; i < hashBitCount; i++) {
BigInteger bitMask = new BigInteger("1").shiftLeft(i);
if (hash.and(bitMask).signum() != 0) {
hashBit[i] += weight;
} else {
hashBit[i] -= weight;
}
}
});
StringBuffer fingerprint = new StringBuffer();
for (int i = 0; i < hashBitCount; i++) {
if (hashBit[i] >= 0) {
fingerprint.append("1");
} else {
fingerprint.append("0");
}
}
return fingerprint.toString();
}
/**
* 计算词的哈希值
*
* @param word 词
* @return 哈希值
*/
private BigInteger hash(String word) {
if (word == null || word.length() == 0) {
return new BigInteger("0");
}
char[] charArray = word.toCharArray();
BigInteger x = BigInteger.valueOf(((long) charArray[0]) << 7);
BigInteger m = new BigInteger("1000003");
BigInteger mask = new BigInteger("2").pow(hashBitCount).subtract(new BigInteger("1"));
long sum = 0;
for (char c : charArray) {
sum += c;
}
x = x.multiply(m).xor(BigInteger.valueOf(sum)).and(mask);
x = x.xor(new BigInteger(String.valueOf(word.length())));
if (x.equals(new BigInteger("-1"))) {
x = new BigInteger("-2");
}
return x;
}
/**
* 计算等长的SimHash值的汉明距离
* 如不能比较距离(比较的两段文本长度不相等),则返回-1
*
* @param simHash1 SimHash值1
* @param simHash2 SimHash值2
* @return 汉明距离
*/
private int hammingDistance(String simHash1, String simHash2) {
if (simHash1.length() != simHash2.length()) {
return -1;
}
int distance = 0;
int len = simHash1.length();
for (int i = 0; i < len; i++) {
if (simHash1.charAt(i) != simHash2.charAt(i)) {
distance++;
}
}
return distance;
}
public static void main(String[] args) throws Exception {
String text1 = "我爱购物";
String text2 = "我爱读书";
String text3 = "他是黑客";
TextSimilarity textSimilarity = new SimHashPlusHammingDistanceTextSimilarity();
double score1pk1 = textSimilarity.getSimilarity(text1, text1);
double score1pk2 = textSimilarity.getSimilarity(text1, text2);
double score1pk3 = textSimilarity.getSimilarity(text1, text3);
double score2pk2 = textSimilarity.getSimilarity(text2, text2);
double score2pk3 = textSimilarity.getSimilarity(text2, text3);
double score3pk3 = textSimilarity.getSimilarity(text3, text3);
System.out.println(text1 + " 和 " + text1 + " 的相似度分值:" + score1pk1);
System.out.println(text1 + " 和 " + text2 + " 的相似度分值:" + score1pk2);
System.out.println(text1 + " 和 " + text3 + " 的相似度分值:" + score1pk3);
System.out.println(text2 + " 和 " + text2 + " 的相似度分值:" + score2pk2);
System.out.println(text2 + " 和 " + text3 + " 的相似度分值:" + score2pk3);
System.out.println(text3 + " 和 " + text3 + " 的相似度分值:" + score3pk3);
}
}
| 34.191176 | 113 | 0.60129 |
baad9961bbffbbef3c8792313898c05f15e6d34a | 1,147 | package com.ruoyi.project.school.mapper;
import java.util.List;
import com.ruoyi.project.school.domain.SysProduct;
/**
* 产品Mapper接口
*
* @author ruoyi
* @date 2020-07-17
*/
public interface SysProductMapper
{
/**
* 查询产品
*
* @param productId 产品ID
* @return 产品
*/
public SysProduct selectSysProductById(Long productId);
/**
* 查询产品列表
*
* @param sysProduct 产品
* @return 产品集合
*/
public List<SysProduct> selectSysProductList(SysProduct sysProduct);
/**
* 新增产品
*
* @param sysProduct 产品
* @return 结果
*/
public int insertSysProduct(SysProduct sysProduct);
/**
* 修改产品
*
* @param sysProduct 产品
* @return 结果
*/
public int updateSysProduct(SysProduct sysProduct);
/**
* 删除产品
*
* @param productId 产品ID
* @return 结果
*/
public int deleteSysProductById(Long productId);
/**
* 批量删除产品
*
* @param productIds 需要删除的数据ID
* @return 结果
*/
public int deleteSysProductByIds(Long[] productIds);
}
| 18.5 | 73 | 0.551874 |
435428917fd3bebccb00de0070d7ee53a5a60de3 | 1,530 | package com.nero.geektime.week11.controller;
import com.alibaba.druid.support.json.JSONUtils;
import com.nero.geektime.week11.config.RedisPool;
import com.nero.geektime.week11.entity.Response;
import com.nero.geektime.week11.model.Publisher;
import com.nero.geektime.week11.utils.SubThread;
import com.nero.geektime.week8.entity.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.JedisPool;
@Controller
public class OrderController {
@RequestMapping("/order/create")
public String createOrder(@RequestParam Order order) {
Response response = new Response();
response.setErrorCode(200);
response.setErrorMsg("ok");
if (null == order) {
response.setErrorCode(10000);
response.setErrorMsg("入参为空");
return JSONUtils.toJSONString(response);
}
String lockKey = order.getOrderNo().toString();
//分布式锁保证只会有一个处理成功
if (null == RedisPool.getJedis().get(lockKey)) {
RedisPool.getJedis().set(lockKey, JSONUtils.toJSONString(order), "nx", "ex", 5000);
//减库存
String productKey = "product:" + order.getProductId().toString() + ":num";
RedisPool.getJedis().decr(productKey);
}
return JSONUtils.toJSONString(response);
}
public void pubSub() {
JedisPool jedisPool = RedisPool.getJedisPool();
SubThread subThread = new SubThread(jedisPool);
subThread.start();
Publisher publisher = new Publisher(jedisPool);
publisher.start();
}
}
| 31.875 | 86 | 0.759477 |
8816e7d46bcb93e5a1a4e8452a4728dfa321877f | 3,598 | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.jcache;
import java.util.concurrent.Callable;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
import org.springframework.cache.support.AbstractValueAdaptingCache;
import org.springframework.util.Assert;
/**
* {@link org.springframework.cache.Cache} implementation on top of a
* {@link javax.cache.Cache} instance.
*
* <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
*
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 3.2
*/
public class JCacheCache extends AbstractValueAdaptingCache {
private final javax.cache.Cache<Object, Object> cache;
/**
* Create an {@link JCacheCache} instance.
* @param jcache backing JCache Cache instance
*/
public JCacheCache(javax.cache.Cache<Object, Object> jcache) {
this(jcache, true);
}
/**
* Create an {@link JCacheCache} instance.
* @param jcache backing JCache Cache instance
* @param allowNullValues whether to accept and convert null values for this cache
*/
public JCacheCache(javax.cache.Cache<Object, Object> jcache, boolean allowNullValues) {
super(allowNullValues);
Assert.notNull(jcache, "Cache must not be null");
this.cache = jcache;
}
@Override
public final String getName() {
return this.cache.getName();
}
@Override
public final javax.cache.Cache<Object, Object> getNativeCache() {
return this.cache;
}
@Override
protected Object lookup(Object key) {
return this.cache.get(key);
}
@Override
public <T> T get(Object key, Callable<T> valueLoader) {
try {
return this.cache.invoke(key, new ValueLoaderEntryProcessor<T>(), valueLoader);
}
catch (EntryProcessorException ex) {
throw new ValueRetrievalException(key, valueLoader, ex.getCause());
}
}
@Override
public void put(Object key, Object value) {
this.cache.put(key, toStoreValue(value));
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
boolean set = this.cache.putIfAbsent(key, toStoreValue(value));
return (set ? null : get(key));
}
@Override
public void evict(Object key) {
this.cache.remove(key);
}
@Override
public void clear() {
this.cache.removeAll();
}
private class ValueLoaderEntryProcessor<T> implements EntryProcessor<Object, Object, T> {
@SuppressWarnings("unchecked")
@Override
public T process(MutableEntry<Object, Object> entry, Object... arguments)
throws EntryProcessorException {
Callable<T> valueLoader = (Callable<T>) arguments[0];
if (entry.exists()) {
return (T) fromStoreValue(entry.getValue());
}
else {
T value;
try {
value = valueLoader.call();
}
catch (Exception ex) {
throw new EntryProcessorException("Value loader '" + valueLoader + "' failed " +
"to compute value for key '" + entry.getKey() + "'", ex);
}
entry.setValue(toStoreValue(value));
return value;
}
}
}
}
| 26.651852 | 90 | 0.716231 |
f80e9cf0dacb3aeefa5822e0986691eb0f0fa2b8 | 3,685 | /*
* 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.kylin.engine.spark.job;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.metadata.model.Segments;
import org.apache.spark.sql.Column;
import org.spark_project.guava.collect.Sets;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class NSparkCubingUtil {
static String ids2Str(Set<? extends Number> ids) {
return String.join(",", ids.stream().map(String::valueOf).collect(Collectors.toList()));
}
static Set<Long> str2Longs(String str) {
Set<Long> r = new LinkedHashSet<>();
for (String id : str.split(",")) {
r.add(Long.parseLong(id));
}
return r;
}
public static Column[] getColumns(Set<Integer> indices1, Set<Integer> indices2) {
Set<Integer> ret = new LinkedHashSet<>();
ret.addAll(indices1);
ret.addAll(indices2);
return getColumns(ret);
}
public static Column[] getColumns(Set<Integer> indices) {
Column[] ret = new Column[indices.size()];
int index = 0;
for (Integer i : indices) {
ret[index] = new Column(String.valueOf(i));
index++;
}
return ret;
}
public static Column[] getColumns(List<Integer> indices) {
Column[] ret = new Column[indices.size()];
int index = 0;
for (Integer i : indices) {
ret[index] = new Column(String.valueOf(i));
index++;
}
return ret;
}
private static final Pattern DOT_PATTERN = Pattern.compile("(\\S+)\\.(\\D+)");
public static final String SEPARATOR = "_0_DOT_0_";
public static String convertFromDot(String withDot) {
Matcher m = DOT_PATTERN.matcher(withDot);
String withoutDot = withDot;
while (m.find()) {
withoutDot = m.replaceAll("$1" + SEPARATOR + "$2");
m = DOT_PATTERN.matcher(withoutDot);
}
return withoutDot;
}
public static String getStoragePath(CubeSegment nDataSegment, Long layoutId) {
String hdfsWorkingDir = nDataSegment.getConfig().getReadHdfsWorkingDirectory();
return hdfsWorkingDir +
getStoragePathWithoutPrefix(nDataSegment.getProject(), nDataSegment.getCubeInstance().getId(), nDataSegment.getUuid(), layoutId);
}
static Set<String> toSegmentNames(Segments<CubeSegment> segments) {
Set<String> s = Sets.newLinkedHashSet();
s.addAll(segments.stream().map(CubeSegment::getName).collect(Collectors.toList()));
return s;
}
public static String getStoragePathWithoutPrefix(String project, String cubeId, String segmentId, long layoutId) {
return project + "/parquet/" + cubeId + "/" + segmentId + "/" + layoutId;
}
}
| 35.432692 | 145 | 0.661872 |
324720f39006bfae917277bb2b5bb0a9daf5d5d0 | 5,824 | /**
* 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.hadoop.hbase.util;
import static org.apache.hadoop.hbase.util.test.LoadTestDataGenerator.INCREMENT;
import static org.apache.hadoop.hbase.util.test.LoadTestDataGenerator.MUTATE_INFO;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Tag;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator;
/** Creates multiple threads that write key/values into the */
public class MultiThreadedWriter extends MultiThreadedWriterBase {
private static final Log LOG = LogFactory.getLog(MultiThreadedWriter.class);
private Set<HBaseWriterThread> writers = new HashSet<HBaseWriterThread>();
private boolean isMultiPut = false;
private Random random = new Random();
// TODO: Make this configurable
private int minTagLength = 16;
private int maxTagLength = 512;
public MultiThreadedWriter(LoadTestDataGenerator dataGen, Configuration conf,
TableName tableName) {
super(dataGen, conf, tableName, "W");
}
/** Use multi-puts vs. separate puts for every column in a row */
public void setMultiPut(boolean isMultiPut) {
this.isMultiPut = isMultiPut;
}
@Override
public void start(long startKey, long endKey, int numThreads, boolean useTags,
int minNumTags, int maxNumTags) throws IOException {
super.start(startKey, endKey, numThreads, useTags, minNumTags, maxNumTags);
if (verbose) {
LOG.debug("Inserting keys [" + startKey + ", " + endKey + ")");
}
for (int i = 0; i < numThreads; ++i) {
HBaseWriterThread writer = new HBaseWriterThread(i);
writers.add(writer);
}
startThreads(writers);
}
private class HBaseWriterThread extends Thread {
private final HTable table;
public HBaseWriterThread(int writerId) throws IOException {
setName(getClass().getSimpleName() + "_" + writerId);
table = new HTable(conf, tableName);
}
public void run() {
try {
long rowKeyBase;
byte[][] columnFamilies = dataGenerator.getColumnFamilies();
while ((rowKeyBase = nextKeyToWrite.getAndIncrement()) < endKey) {
byte[] rowKey = dataGenerator.getDeterministicUniqueKey(rowKeyBase);
Put put = new Put(rowKey);
numKeys.addAndGet(1);
int columnCount = 0;
for (byte[] cf : columnFamilies) {
byte[][] columns = dataGenerator.generateColumnsForCf(rowKey, cf);
int numTags;
if (minNumTags == maxNumTags) {
numTags = minNumTags;
} else {
numTags = minNumTags + random.nextInt(maxNumTags - minNumTags);
}
Tag[] tags = new Tag[numTags];
for (byte[] column : columns) {
byte[] value = dataGenerator.generateValue(rowKey, cf, column);
byte[] tag = LoadTestTool.generateData(random,
minTagLength + random.nextInt(maxTagLength - minTagLength));
if(useTags) {
for (int n = 0; n < numTags; n++) {
Tag t = new Tag((byte) n, tag);
tags[n] = t;
}
put.add(cf, column, value, tags);
} else {
put.add(cf, column, value);
}
++columnCount;
if (!isMultiPut) {
insert(table, put, rowKeyBase);
numCols.addAndGet(1);
put = new Put(rowKey);
}
}
long rowKeyHash = Arrays.hashCode(rowKey);
put.add(cf, MUTATE_INFO, HConstants.EMPTY_BYTE_ARRAY);
put.add(cf, INCREMENT, Bytes.toBytes(rowKeyHash));
if (!isMultiPut) {
insert(table, put, rowKeyBase);
numCols.addAndGet(1);
put = new Put(rowKey);
}
}
if (isMultiPut) {
if (verbose) {
LOG.debug("Preparing put for key = [" + rowKey + "], " + columnCount + " columns");
}
insert(table, put, rowKeyBase);
numCols.addAndGet(columnCount);
}
if (trackWroteKeys) {
wroteKeys.add(rowKeyBase);
}
}
} finally {
try {
table.close();
} catch (IOException e) {
LOG.error("Error closing table", e);
}
numThreadsWorking.decrementAndGet();
}
}
}
@Override
public void waitForFinish() {
super.waitForFinish();
System.out.println("Failed to write keys: " + failedKeySet.size());
for (Long key : failedKeySet) {
System.out.println("Failed to write key: " + key);
}
}
}
| 35.084337 | 97 | 0.628606 |
b3acd94ce66d899eb8a7b4a8c38f3761e29dd0a0 | 1,593 | package net.wisedragoon.bonk.procedures;
import net.wisedragoon.bonk.init.BonkModGameRules;
import net.minecraftforge.fmllegacy.server.ServerLifecycleHooks;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.ChatType;
import net.minecraft.Util;
public class CrashCommandExecutedProcedure {
public static void execute(LevelAccessor world, double x, double y, double z, Entity entity) {
if (entity == null)
return;
if (world.getLevelData().getGameRules().getBoolean(BonkModGameRules.BONKDEBUGCOMMANDS)) {
if (!world.isClientSide()) {
MinecraftServer mcserv = ServerLifecycleHooks.getCurrentServer();
if (mcserv != null)
mcserv.getPlayerList().broadcastMessage(
new TextComponent(
(entity.getDisplayName().getString() + " is gonna crash the server. Admins, log that name and ban him!")),
ChatType.SYSTEM, Util.NIL_UUID);
}
if (world instanceof Level _level && !_level.isClientSide())
_level.explode(null, x, y, z, 32767, Explosion.BlockInteraction.BREAK);
} else {
if (entity instanceof Player _player && !_player.level.isClientSide())
_player.displayClientMessage(new TextComponent("Bonk Gameplay Commands is disabled. Please enable them to use this command."),
(false));
}
}
}
| 40.846154 | 131 | 0.741368 |
269f18edbee1165eec7a345f49f5c3baf1af49d8 | 4,578 | /*
*
* 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.dromara.hodor.remoting.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.dromara.hodor.common.concurrent.HodorThreadFactory;
import org.dromara.hodor.common.utils.OSInfo;
import org.dromara.hodor.remoting.api.AbstractNetServer;
import org.dromara.hodor.remoting.api.Attribute;
import org.dromara.hodor.remoting.api.HodorChannel;
import org.dromara.hodor.remoting.api.HodorChannelHandler;
/**
* NettyServer starter.
*
* @author xiaoyu
*/
public class NettyServer extends AbstractNetServer {
private ServerBootstrap bootstrap;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private HodorChannel channel;
private NettyChannelHandler serverHandler;
private Class<? extends ServerSocketChannel> serverSocketChannelClass;
NettyServer(Attribute attribute, HodorChannelHandler handler) {
super(attribute, handler);
init();
}
@Override
public void bind() {
this.bootstrap.group(bossGroup, workerGroup)
.handler(new LoggingHandler(LogLevel.INFO))
.channel(serverSocketChannelClass)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024 * 1024, 16 * 1024 * 1024))
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childHandler(new NettyServerInitializer(serverHandler));
ChannelFuture future = bootstrap.bind(getHost(), getPort());
io.netty.channel.Channel channel = future.syncUninterruptibly().channel();
this.channel = new NettyChannel(channel);
}
@Override
public void close() {
if (channel != null) {
channel.close();
}
if (bootstrap != null) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private void init() {
this.serverHandler = new NettyChannelHandler(getAttribute(), this);
this.bootstrap = new ServerBootstrap();
if (useEpoll()) {
this.bossGroup = new EpollEventLoopGroup(1, HodorThreadFactory.create("netty-epoll-ServerBoss", false));
this.workerGroup = new EpollEventLoopGroup(getIoThreads(), HodorThreadFactory.create("netty-epoll-ServerWork", false));
serverSocketChannelClass = EpollServerSocketChannel.class;
} else {
this.bossGroup = new NioEventLoopGroup(1, HodorThreadFactory.create("netty-nio-ServerBoss", false));
this.workerGroup = new NioEventLoopGroup(getIoThreads(), HodorThreadFactory.create("netty-nio-ServerWork", false));
serverSocketChannelClass = NioServerSocketChannel.class;
}
}
private boolean useEpoll() {
return Epoll.isAvailable() && OSInfo.isLinux() && getUseEpollNative();
}
}
| 40.157895 | 131 | 0.717562 |
744ae28816357f03ad774a5f88f71b3f315eb1db | 6,228 | package com.digirati.elucidate.test.schema.w3c;
import org.junit.Test;
import com.digirati.elucidate.test.schema.AbstractSchemaValidatorTest;
public class W3CAnnotationValidatorTest extends AbstractSchemaValidatorTest {
@Override
protected String getSchemaFileName() {
return "/schema/w3c-annotation-schema.json";
}
@Test
public void validateExampleOne() throws Exception {
validateJson("/example-w3c-annotation/example1.jsonld");
}
@Test
public void validateExampleTwo() throws Exception {
validateJson("/example-w3c-annotation/example2.jsonld");
}
@Test
public void validateExampleThree() throws Exception {
validateJson("/example-w3c-annotation/example3.jsonld");
}
@Test
public void validateExampleFour() throws Exception {
validateJson("/example-w3c-annotation/example4.jsonld");
}
@Test
public void validateExampleFive() throws Exception {
validateJson("/example-w3c-annotation/example5.jsonld");
}
@Test
public void validateExampleSix() throws Exception {
validateJson("/example-w3c-annotation/example6.jsonld");
}
@Test
public void validateExampleSeven() throws Exception {
validateJson("/example-w3c-annotation/example7.jsonld");
}
@Test
public void validateExampleEight() throws Exception {
validateJson("/example-w3c-annotation/example8.jsonld");
}
@Test
public void validateExampleNine() throws Exception {
validateJson("/example-w3c-annotation/example9.jsonld");
}
@Test
public void validateExampleTen() throws Exception {
validateJson("/example-w3c-annotation/example10.jsonld");
}
@Test
public void validateExampleEleven() throws Exception {
validateJson("/example-w3c-annotation/example11.jsonld");
}
@Test
public void validateExampleTwelve() throws Exception {
validateJson("/example-w3c-annotation/example12.jsonld");
}
@Test
public void validateExampleThirteen() throws Exception {
validateJson("/example-w3c-annotation/example13.jsonld");
}
@Test
public void validateExampleFourteen() throws Exception {
validateJson("/example-w3c-annotation/example14.jsonld");
}
@Test
public void validateExampleFifteen() throws Exception {
validateJson("/example-w3c-annotation/example15.jsonld");
}
@Test
public void validateExampleSixteen() throws Exception {
validateJson("/example-w3c-annotation/example16.jsonld");
}
@Test
public void validateExampleSeventeen() throws Exception {
validateJson("/example-w3c-annotation/example17.jsonld");
}
@Test
public void validateExampleEighteen() throws Exception {
validateJson("/example-w3c-annotation/example18.jsonld");
}
@Test
public void validateExampleNineteen() throws Exception {
validateJson("/example-w3c-annotation/example19.jsonld");
}
@Test
public void validateExampleTwenty() throws Exception {
validateJson("/example-w3c-annotation/example20.jsonld");
}
@Test
public void validateExampleTwentyOne() throws Exception {
validateJson("/example-w3c-annotation/example21.jsonld");
}
@Test
public void validateExampleTwentyTwo() throws Exception {
validateJson("/example-w3c-annotation/example22.jsonld");
}
@Test
public void validateExampleTwentyThree() throws Exception {
validateJson("/example-w3c-annotation/example23.jsonld");
}
@Test
public void validateExampleTwentyFour() throws Exception {
validateJson("/example-w3c-annotation/example24.jsonld");
}
@Test
public void validateExampleTwentyFive() throws Exception {
validateJson("/example-w3c-annotation/example25.jsonld");
}
@Test
public void validateExampleTwentySix() throws Exception {
validateJson("/example-w3c-annotation/example26.jsonld");
}
@Test
public void validateExampleTwentySeven() throws Exception {
validateJson("/example-w3c-annotation/example27.jsonld");
}
@Test
public void validateExampleTwentyEight() throws Exception {
validateJson("/example-w3c-annotation/example28.jsonld");
}
@Test
public void validateExampleTwentyNine() throws Exception {
validateJson("/example-w3c-annotation/example29.jsonld");
}
@Test
public void validateExampleThirty() throws Exception {
validateJson("/example-w3c-annotation/example30.jsonld");
}
@Test
public void validateExampleThirtyOne() throws Exception {
validateJson("/example-w3c-annotation/example31.jsonld");
}
@Test
public void validateExampleThirtyTwo() throws Exception {
validateJson("/example-w3c-annotation/example32.jsonld");
}
@Test
public void validateExampleThirtyThree() throws Exception {
validateJson("/example-w3c-annotation/example33.jsonld");
}
@Test
public void validateExampleThirtyFour() throws Exception {
validateJson("/example-w3c-annotation/example34.jsonld");
}
@Test
public void validateExampleThirtyFive() throws Exception {
validateJson("/example-w3c-annotation/example35.jsonld");
}
@Test
public void validateExampleThirtySix() throws Exception {
validateJson("/example-w3c-annotation/example36.jsonld");
}
@Test
public void validateExampleThirtySeven() throws Exception {
validateJson("/example-w3c-annotation/example37.jsonld");
}
@Test
public void validateExampleThirtyEight() throws Exception {
validateJson("/example-w3c-annotation/example38.jsonld");
}
@Test
public void validateExampleThirtyNine() throws Exception {
validateJson("/example-w3c-annotation/example39.jsonld");
}
@Test
public void validateExampleFourty() throws Exception {
validateJson("/example-w3c-annotation/example40.jsonld");
}
@Test
public void validateExampleComplete() throws Exception {
validateJson("/example-w3c-annotation/example-complete.jsonld");
}
}
| 28.438356 | 77 | 0.691554 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.